Python Functions with some tricks

- 1 min

Define functions is one of basic Python skills. I would like to focus on closure and its tricks.


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


When do we have a closure?

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


[1] Python Closures [2] Python cookbook 3rd version

Vic Yang

Vic Yang

Back-end Engineer

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora