python-3.x - 在Python中,如何输入提示具有空默认值的列表?

标签 python-3.x type-hinting default-arguments

我想创建一个如下所示的函数,但我知道默认参数永远不应该是可变的:

def foo(req_list: list, opt_list: list = []): 
    ...

如果没有类型提示,我知道将可选参数默认为空列表的方法是:

def bar(req_list, opt_list=None):
    if opt_list == None:
        opt_list = []
    ...

但我不确定使用类型提示执行此操作的正确方法。

最佳答案

你所拥有的在语义上是正确的。尽管我会这样做,但有点呼应你的第二个代码块。

def foo(req_list: list, opt_list: list | None = None):
    if opt_list is None:
        opt_list = []
    ...

关于python-3.x - 在Python中,如何输入提示具有空默认值的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71431701/

相关文章:

php - 根据先前的参数获取默认参数的值

c++ - 我是否错误地使用了默认参数?

c++ - 在 C++ 中将默认参数值放在哪里?

python - 如何在没有任何 shell 脚本的情况下运行新进程并与其建立连接?

python-3.x - 可选类型注释。检查是否为“无”后使用值?

python-3.x - 'Shuffle' 被认为是 model_selection.train_test_split 的无效参数

python - 使用内置 map 功能打字

python - 为需要 kwargs 的 Callable 输入提示

python - 如何在 django 命令中实现应用程序命名空间?

Python 3.0 和语言演变