I was looking at the definition of the glob
function and I noticed that the second argument was simply *
.
def glob(pathname, *, recursive=False): """Return a list of paths matching a pathname pattern. [...] """ return list(iglob(pathname, recursive=recursive))
What is the point of the *
?
Python has *args which allow us to pass the variable number of non keyword arguments to function. In the function, we should use an asterisk * before the parameter name to pass variable length arguments.
The asterisk (star) operator is used in Python with more than one meaning attached to it. For numeric data types, * is used as multiplication operator >>> a=10;b=20 >>> a*b 200 >>> a=1.5; b=2.5; >>> a*b 3.75 >>> a=2+3j; b=3+2j >>> a*b 13j.
It means that the function takes zero or more arguments and the passed arguments would be collected in a list called formulation . For example, when you call sum(1, 2, 3, 4) , formation would end up being [1, 2, 3, 4] .
In a function definition, the double asterisk is also known **kwargs. They used to pass a keyword, variable-length argument dictionary to a function. The two asterisks (**) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.
The *
indicates the end of the positional arguments. Every argument after that can only be specified by keyword. This is defined in PEP 3102
>>> def foo1(a, b=None): ... print(a, b) ... >>> def foo2(a, *, b=None): ... print(a, b) ... >>> foo1(1, 2) 1 2 >>> foo2(1, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: foo1() takes 1 positional argument but 2 were given >>> foo2(1, b=2) 1 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With