5

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.

Passiday
  • 7,573
  • 8
  • 42
  • 61
  • 2
    Check out http://stackoverflow.com/questions/4419785/dont-show-python-raise-line-in-the-exception-stack?rq=1 It might help – TerryA Mar 16 '13 at 11:34
  • 1
    A stack trace that candidly tells you what and where has happened is immensely helpful, both for code maintainer reading bug reports and developer using your library. You can't hide the source anyway, why bother obfuscating your stack traces? – 9000 Mar 16 '13 at 11:40
  • 1
    Well, it's just.. unusual, comparing to some other programming languages I have background in. I thought if I can't see source when list[index] triggers IndexError, why should my code be more open. But I can swallow this, if this is cultural for Python. – Passiday Mar 16 '13 at 12:28

1 Answers1

5

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.

babbageclunk
  • 8,523
  • 1
  • 33
  • 37