Python3: 如何在方法头中定义异常?
Python3: How to define exceptions in method headers?
昨天,我在 python 3(也许在 python 2 ;)中找到了一种模拟类似类型安全的方法。例如,通过编写以下内容:
def do_stuff(amount: int, name: str, place: str = 'London') -> list:
您可以让 IDE 通知您是否要设置一个不符合预期类型的参数(给出一个您希望为整数的字符串)。 Python 本身会忽略它们,这对我来说完全没问题。
但是,现在我想为它提供在此过程中可能抛出的异常。我怎样才能做到这一点?不幸的是,我什至不知道要搜索什么。有人可以帮我吗?我想让我的 IDE (PyCharm) 提醒我,在某些情况下,我使用的函数可能会抛出异常,最好将其包装在 try-except 语句中。
我只说自己写的方法,不是外部代码,仅供参考。不幸的是,reStructuredText 或 epytext 确实记录了这一点,但对 IDE-checks =Y
没有帮助
提前致谢
肯尼斯
这似乎不受支持。添加类型提示的提案 PEP484 说 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.
昨天,我在 python 3(也许在 python 2 ;)中找到了一种模拟类似类型安全的方法。例如,通过编写以下内容:
def do_stuff(amount: int, name: str, place: str = 'London') -> list:
您可以让 IDE 通知您是否要设置一个不符合预期类型的参数(给出一个您希望为整数的字符串)。 Python 本身会忽略它们,这对我来说完全没问题。
但是,现在我想为它提供在此过程中可能抛出的异常。我怎样才能做到这一点?不幸的是,我什至不知道要搜索什么。有人可以帮我吗?我想让我的 IDE (PyCharm) 提醒我,在某些情况下,我使用的函数可能会抛出异常,最好将其包装在 try-except 语句中。
我只说自己写的方法,不是外部代码,仅供参考。不幸的是,reStructuredText 或 epytext 确实记录了这一点,但对 IDE-checks =Y
没有帮助提前致谢 肯尼斯
这似乎不受支持。添加类型提示的提案 PEP484 说 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.