Lesson 5 of 5 · Advanced Python · 3 min read · Updated
functools and introspection
reduce, partial and caching — and asking Python about its own objects.
Tools from functools
python
from functools import reduce, partial, lru_cache
print(reduce(lambda a, b: a * b, [1, 2, 3, 4, 5]))
from_binary = partial(int, base=2)
print(from_binary("1010"))
@lru_cache(maxsize=None)
def fib(n):
return n if n < 2 else fib(n - 1) + fib(n - 2)
print(fib(80))
Output
120
10
23416728348467685
reducefolds a list into one value: 1×2, then ×3, ×4, ×5. For sums, plainsum()is clearer.partialmakes a new function with some arguments already filled in.lru_cacheremembers results, so eachfib(n)is worked out once. Without it,fib(80)would take longer than you would wait.
Introspection: asking about objects
python
value = [1, 2, 3]
print(type(value).__name__)
print(isinstance(value, (list, tuple)))
print(hasattr(value, "append"), callable(len))
print(getattr(value, "count")(2))
print([name for name in dir(value) if not name.startswith("_")][:4])
Output
list
True
True True
1
['append', 'clear', 'copy', 'count']
Python can describe any object while the program runs: its type, what attributes it has, whether it can be called. getattr(obj, "name") fetches an attribute whose name is only known at run time — from user input or a file, say.
python
def area(r):
"""Return the area of a circle of radius r."""
return 3.14159 * r * r
print(area.__name__)
print(area.__doc__)
Output
area
Return the area of a circle of radius r.
Note
This is why docstrings matter: help(area) and every code editor read them. At the interactive prompt, dir() and help() are the fastest way to explore anything — including modules you have never used.
What does partial(pow, exp=2) give you?
Try this now
- Use reduce to find the largest number in a list without max(), then compare it with max().
- At the interactive prompt, explore the
strtype withdir(str)and pick three methods you have not used yet; read theirhelp().
Create a free account to save your progress, or sign in.