Kenneth K. Kenneth K. - 1 year ago 143
Python Question

Python3: How to define exceptions in method headers?

yesterday, I found a way to simulate something like type-safety in python 3 (and maybe in python 2 ;). For example by writing the following:

def do_stuff(amount: int, name: str, place: str = 'London') -> list:

you can tell your IDE to notify you if you want to set an argument which has not the expected type (giving a string where you would expect an integer). Python itself ignores them, which is totally fine for me.

However, now I want to provide it with exceptions which may be thrown during the process. How can I achieve this? Unfortunately, I don't even know what to search for. Can someone help me out? I want my IDE (PyCharm) to remind me, that in some cases the function I'm using may throw an exception and it would be a nice idea to wrap it in a try-except statement.

I'm only talking about methods written by myself, not external code and it's for documentation only. Unfortunately reStructuredText or epytext do document this, but don't help with the IDE-checks =Y

Thanks in advance

Answer Source

This does not appear to be supported. The proposal that added type hinting, PEP484, says this about exceptions:

No syntax for listing explicitly raised exceptions is proposed. Currently the only known use case for this feature is documentational, in which case the recommendation is to put this information in a docstring.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download