Python: try statement in a single line

Brant picture Brant · Mar 26, 2010 · Viewed 99.1k times · Source

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...

Answer

Walter Mundt picture Walter Mundt · Nov 9, 2011

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.