Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the use of * in python function definition? [duplicate]

Tags:

python

def iglob(pathname, *, recursive=False):
"""Return an iterator which yields the paths matching a pathname pattern.

The pattern may contain simple shell-style wildcards a la
fnmatch. However, unlike fnmatch, filenames starting with a
dot are special cases that are not matched by '*' and '?'
patterns.

If recursive is true, the pattern '**' will match any files and
zero or more directories and subdirectories.
"""
it = _iglob(pathname, recursive)
if recursive and _isrecursive(pathname):
    s = next(it)  # skip empty string
    assert not s
return it

When i browse the glob's code in python3.5.1, the function defined here, why there is a * in the function parameter list. And if i pass three parameters to this function the TypeError raised, what's the effect of the *? thanks first.

like image 728
inmove shawn Avatar asked Apr 07 '16 05:04

inmove shawn


1 Answers

In python 3 you can specify * barely to force parameters after that as keyword only arguments:

>>>def fn(arg1, arg2, *, kwarg1, kwarg2):
...     print(arg1, arg2, kwarg1, kwarg2)
... 
>>> fn(1, 2, 3, 4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fn() takes 2 positional arguments but 4 were given
>>> fn(1, 2, kwarg1=3, kwarg2=4)
1 2 3 4
>>> 

Here in this example it forces kwarg1 and kwarg2 to sent as keyword arguments only.

like image 81
riteshtch Avatar answered Nov 14 '22 23:11

riteshtch