Python: try statement in a single line

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

    if you need to actually manage exceptions:
    (modified from poke53280's answer)

    >>> def try_or(fn, exceptions: dict = {}):
        try:
            return fn()
        except Exception as ei:
            for e in ei.__class__.__mro__[:-1]:
                if e in exceptions: return exceptions[e]()
            else:
                raise
    
    
    >>> def context():
        return 1 + None
    
    >>> try_or( context, {TypeError: lambda: print('TypeError exception')} )
    TypeError exception
    >>> 
    

    note that if the exception is not supported, it will raise as expected:

    >>> try_or( context, {ValueError: lambda: print('ValueError exception')} )
    Traceback (most recent call last):
      File "", line 1, in 
        try_or( context, {ValueError: lambda: print('ValueError exception')} )
      File "", line 3, in try_or
        return fn()
      File "", line 2, in context
        return 1 + None
    TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
    >>> 
    

    also if Exception is given, it will match anything below.
    (BaseException is higher, so it will not match)

    >>> try_or( context, {Exception: lambda: print('exception')} )
    exception
    

提交回复
热议问题