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

如果我有这样的功能:

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

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

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

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

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

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

编辑:我不知道默认参数如何在Python中工作,但出于这个问题,我将保留上面的示例。通常,最好执行以下操作:

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

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 typing documentation or on a Google search.

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:

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

回答 0

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

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

print(foo.__annotations__)

这个输出

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

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

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

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 section makes it clear that keyword arguments works with function annotations in this way.

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


回答 1

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

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

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 None is allowed . From typing.Optional:

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

回答 2

我最近看到了这种单线:

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

I recently saw this one-liner:

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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。