Python: try statement in a single line

前端 未结 13 1615
囚心锁ツ
囚心锁ツ 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:48

    The problem is that its actually a django model.objects.get query i am trying to test. the .get returns an error if no data is found... it doesn't return None (which annoys me)

    Use something like this:

    print("result:", try_or(lambda: model.objects.get(), ''))
    

    Where try_or is an utility function defined by you:

    def try_or(fn, default):
        try:
            return fn()
        except:
            return default
    

    Optionally you can restrict the accepted exception types to NameError, AttributeError, etc.

提交回复
热议问题