Functions 101
Lambda Expressions
Small anonymous functions can be created with the lambda
keyword. This function returns the sum of its two arguments: lambda a, b: a+b
.
Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:
The above example uses a lambda expression to return a function. Another use is to pass a small function as an argument:
Here is an example showing implementing a compact addition function using lambda:
Decorators
A decorator is a function that creates a wrapper around another function. The primary purpose of this wrapping is to alter or enhance the behavior of the object being wrapped.
Syntactically, decorators are denoted using the special @
symbol as follows:
The preceding code is shorthand for the following:
In the example, a function func()
is defined. However, immediately after its definition, the function object itself is passed to the function decorate()
, which returns an object that replaces the original func
.
Consider the following example:
Output:
Map, Filter, and Reduce
Programmers familiar with functional languages often inquire about common list operations such as map, filter, and reduce. Much of this functionality is provided by list comprehensions and generator expressions.
Python provides a built-in map()
function that is the same as mapping a function with a generator expression:
The built-in filter()
function creates a generator that filters values:
If you want to accumulate or reduce values, you can use functools.reduce()
. The idea behind Python's reduce()
is to take an existing function, apply it cumulatively to all the items in an iterable, and generate a single final value:
Last updated