Python Functions with some tricks
- 1 minDefine functions is one of basic Python skills. I would like to focus on closure and its tricks.
Metadata
We can add some annotations on function in order to let programmers know how this function should be used.
Python interpreter wouldn’t give any semantic meaning on these statement. They are not type checks mechanism. However, they still give other maintainers enough clues to track code.
If functions have multiple values to return, they are packed in tuple and returned.
Default value in parameters
Indicated default values should always be immutable objects Like None, True, False, number or string
Capture variable in lambda
Using functools.partial
Closure
When do we have a closure?
- We must have a nested function (function inside a function).
- The nested function must refer to a value defined in the enclosing function.
- The enclosing function must return the nested function.
When to use closures?
Closures can avoid the use of global values and provides some form of data hiding. It can also provide an object oriented solution to the problem.
We may want to replace single-method class with closure.
We may also want our callback functions to bring additional information
Reference
[1] Python Closures [2] Python cookbook 3rd version