This is the last post in a series covering Pythonic code written by Michael Kennedy of Talk Python To Me . Be sure to catch the whole series with 5 powerful Pythonic recommendations and over 45 minutes of video examples.
Python treats functions as first class citizens. This provides a tonne of flexibility, but what exactly does it mean? Well, functions are basically instances of a type; just like the string ‘cat’ or the object ‘new_user’ created from the Customer class. With them we can:
- Pass functions between methods
- Compare them
- Create private closures using functions within functions
- And more…
The key part we want to focus upon is the first feature: Passing function between methods. This allows us to write code (methods or functions) that are not fully implemented but instead depend on the caller to supply the implementation.
PASSING FUNCTIONS BETWEEN METHODS
Here’s an example. The following method trims a sequence of numbers down to a smaller list and returns those numbers. But the method doesn’t decide which numbers matter. Rather the caller supplies a method to make that decision:
def find_special_numbers(special_selector, limit=10): found =  n = 0 while len(found) < limit: if special_selector(n): found.append(n) n += 1 return found
If we had a function like this that could determine whether a number was odd:
def check_for_odd(n): return n % 2 == 1
Then we could combine that to get just the odd numbers:
But writing separate methods for these adds no value and only detracts from our solution. That’s where lambda methods come in.
USING LAMBDA EXPRESSIONS
We can use lambda methods as small, inline blocks of code (which are just functions like any other) that are used directly where they are called. Here’s the same thing with lambdas (notice no other check method):
find_special_numbers(lambda i: i % 2 == 1, 25)
Nice huh? Lambdas solve a bunch of problems elegantly in Python. Check out this video to see them in action!
VIDEO: LAMBDA EXPRESSIONS
You can find the code for this video on GitHub .