Raise error in Python, exclude last level in stack trace

So, I am developing this class with an index. I would like to throw (or "raise" in Python lingo) an IndexError exception. Well, thatโ€™s pretty trivial,

if errorCondition: raise IndexError("index out of range") 

However, when this code runs in the console and an error occurs, the stack trace also includes the line where the error occurs:

 Traceback (most recent call last): File "code.py", line 261, in <module> print myCards[99] File "Full/Path/To/The/module.py", line 37, in __getitem__ raise IndexError("item index out of range") IndexError: item index out of range 

I find this odd, I would like to hide the internal work of my class from the executor, not to give out information about extracting the file, line and code from the external module.

Is there any way to handle this? The whole point of raising the error is to provide enough information to describe why the function call went wrong, and not where the error occurred inside the external code.

+4
source share
1 answer

If you distribute your code as .pyc bytecode files (usually automatically generated upon the first import of the module) or create a wrong path for .py source files for the created .pyc files (by moving / deleting source files), the stack trace will skip lines source code.

You can control the creation of bytecode files using the compileall stdlib module: http://docs.python.org/2/library/compileall.html

According to commentators, this is unusual - additional information can save valuable time by debugging a production problem.

+4
source

All Articles