Is there a way in python to turn a try/except into a single line?
something like...
b = 'some variable'
a = c | b #try statement goes here
Where b
is a declared variable and c
is not... so c
would throw an error and a
would become b
...
This is terribly hackish, but I've used it at the prompt when I wanted to write up a sequence of actions for debugging:
exec "try: some_problematic_thing()\nexcept: problem=sys.exc_info()"
print "The problem is %s" % problem[1]
For the most part, I'm not at all bothered by the no-single-line-try-except restriction, but when I'm just experimenting and I want readline to recall a whole chunk of code at once in the interactive interpreter so that I can adjust it somehow, this little trick comes in handy.
For the actual purpose you are trying to accomplish, you might try locals().get('c', b)
; ideally it would be better to use a real dictionary instead of the local context, or just assign c to None before running whatever may-or-may-not set it.