Python: try statement in a single line

前端 未结 13 1617
囚心锁ツ
囚心锁ツ 2020-12-01 03:47

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
<         


        
13条回答
  •  情歌与酒
    2020-12-01 04:39

    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.

提交回复
热议问题