【发布时间】:2021-04-19 22:03:48
【问题描述】:
我在 python 中有一些函数,我需要验证某些参数是否为None,否则引发异常。目前我的解决方案是:
def notnone(arg):
if arg == None:
raise Exception()
return arg
def example_function(..., a, ...):
a = notnone(a)
...
在python中,有没有更优雅的解决方案?和装饰器一样优雅的功能?我在想像下面这样的事情(虽然我知道这行不通):
def example_function(..., @notnone a, ...):
...
【问题讨论】:
-
不,Python 语法不支持参数上的装饰器。
-
你最好的选择可能是类型注释。
标签: python design-patterns decorator