Have you ever found yourself looking at someone else's function and wondered what the argument *args, **kw, or **kwargs means / does?
Example:
def my_function(proto, *args, **kw):
# rest of the function code hereThose arguments are called "Keyword Arguments". Essentially, they are place holders for multiple arguments, and they are extremely useful especially when you need to pass a different number of arguments each time you call the function.
Example:
>> my_function('filter', 'python', 'html', start='now')
>> my_function('proto', 'filter')
>> my_function('ask', pg='2')args, kw, and kwargs themselves aren't "special", it's the asterisks (*) that makes it "special". One * will create a tuple out of all the one off arguments (e.g. 'filter'), where as the double ** will create a dictionary out of all the arguments that have an equals (e.g. start = 'now').
note: If you're using both the single (*) and double (**) asterisk in your function, the single (*) MUST come before the double.
A Simple Test
def kwargs(basic, *huh, **no_way):
print basic, huh, no_way
>> kwargs('proto', 'filter', '.com', a='pythonic', maybe='yes')
>> proto ('filter', '.com') {'a': 'pythonic', 'maybe': 'yes'}
>> kwargs('girls', yes='no')
>> girls () {'yes': 'no'}
So, if you don't want your functions to raise an TypeError or you need your functions to accept variable number of arguments, you can use "Keyword Arguments".


Comments
Post new comment