Oct-10-2019, 07:05 AM
def myfunc(n): return lambda a : a * nis similar to this:
def myfunc(n): def inner(a): return a * n return innerIn both cases the function
myfunc
returns a function
.The lambda expression is an anonymous function. In both cases the function
myfunc
is a closure.This means inside the function is another one, which has access to the stack of the parant function.
Calling this function looks strange:
n = 10 a = 20 result = myfunc(n)(a) print(result)You can bring this back a normal form:
def myfunc(n, a): return a * nCalling it:
result = myfunc(10,20)Closures are used for decorators and functional style. For example inside the
operator
module are this kind of closures available.import operator # list with dicts mylist1 = [dict(value=10, name='c'), dict(value=20, name='b'), dict(value=30, name='a')] # we want to sort by name, no problem: by_name = sorted(mylist1, key=operator.itemgetter('name')) by_value = sorted(mylist1, key=operator.itemgetter('value'))The sorted function uses the
key
to sort. It must be a callable and for each item in the list, the callable is called with. The callable should return something, that can be used for sorting. For example it may return str, then it's sorted lexically or it returns numbers or tuples with numbers. Mostly you see in examples for sorting the lambda expression.In tutorials about sorting, you see often this:
by_name = sorted(mylist1, key=lambda x: x['name']) by_value = sorted(mylist1, key=lambda x: x['value'])Another thing you have to know, that functions return implicit
None
.def foo(): print('Hello foo') ret_val = foo() print(f"Return value of foo is: {ret_val}\nIt's type is: {type(ret_val)}")
Output:Hello foo
Return value of foo is: None
It's type is: <class 'NoneType'>
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!