你能不提供关键字参数而不提供默认值吗?

时间:2023-01-29 23:20:53

I am used to having function/method definitions like so in Python:

我习惯在Python中有这样的函数/方法定义:

def my_function(arg1=None , arg2='default'):
    ... do stuff here

If I don't supply arg1 (or arg2) then the default value of None (or `'default') is assigned.

如果我不提供arg1(或arg2),则分配默认值None(或“default”)。

Can I specify keyword arguments like this, but without a default? I would expect it to raise an error if the argument was not supplied.

我可以像这样指定关键字参数,但没有默认值吗?如果没有提供参数,我希望它会引发错误。

2 个解决方案

#1


7  

You can in modern Python (3, that is):

你可以在现代Python(3,即):

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "<ipython-input-5-08a2da4138f6>", line 1, in <module>
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "<ipython-input-7-14386ea74437>", line 1, in <module>
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob

#2


7  

Any argument can be given as with a keyword expression, whether or not it has a default:

任何参数都可以与关键字表达式一样给出,无论它是否具有默认值:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error

If you want to force the arguments to be keyword-only, then see DSM's answer, but that didn't seem like what you were really asking.

如果你想强制参数只是关键字,那么请参阅DSM的答案,但这似乎不是你真正要求的。

#1


7  

You can in modern Python (3, that is):

你可以在现代Python(3,即):

>>> def func(*, name1, name2):
...     print(name1, name2)
...     
>>> func()
Traceback (most recent call last):
  File "<ipython-input-5-08a2da4138f6>", line 1, in <module>
    func()
TypeError: func() missing 2 required keyword-only arguments: 'name1' and 'name2'    
>>> func("Fred", "Bob")
Traceback (most recent call last):
  File "<ipython-input-7-14386ea74437>", line 1, in <module>
    func("Fred", "Bob")
TypeError: func() takes 0 positional arguments but 2 were given

>>> func(name1="Fred", name2="Bob")
Fred Bob

#2


7  

Any argument can be given as with a keyword expression, whether or not it has a default:

任何参数都可以与关键字表达式一样给出,无论它是否具有默认值:

def foo(a, b):
    return a - b
foo(2, 1)         # Returns 1
foo(a=2, b=1)     # Returns 1
foo(b=2, a=1)     # Returns -1
foo()             # Raises an error

If you want to force the arguments to be keyword-only, then see DSM's answer, but that didn't seem like what you were really asking.

如果你想强制参数只是关键字,那么请参阅DSM的答案,但这似乎不是你真正要求的。