在 Python 中使用类型提示添加默认参数值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38727520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:21:13  来源:igfitidea点击:

Adding default parameter value with type hint in Python

pythonpython-3.xtype-hinting

提问by josh

If I have a function like this:

如果我有这样的功能:

def foo(name, opts={}):
  pass

And I want to add type hints to the parameters, how do I do it? The way I assumed gives me a syntax error:

我想给参数添加类型提示,我该怎么做?我假设的方式给了我一个语法错误:

def foo(name: str, opts={}: dict) -> str:
  pass

The following doesn't throw a syntax error but it doesn't seem like the intuitive way to handle this case:

以下不会引发语法错误,但它似乎不是处理这种情况的直观方法:

def foo(name: str, opts: dict={}) -> str:
  pass

I can't find anything in the typingdocumentationor on a Google search.

我在typing文档或 Google 搜索中找不到任何内容。

Edit: I didn't know how default arguments worked in Python, but for the sake of this question, I will keep the examples above. In general it's much better to do the following:

编辑:我不知道 Python 中的默认参数是如何工作的,但是为了这个问题,我将保留上面的示例。一般来说,最好执行以下操作:

def foo(name: str, opts: dict=None) -> str:
  if not opts:
    opts={}
  pass

回答by no?????z???

Your second way is correct.

你的第二种方法是正确的。

def foo(opts: dict = {}):
    pass

print(foo.__annotations__)

this outputs

这输出

{'opts': <class 'dict'>}

It's true that's it's not listed in PEP 484, but type hints are an application of function annotations, which are documented in PEP 3107. The syntax sectionmakes it clear that keyword arguments works with function annotations in this way.

确实,它没有在PEP 484 中列出,但类型提示是函数注释的应用,在 PEP 3107 中记录。语法部分清楚地表明关键字参数以这种方式与函数注释一起使用。

I strongly advise against using mutable keyword arguments. More information here.

我强烈建议不要使用可变关键字参数。更多信息在这里

回答by Tomasz Bartkowiak

If you're using 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 Noneis allowed . From typing.Optional:

如果您使用的是输入(在 Python 3.5 中引入),您可以使用typing.Optional,其中Optional[X]等效于Union[X, None]. 它用于表示None允许的显式值。从打字。可选

def foo(arg: Optional[int] = None) -> None:
    ...

回答by Kirkalicious

I recently saw this one-liner:

我最近看到了这个单行:

def foo(name: str, opts: dict=None) -> str:
    opts = {} if not opts else opts
    pass