Functions in Python: Arguments, Lambdas, Decorators, Generators
Functions in Python: Arguments, Lambdas, Decorators, Generators
>>> f()
()
{}
>>> f(1,2,3)
(1, 2, 3)
{}
>>> f(a=1, c=3, b=2)
()
{'a': 1, 'c': 3, 'b': 2}
>>> f(1, b=2, c=3)
(1,)
{'c': 3, 'b': 2}
Default arguments
>>> def func(a=5):
... print a
>>> func()
5
>>> func(6)
6
>>> func()
5
Default arguments - part II
>>> def func(a=[]):
... print a
>>> func()
[]
>>> func(['a'])
['a']
>>> func()
[]
Default arguments - part III
>>> def func(a=[]):
... a = a * 5
... print a
>>> func()
[]
>>> func()
[]
>>> func([1])
[1, 1, 1, 1, 1]
>>> func()
[]
Default arguments - part IV - problem
>>> def func(a=[]):
... a.append(2)
... print a
>>> func()
[2]
>>> func()
[2, 2]
>>> func([1])
[1, 2]
>>> func()
[2, 2, 2]
Default arguments - part V - solution
>>> def func(a=None):
... a = a or []
... a.append(2)
... print a
...
>>> func()
[2]
>>> func()
[2]
Preloading arguments
>>> def func(a, b, c):
... print a, b, c
>>> func_preloader(b=2)
523
Preloading arguments - mixing
>>> def func(a, b, c):
... print a, b, c
>>> func_preloader(2)
TypeError: func() got multiple values for keyword argument 'a'
Python introspection
>>> help(func)
Help on function func in module __main__:
func(a, b, c)
Just an example how introspection works
Methods related to introspection
● type(var) # show the type of the object
● dir(var) # lists object's methods and attributes
● id(var) # return object specific identificator
● getattr(obj, <attribute name>, <default value>)
● hasattr(obj, <attribute name>)
● globals()
● locals()
● callable(obj) # returns True if the object is callable
Lambda functions
>>> f = lambda x,y: x+y
>>> f(1,2)
3
# Python 3.2.3
>>> f = lambda x: print(x) # print is a function
>>> f(5)
5
Lambdas usage
>>> map(lambda x: x**2, range(5))
[0, 1, 4, 9, 16]
>>> a()
<generator object a at 0x158caa0>
>>> a()
<generator object a at 0x158caa0>
Generators - range vs xrange
>>> range(10**10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
MemoryError
>>> xrange(10**10)
xrange(10000000000)
>>> @decorator(debug=False)
... def f(a, b, c):
... return a + b + c
...
>>> f(1, 2, 3)
6
Q&A
Problems to solve
1) Create a function that accept both positional and
keyword arguments and returns their sum