Tutorial by Examples

You can use the star * when writing a function to collect all positional (ie. unnamed) arguments in a tuple: def print_args(farg, *args): print("formal arg: %s" % farg) for arg in args: print("another positional arg: %s" % arg) Calling method: print_args(1, &...
You can define a function that takes an arbitrary number of keyword (named) arguments by using the double star ** before a parameter name: def print_kwargs(**kwargs): print(kwargs) When calling the method, Python will construct a dictionary of all keyword arguments and make it available in ...
A common use case for *args in a function definition is to delegate processing to either a wrapped or inherited function. A typical example might be in a class's __init__ method class A(object): def __init__(self, b, c): self.y = b self.z = c class B(A): def __init__(...
You can use a dictionary to assign values to the function's parameters; using parameters name as keys in the dictionary and the value of these arguments bound to each key: def test_func(arg1, arg2, arg3): # Usual function with three arguments print("arg1: %s" % arg1) print("a...
The effect of using the * operator on an argument when calling a function is that of unpacking the list or a tuple argument def print_args(arg1, arg2): print(str(arg1) + str(arg2)) a = [1,2] b = tuple([3,4]) print_args(*a) # 12 print_args(*b) # 34 Note that the length of the starr...
Python 3 allows you to define function arguments which can only be assigned by keyword, even without default values. This is done by using star * to consume additional positional parameters without setting the keyword parameters. All arguments after the * are keyword-only (i.e. non-positional) arg...
def foobar(foo=None, bar=None): return "{}{}".format(foo, bar) values = {"foo": "foo", "bar": "bar"} foobar(**values) # "foobar"
To use default values with **kwargs def fun(**kwargs): print kwargs.get('value', 0) fun() # print 0 fun(value=1) # print 1

Page 1 of 1