1

I would like to know the shortest possible way to throw an exception in Python that is not itself a SyntaxError.

For context, I use an IPython shell for development while editing the source in a different file and use live reload to bring in the changes. To set a break point in code, I usually insert import ipdb; ipdb.set_trace() to where I need the break point. A different way is triggering an arbitrary Exception, then use the %debug magic command on the interpreter to enter post-mortem debugging. I usually use 1/0 for this purpose, which raises a ZeroDivisionError. SyntaxError on the other hand is precluded, because then the program would not run at all.

The shortest one I can think of is using a non-existent variable, such as a, which results in a NameError: name 'a' is not defined. However this is not guaranteed to always work and requires me to be aware of the current scope. Is there a better way?

kimegitee
  • 11
  • 1
  • 1
    why not just `raise Exception`? Why does the length matter? – juanpa.arrivillaga Dec 05 '22 at 19:01
  • I think just a raise Exception may not work, especially if the code is already dealing with exceptions. The author is just looking for an effortless way to get into debug mode using IPythonShell – WombatPM Dec 05 '22 at 19:06
  • @WombatPM why wouldn't explicitly raising an exception work but doing an operation that results in an exception being raised not be a problem? That doesn't make any sense. The OP seems to just be interested in playing code golf – juanpa.arrivillaga Dec 06 '22 at 00:35
  • 1
    Oh it will work most of the time. But he’s not stepping through code line by line. So if he places a raises an exception that is handled by code he will not get the break into the debugger he is looking for. Bottom line he should just suck it up and set breakpoints if he wants to debug. For the record his intentional division by zero suffers the same problem – WombatPM Dec 06 '22 at 07:51
  • If you worry about code that may catch your ZeroDivisionError and NameError, then create your own : `class MyOwnException(Exception): pass` then `raise MyOwnException` on the next line. It would be only caught by (unusual) `except Exception`. In this case you can instead inherit from `BaseException`. But otherwise I agree with the previous commenters. Myself I use `1/0` regularly. – Lenormju Dec 06 '22 at 11:34

0 Answers0