Python: try statement in a single line

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

提交回复
热议问题