Is there a way to ‘detect’ what exceptions function/method raises? Examplifying:
def foo():
print 'inside foo, next calling bar()'
_bar()
_baz()
# lots of other methods calls which raise other legitimate exceptions
def _bar():
raise my_exceptions.NotFound
def _baz():
raise my_exceptions.BadRequest
so, supposing that foo is part of my API and I need to document it, is there a way to get all exceptions that can be raised from it?
Just to be clear I don’t want to handle those exceptions, they are supposed to happen (when a resource is not found or the request is malformed for instance).
I’m thinking to create some tool that transform that sequence of code in something ‘inline’ like:
def foo():
print 'inside foo, next calling bar()'
# what _bar() does
raise my_exceptions.NotFound
# what _baz() does
raise my_exceptions.BadRequest
# lots of other methods calls which raise other legitimate exceptions
Is there anything that can help me detect that instead of navigate through each method call? (Which goes deep into several files.)
You can’t reasonably do this with Python, for a few reasons:
1) The Python primitives don’t document precisely what exceptions they can throw. The Python ethos is that anything can throw any exception at any time.
2) Python’s dynamic nature makes it very difficult to statically analyze code at all, it’s pretty much impossible to know what code “might” do.
3) All sorts of uninteresting exceptions would have to be in the list, for example, if you have
self.foo, then it could raise AttributeError. It would take a very sophisticated analyzer to figure out thatfoomust exist.