使用类型提示时如何向函数添加默认参数? [英] How do I add default parameters to functions when using type hinting?

查看:26
本文介绍了使用类型提示时如何向函数添加默认参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的功能:

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

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

I can't find anything in the typing documentation or on a Google search.

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

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

推荐答案

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

Your second way is correct.

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

print(foo.__annotations__)

这个输出

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

确实,PEP 484 中没有列出,但类型提示是函数的应用注释,记录在 PEP 3107 中.语法部分明确说明关键字参数有效以这种方式使用函数注释.

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.

这篇关于使用类型提示时如何向函数添加默认参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆