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