Funky functions
Lambda
Who has seen lambda in Python code?
>>> lowercase = lambda s: s.lower()
Lambda expressions create lambda functions.
Lambda functions are objects that can be passed around:
>>> lowercase
<function <lambda> at 0x...>
So we could pass a lambda function into another function which would then use our lambda function for some specific purpose.
For example, Python’s built-in sorted function accepts an optional key argument that’s expected to be a function which returns the value to sort each item by.
Here we’re sorting a list of strings case insensitively by using our lowercase lambda function:
>>> fruits = ['Lemon', 'apple', 'lime', 'pear', 'Watermelon', 'BANANA']
>>> sorted(fruits, key=lowercase)
['apple', 'BANANA', 'Lemon', 'lime', 'pear', 'Watermelon']
So lambda expressions create functions… but we already have a much more common syntax for creating functions in Python.
A def expression:
>>> def lowercase(s): return s.lower()
So what makes lambda special?
First-class functions
You might think that lambda functions are special because they can be passed into other functions. But that’s actually true of any in Python:
>>> def lowercase(s): return s.lower()
>>> sorted(fruits, key=lowercase)
['apple', 'BANANA', 'Lemon', 'lime', 'pear', 'Watermelon']
Functions in Python can be passed around because functions are objects in Python.
It doesn’t matter whether a function is made with lambda or with def.
The thing that’s special about lambda expressions is that they’re expressions.
Instead of writing two of lines of code to sort by lowercase strings, we could use one of code:
>>> sorted(fruits, key=lambda s: s.lower())
['apple', 'BANANA', 'Lemon', 'lime', 'pear', 'Watermelon']
We’re defining a function and then passing that function into another function all in one line of code.
The def statement defines a function, but it’s a statement and not an expression.
An expression can be embedded within another expression or statement in Python.
But a statement must stand on its own.
A statement cannot be embedded within another statement.
Lambda is limiting
Unlike the def syntax for defining a function, you can pass a lambda function into another function on the same line of code that you *define* the lambda function.
So lambda expressions allows us to write shorter code by defining a function on the same line that we pass that function to sorted.
But lambda expressions can only can contain a single Python expression, not even a single Python statement: just an expression.
Also they can’t have documentation and they don’t have a name.
PEP 8, the official Python style guide, says that code like this:
square = lambda n: n**2
Should always be replaced by code like this:
def square(n): return n**2
Or if you prefer, a multi-line function definition with a nice docstring like this:
def square(n):
"""Return the square of the given number."""
return n**2
I would take this advice a step further by arguing that lambda expressions should *usually* be avoided. Giving a function a name often makes its use easier to understand and many lambda functions can be replaced by (fairly well-named) functions that already exist.
Do you even need a function?
I prefer to define the large majority of my functions using def blocks instead of using lambda expressions.
Even when I could define a function on the same line that I pass it into another function, I often prefer to give it a nice name instead… and maybe even a docstring:
>>> def lowercase(s):
... """Return case-normalized string."""
... return s.lower()
...
This is a case where we don’t even necessarily need to define a function.
The string class has a lower method.
Methods are functions that are attached to classes and which are typically designed to operate on instances of that class.
All strings have a lower method:
>>> name = "Trey"
>>> name.lower
<built-in method lower of str object at 0x...>
>>> name.lower()
'trey'
But methods are actually defined on a class, so every method also lives on the class itself.
That means the str class must also have a lower function hanging off of it:
>>> str.lower
<method 'lower' of 'str' objects>
Instead of calling a method on a string, we could actually call the corresponding function on the str class and pass in the instance of the str class that we’re operating on:
>>> str.lower(name)
'trey'
That’s not the way methods should usually be called because it’s weird.
But the fact that every method is also a function that lives on a class could be handy when we’re making a lambda function that simply accepts an object and calls a method on that object.
These three lines of code all do essentially the same thing:
lowercase = lambda s: s.lower()
def lowercase(s): return s.lower()
lowercase = str.lower
They all create a lowercase variable that points to a function object which can be called with a string and returns a lowercased version of that string.
So we could have used sorted with a key function like this:
>>> sorted(fruits, key=str.lower)
['apple', 'BANANA', 'Lemon', 'lime', 'pear', 'Watermelon']
That might look a bit odd, but I find it pretty readable. Even if it’s not clear why it works at first, it’s probably clear what it’s supposed to do.
Callables are the key
Here are some truths we’ve learned about functions:
functions are objects that can be passed around.
Lambda expressions are expressions that define a single-line function.
Methods are functions attached to classes that operate on instances of that class.
Here’s another truth:
Sometimes functions are actually classes
Let’s play the “class or function” game. I’d like you to guess which of these “functions” is a function and which is a class:
print
list
enumerate
int
sorted
reversed
str
type
open
super
repr
bool
Of those 12 “functions”, only 4 are actually implemented as functions. The rest are classes!
Python’s class instance creation syntax is the same as its function calling syntax. You use a function by calling it:
>>> print("Hello")
Hello
And you create a new class instance by calling the class:
>>> bool()
False
So if a function or class says it accepts a function, it probably accepts any callable object.
Decorators
You can define a function anywhere in Python… even inside another function.
def greet_me(name="friend"):
def greet():
print("Hello {}".format(name))
return greet
This outer function will dynamically create a new function object each time it’s called.
>>> greet_me()
<function greet_me.<locals>.greet at 0x...>
>>> greet_trey = greet_me("Trey")
Since this function also returns that new function object, Python needs a way to keep track of the surrounding scope of that the returned inner function.
>>> greet_trey()
Hello Trey
Python has a non-local or enclosing scope for this purpose.
This idea of having an enclosing scope is called a “closure”. Most modern programming languages implement closures to allow for dynamic function creation.
Here is an example of a decorator:
def call_logger(func):
def wrapper(*args, **kwargs):
print("Function started")
value = func(*args, **kwargs)
print("Function returned")
return value
return wrapper
Python has a special syntax that you may have seen before which is related to this idea of dynamically creating functions:
@call_logger
def greet(name):
print("Hello", name)
This is called the decorator syntax and the thing after that @ symbol is called a decorator function.
This syntax is really just syntactic sugar for passing a newly defined function into that decorator function and then assigning the return value to the same name that the new function was about to be assigned to:
def greet(name):
print("Hello", name)
greet = call_logger(greet)
Here’s how it works. Note that this works for each method: using the syntactic sugar of @call_logger or directly creating it as shown directly above.
>>> greet("Trey")
Function started
Hello Trey
Function returned
If that seems a bit confusing, it’s because it is a bit confusing. The idea of functions that accept functions and return new functions is weird… but it allows for some pretty interesting tools to be built in Python.
Function Exercises
These exercises are all in the functions.py file in the exercises directory. Edit the file to refactor the function(s) or fix the error(s) in the function(s). To run the test: from the exercises folder, type python test.py <function_name>, like this:
$ python test.py longest_first
longest_first
Here’s a function that sorts strings based on their lengths.
def longest_first(strings):
"""Return list of strings with longest first."""
length_and_string = [(len(s), s) for s in strings]
sorted_with_key = sorted(length_and_string, reverse=True)
return [t[1] for t in sorted_with_key]
It should work like this:
>>> from functions import longest_first
>>> # Some of us are lazy typers when we can be.
>>> strings = "We want the longest string".split()
>>> strings
['We', 'want', 'the', 'longest', 'string']
>>> longest_first(strings)
['longest', 'string', 'want', 'the', 'We']
>>> strings = "123 9 3949501 9999 345".split()
>>> strings
['123', '9', '3949501', '9999', '345']
>>> longest_first(strings)
['3949501', '9999', '123', '345', '9']
>>> longest_first([""])
['']
>>> longest_first(["string"])
['string']
Refactor this function to make it simpler.
Hint
This could all be one (fairly readable) line of code.
get_earliest
Here’s a function that accepts any number of date strings and returns the date string that represents the earliest date. Note we are using the US date format of “MM/DD/YYYY”; apologies to those of you who normally use other versions of date formats.
def get_earliest(*dates):
"""Return the earliest of all the entered dates."""
rearranged = []
for date in dates:
m, d, y = date.split("/")
rearranged.append((y, m, d))
y, m, d = min(rearranged)
return f"{m}/{d}/{y}"
This function can be used like this:
>>> from functions import get_earliest
>>> get_earliest('12/31/2023', '01/01/2024')
'12/31/2023'
>>> get_earliest('12/31/2023', '01/01/2024', '04/06/1999', '06/04/1999')
'04/06/1999'
Refactor this function to use the min function with a key argument instead.
Hint
Define a parse_date function that turns a date string into a (year, month, day) tuple and then pass that function to the min function’s key argument to find the date string that represents the earliest date.
Four
Write a four decorator that ignores the function it’s decorating and returns the number 4 instead.
Note that the decorated function is replaced by the number 4 (it’s not even a function anymore).
This decorator is obviously ridiculous, but making it should reinforce your understanding of decorators.
>>> from functions import four
>>> @four
... def greet(name):
... print("Hello {}".format(name))
...
>>> greet
4
>>> type(greet)
<class 'int'>
Groot
Write a groot decorator that ignores the function it’s decorating and returns a function that prints “Groot”.
Yes, this decorator is also ridiculous, but making it should reinforce your understanding of decorators.
>>> from functions import groot
>>> @groot
... def greet(name):
... print("Hello {}".format(name))
...
>>> greet("Trey")
Groot
JSONify
Make a decorator jsonify that will take the return value of the function and return a JSON-encoded version of the return value.
>>> from functions import jsonify
>>> @jsonify
... def get_thing():
... return {'trey': "red", 'diane': "purple"}
...
>>> get_thing()
'{"trey": "red", "diane": "purple"}'
Hint
You’ll want to use json.dumps