Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Star (*) as an argument in python function [duplicate]

Tags:

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 *?

like image 864
BiBi Avatar asked Dec 15 '18 20:12

BiBi


People also ask

What does * mean in Python argument?

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.

What does * mean in Python function?

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.

What does * mean Python function input?

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] .

What do double asterisks mean in Python?

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.


Video Answer


1 Answers

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 
like image 154
Adam Smith Avatar answered Oct 21 '22 15:10

Adam Smith