Python: How can I know which exceptions might be thrown from a method call

前端 未结 7 1315
感情败类
感情败类 2020-11-28 05:43

Is there a way knowing (at coding time) which exceptions to expect when executing python code? I end up catching the base Exception class 90% of the time since I don\'t kno

7条回答
  •  隐瞒了意图╮
    2020-11-28 05:56

    I guess a solution could be only imprecise because of lack of static typing rules.

    I'm not aware of some tool that checks exceptions, but you could come up with your own tool matching your needs (a good chance to play a little with static analysis).

    As a first attempt, you could write a function that builds an AST, finds all Raise nodes, and then tries to figure out common patterns of raising exceptions (e. g. calling a constructor directly)

    Let x be the following program:

    x = '''\
    if f(x):
        raise IOError(errno.ENOENT, 'not found')
    else:
        e = g(x)
        raise e
    '''
    

    Build the AST using the compiler package:

    tree = compiler.parse(x)
    

    Then define a Raise visitor class:

    class RaiseVisitor(object):
        def __init__(self):
            self.nodes = []
        def visitRaise(self, n):
            self.nodes.append(n)
    

    And walk the AST collecting Raise nodes:

    v = RaiseVisitor()
    compiler.walk(tree, v)
    
    >>> print v.nodes
    [
        Raise(
            CallFunc(
                Name('IOError'),
                [Getattr(Name('errno'), 'ENOENT'), Const('not found')],
                None, None),
            None, None),
        Raise(Name('e'), None, None),
    ]
    

    You may continue by resolving symbols using compiler symbol tables, analyzing data dependencies, etc. Or you may just deduce, that CallFunc(Name('IOError'), ...) "should definitely mean raising IOError", which is quite OK for quick practical results :)

提交回复
热议问题