Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you have keyword arguments without supplying a default value?

I am used to having function/method definitions like so in 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.

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

like image 695
wobbily_col Avatar asked Mar 13 '15 16:03

wobbily_col


2 Answers

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

>>> 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
like image 71
DSM Avatar answered Sep 27 '22 23:09

DSM


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.

like image 44
Dolda2000 Avatar answered Sep 27 '22 22:09

Dolda2000