Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python method/function arguments starting with asterisk and dual asterisk [duplicate]

Tags:

python

I am not able understand where does these type of functions are used and how differently these arguments work from the normal arguments. I have encountered them many time but never got chance to understand them properly.

Ex:

def method(self, *links, **locks):     #some foo     #some bar     return 

I know i could have search the documentation but i have no idea what to search for.

like image 929
Shiv Deepak Avatar asked Nov 29 '10 17:11

Shiv Deepak


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 before an argument in Python?

The asterisk is an operator in Python that is commonly known as the multiplication symbol when used between two numbers ( 2 * 3 will produce 6 ) but when it is inserted at the beginning of a variable, such as an iterable, like a list or dictionary, it expands the contents of that variable.

What is asterisk in Python function argument?

In Python, the single-asterisk form of *args can be used as a parameter to send a non-keyworded variable-length argument list to functions. It is worth noting that the asterisk ( * ) is the important element here, as the word args is the established conventional idiom, though it is not enforced by the language.

What happens when we prefix a parameter with an asterisk (*) in Python?

The asterisk (star) operator is used in Python with more than one meaning attached to it. Single asterisk as used in function declaration allows variable number of arguments passed from calling environment. Inside the function it behaves as a tuple.


1 Answers

The *args and **keywordargs forms are used for passing lists of arguments and dictionaries of arguments, respectively. So if I had a function like this:

def printlist(*args):     for x in args:         print(x) 

I could call it like this:

printlist(1, 2, 3, 4, 5)  # or as many more arguments as I'd like 

For this

def printdict(**kwargs):     print(repr(kwargs))  printdict(john=10, jill=12, david=15) 

*args behaves like a list, and **keywordargs behaves like a dictionary, but you don't have to explicitly pass a list or a dict to the function.

See this for more examples.

like image 164
Rafe Kettler Avatar answered Sep 20 '22 17:09

Rafe Kettler