Python: try statement in a single line

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

    Version of poke53280 answer with limited expected exceptions.

    def try_or(func, default=None, expected_exc=(Exception,)):
        try:
            return func()
        except expected_exc:
            return default
    

    and it could be used as

    In [2]: try_or(lambda: 1/2, default=float('nan'))
    Out[2]: 0.5
    
    In [3]: try_or(lambda: 1/0, default=float('nan'), expected_exc=(ArithmeticError,))
    Out[3]: nan
    
    In [4]: try_or(lambda: "1"/0, default=float('nan'), expected_exc=(ArithmeticError,))
    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    [your traceback here]
    TypeError: unsupported operand type(s) for /: 'str' and 'int'
    
    In [5]: try_or(lambda: "1"/0, default=float('nan'), expected_exc=(ArithmeticError, TypeError))
    Out[5]: nan
    
    0 讨论(0)
  • 2020-12-01 04:44

    Here is a simpler version of the answer provided by @surendra_ben

    a = "apple"
    ​
    try: a.something_that_definitely_doesnt_exist
    except: print("nope")
    
    ...
    
    nope
    
    0 讨论(0)
  • 2020-12-01 04:45

    Another way is to define a context manager:

    class trialContextManager:
        def __enter__(self): pass
        def __exit__(self, *args): return True
    trial = trialContextManager()
    

    Then use the with statement to ignore errors in one single line:

    >>> with trial: a = 5      # will be executed normally
    >>> with trial: a = 1 / 0  # will be not executed and no exception is raised
    >>> print a
    5
    

    No exception will be raised in case of a runtime error. It's like a try: without the except:.

    0 讨论(0)
  • 2020-12-01 04:45

    How about using two lines. is it ok ?

    >>> try: a = 3; b= 0; c = a / b
    ... except : print('not possible'); print('zero division error')
    ...
    not possible
    zero division error
    
    0 讨论(0)
  • 2020-12-01 04:47

    You can do it by accessing the namespace dict using vars(), locals(), or globals(), whichever is most appropriate for your situation.

    >>> b = 'some variable'
    >>> a = vars().get('c', b)
    
    0 讨论(0)
  • 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(), '<n/a>'))
    

    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.

    0 讨论(0)
提交回复
热议问题