Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raise an error in Python, exclude the last level in stack trace [duplicate]

So, I am developing this class that has an indexer. I'd 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 is run in console and error happens, the stack trace includes also the line where the error is raised:

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 kind of odd, I'd like to hide the inner workings of my class from the implementer, not give out an information about the file, row and code extract from an external module.

Is there some way to manage this? All the point of raising error is to provide enough information to describe why the function call went wrong, not where inside the external code the error was raised.

like image 503
Passiday Avatar asked Mar 16 '13 11:03

Passiday


1 Answers

If you distribute your code as .pyc bytecode files (ordinarily auto-generated on first import of a module), or contrive for the generated .pyc files to not have the correct path to the .py source files (by moving/removing the source files), the stack trace will omit the source code lines.

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

As commenters have pointed out, this is unusual - the extra information can save valuable time debugging a production problem.

like image 189
babbageclunk Avatar answered Oct 29 '22 17:10

babbageclunk