what is *args/**kw


Fri Oct 07 2022 11:22:29 GMT+0000 (UTC)

Saved by @quaie #python

I've been reading the following example, and couldn't figure out, what
**kw mean. (It's an empty dictionary, but what's the semantics):
It's a keyword argument. It's some kind of repository for arguments
that aren't recognized.

If you have function like this:
def func(a, *args, *kw):
	print a
	print args
	print kw

and you call the functin like this:

func('value A', 'value B', 'value C', argumentA = 'value D', argumentB = 'value D')

the extra arguments would normally raise an error, but with the * and **, Python would:
- assign 'value B' and 'value C' to args
- assign 'argumentA':'value D' and 'argumentB':'value E' to kw

so if you run the function, it will output:
value A
('value B', 'value C')
{'argumentB': 'value E', 'argumentA': 'value D'}

the args and kw can be accessed like a tuple and dictionary respectively