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

时间:2021-07-24 17:42:38

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:

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

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

1 个解决方案

#1


65  

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.

确实,PEP 484中没有列出它,但是类型提示是函数注释的应用程序,在PEP 3107中有记录。语法部分明确指出,关键字参数是通过这种方式与函数注释一起工作的。

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

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

#1


65  

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.

确实,PEP 484中没有列出它,但是类型提示是函数注释的应用程序,在PEP 3107中有记录。语法部分明确指出,关键字参数是通过这种方式与函数注释一起工作的。

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

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