使用类型提示时如何向函数添加默认参数?
How do I add default parameters to functions when using type hinting?
如果我有这样的函数:
def foo(name, opts={}):
pass
我想为参数添加类型提示,我该怎么做?我假设的方式给我一个语法错误:
def foo(name: str, opts={}: dict) -> str:
pass
以下不会引发语法错误,但它似乎不是处理这种情况的直观方法:
def foo(name: str, opts: dict={}) -> str:
pass
我在 typing
documentation 或 Google 搜索中找不到任何内容。
编辑:我不知道 Python 中的默认参数是如何工作的,但为了这个问题,我将保留上面的例子。一般来说,执行以下操作会更好:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
你的第二种方法是正确的。
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
这个输出
{'opts': <class 'dict'>}
的确,PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section 中没有列出,这表明关键字参数以这种方式与函数注释一起使用。
我强烈建议不要使用可变关键字参数。更多信息 here.
我最近看到这个one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
如果您正在使用 typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...
如果我有这样的函数:
def foo(name, opts={}):
pass
我想为参数添加类型提示,我该怎么做?我假设的方式给我一个语法错误:
def foo(name: str, opts={}: dict) -> str:
pass
以下不会引发语法错误,但它似乎不是处理这种情况的直观方法:
def foo(name: str, opts: dict={}) -> str:
pass
我在 typing
documentation 或 Google 搜索中找不到任何内容。
编辑:我不知道 Python 中的默认参数是如何工作的,但为了这个问题,我将保留上面的例子。一般来说,执行以下操作会更好:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
你的第二种方法是正确的。
def foo(opts: dict = {}):
pass
print(foo.__annotations__)
这个输出
{'opts': <class 'dict'>}
的确,PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax section 中没有列出,这表明关键字参数以这种方式与函数注释一起使用。
我强烈建议不要使用可变关键字参数。更多信息 here.
我最近看到这个one-liner:
def foo(name: str, opts: dict=None) -> str:
opts = {} if not opts else opts
pass
如果您正在使用 typing (introduced in Python 3.5) you can use typing.Optional
, where Optional[X]
is equivalent to Union[X, None]
. It is used to signal that the explicit value of None
is allowed . From typing.Optional:
def foo(arg: Optional[int] = None) -> None:
...