PYTHON · PYTHON FOR EVERYONE · CHAPTER 9

Functional programming

Treat functions as data to transform inventories and logs with less code and less memory.

8 min readCourse: Python for EveryoneLevel: beginner

From point A to point B

Point A: you know how to define and call functions, and you solve almost everything with for loops and helper lists. Point B: by the end of this chapter, you'll use functions as data and transform collections in one line. You'll also process large logs without running out of memory and extend a function without touching its code.

What functional programming is

Functional programming is a paradigm that builds programs from functions in the mathematical sense: they take input values and return a result, with no side effects. In pure functional languages such as Haskell, a program is just a chain of functions applied to some data.

Python isn't a pure functional language. It's multi-paradigm: it combines the imperative style, object orientation and several functional ideas. The most useful ones are the ones you'll see here.

Why does this matter for network automation? Because much of the work is transforming collections: a list of devices, the lines of a log or the entries of a JSON response. The functional style expresses those transformations in a short, clear way.

Higher-order functions

In Python, everything is an object, functions included. You can store them in variables, put them in a dictionary, pass them as arguments or return them as results. A function that takes or returns other functions is called a higher-order function.

This example returns the function that builds an interface's configuration line for each vendor:

def formatter(vendor):
    def cisco(iface):
        return f"interface {iface}"

    def juniper(iface):
        return f"set interfaces {iface}"

    def arista(iface):
        return f"interface {iface}"

    by_vendor = {"cisco": cisco, "juniper": juniper, "arista": arista}
    return by_vendor[vendor]

f = formatter("juniper")
print(f)               # → <function formatter.<locals>.juniper at 0x...>
print(f("ge-0/0/1"))   # → set interfaces ge-0/0/1

# No intermediate variable: two pairs of parentheses
print(formatter("cisco")("Gi0/1"))   # → interface Gi0/1

Follow the flow. Inside formatter, you define 3 functions and a dictionary that maps each vendor to one of them. formatter doesn't call any of them: it returns the chosen function, which gets stored in f.

Since f holds a function, you call it with parentheses, like any other. On the last line, the first pair of parentheses is for formatter and the second is for the function it returns.

The reverse case is just as common: passing a function as an argument. Notice that str.upper and len go without parentheses, because you're handing over the function, not its result.

def apply(func, values):
    return [func(v) for v in values]

hostnames = ["r1", "sw-core", "fw01"]
print(apply(str.upper, hostnames))   # → ['R1', 'SW-CORE', 'FW01']
print(apply(len, hostnames))         # → [2, 7, 4]

map, filter and reduce

These 3 functions take a function and a collection, and they replace the most common loops.

  • map(function, iterable, ...) applies the function to each item.
  • filter(function, iterable) keeps only the items for which the function returns a truthy value.
  • reduce(function, iterable, initial) combines the items two at a time until a single value is left.
latencies_ms = [12, 48, 7, 150, 33]

def to_seconds(ms):
    return ms / 1000

result = map(to_seconds, latencies_ms)
print(result)          # → <map object at 0x...>
print(list(result))    # → [0.012, 0.048, 0.007, 0.15, 0.033]
print(list(result))    # → []  (the iterator is already used up)

def is_slow(ms):
    return ms > 40

print(list(filter(is_slow, latencies_ms)))   # → [48, 150]

# map with several sequences: it stops at the shortest one
hosts = ["R1", "R2", "R3"]
ips = ["10.0.0.1", "10.0.0.2"]
print(list(map(lambda h, ip: f"{h}={ip}", hosts, ips)))
# → ['R1=10.0.0.1', 'R2=10.0.0.2']

If you pass several sequences to map, the function must accept one argument for each. Python 3.14 added the strict=True parameter: with it, map raises ValueError if the sequences don't have the same length, instead of silently cutting them short.

from functools import reduce

bytes_per_iface = [1200, 560, 3400, 80]

def add(x, y):
    return x + y

print(reduce(add, bytes_per_iface))        # → 5240
print(reduce(add, [], 0))                  # → 0  (initial value)
print(sum(bytes_per_iface))                # → 5240
print(max(bytes_per_iface))                # → 3400

reduce first computes add(1200, 560), then adds that result to 3400, and so on to the end. The initial value avoids an error when the collection is empty. To add things up or find the maximum or minimum, sum, max and min are more readable.

Python 3.14 update. The original book, written for Python 2.5, announced these "Python 3000" changes as future plans; today they're the norm. map and filter return lazy iterators, not lists: values are computed as you loop over them, and you can only loop over them once. reduce is no longer a built-in function: import it from functools. And map with sequences of different lengths no longer pads with None: it stops at the shortest one (use itertools.zip_longest if you need padding).

Lambda functions

Often, the function you pass to map, filter or sorted fits on one line and you won't reuse it. That's what lambda is for: it creates an anonymous function inline.

You write lambda, the parameters separated by commas and without parentheses, a colon and a single expression. The value of that expression is what it returns.

latencies_ms = [12, 48, 7, 150, 33]
print(list(filter(lambda ms: ms > 40, latencies_ms)))   # → [48, 150]

double = lambda x: x * 2
print(double(21))                                        # → 42

routers = [("R2", 72), ("R1", 340), ("R3", 12)]
print(sorted(routers, key=lambda r: r[1]))
# → [('R3', 12), ('R2', 72), ('R1', 340)]

Compare the first example with the filter from the previous section: you no longer need to define is_slow. The limitation is deliberate: a lambda only allows one expression, with no multi-line if, no loops and no return. If you need more, use def.

Assigning a lambda to a variable, like double, works, but the PEP 8 style guide recommends def in that case: the function gets a useful name in error messages.

List, dictionary and set comprehensions

The list comprehension, borrowed from Haskell, creates a new list from an iterable. It has an expression, one or more for clauses and, optionally, one or more if clauses.

latencies_ms = [12, 48, 7, 150, 33]

print([ms / 1000 for ms in latencies_ms])
# → [0.012, 0.048, 0.007, 0.15, 0.033]
print([ms for ms in latencies_ms if ms > 40])
# → [48, 150]

# Several for clauses: every switch with every port
switches = ["sw1", "sw2"]
ports = [0, 1, 2]
print([f"{s}:Gi0/{p}" for s in switches for p in ports if p > 0])
# → ['sw1:Gi0/1', 'sw1:Gi0/2', 'sw2:Gi0/1', 'sw2:Gi0/2']

# Equivalent with nested loops
result = []
for s in switches:
    for p in ports:
        if p > 0:
            result.append(f"{s}:Gi0/{p}")
print(result)
# → ['sw1:Gi0/1', 'sw1:Gi0/2', 'sw2:Gi0/1', 'sw2:Gi0/2']

Read the first one as "for each ms in latencies_ms, compute ms / 1000". The second does the job of filter: it only keeps what meets the condition. With several for clauses, the order is the same as the nested loops would have.

The same idea works for dictionaries and sets. Only the braces change and, in the dictionary, the key: value pair:

inventory = [
    {"hostname": "R1", "ip": "10.0.0.1", "vendor": "cisco"},
    {"hostname": "R2", "ip": "10.0.0.2", "vendor": "juniper"},
    {"hostname": "SW1", "ip": "10.0.0.11", "vendor": "cisco"},
]

# Dictionary comprehension: hostname → ip
ip_of = {d["hostname"]: d["ip"] for d in inventory}
print(ip_of)   # → {'R1': '10.0.0.1', 'R2': '10.0.0.2', 'SW1': '10.0.0.11'}

# Set comprehension: unique values
vendors = {d["vendor"] for d in inventory}
print(sorted(vendors))   # → ['cisco', 'juniper']

In Python today, comprehensions are the preferred way to transform and filter. map and filter are still valid, especially when you already have a named function. If a comprehension doesn't fit in one or two readable lines, go back to the for loop.

Generators

A generator expression looks just like a list comprehension, but with parentheses. The difference is what it produces: not a list, but a generator, which computes each value only when you ask for it.

latencies_ms = [12, 48, 7, 150, 33]

lst = [ms * 2 for ms in latencies_ms]
gen = (ms * 2 for ms in latencies_ms)
print(lst)          # → [24, 96, 14, 300, 66]
print(gen)          # → <generator object <genexpr> at 0x...>
print(sum(gen))     # → 500

You can also write a generator function. It's a regular function that uses yield instead of return. Each yield hands over a value and pauses the function, with its variables intact, until the next one is requested.

def ip_range(base, start, end, step=1):
    """Generates base.N addresses from start to end (inclusive)."""
    n = start
    while n <= end:
        yield f"{base}.{n}"
        n += step

g = ip_range("10.0.0", 1, 9, 4)
print(g)            # → <generator object ip_range at 0x...>
print(next(g))      # → 10.0.0.1

for ip in ip_range("10.0.0", 1, 9, 4):
    print(ip)
# → 10.0.0.1
# → 10.0.0.5
# → 10.0.0.9

print(list(ip_range("192.168.1", 250, 254, 2)))
# → ['192.168.1.250', '192.168.1.252', '192.168.1.254']

A generator works anywhere an iterable is accepted: a for, list(), sum() or sorted(). Notice that list() takes the call to the generator function, not the function itself.

The advantage is memory. A list stores all its items at once; a generator stores only the one it's handing over. With a syslog file of millions of lines, that difference decides whether your script finishes or not:

import sys

records = [
    "Oct 24 10:01:02 R1 %LINK-3-UPDOWN: Interface Gi0/1, changed state to down",
    "Oct 24 10:01:05 R1 %SYS-5-CONFIG_I: Configured from console",
    "Oct 24 10:02:40 R2 %LINK-3-UPDOWN: Interface Gi0/2, changed state to up",
]

def link_events(lines):
    for line in lines:
        if "%LINK-" in line:
            yield line.split()[3]

print(list(link_events(records)))   # → ['R1', 'R2']

# List vs. generator: memory used
lst = [n for n in range(1_000_000)]
gen = (n for n in range(1_000_000))
print(sys.getsizeof(lst) > 1_000_000, sys.getsizeof(gen) < 500)   # → True True

In the files chapter, you'll see that an open file is also read line by line. So link_events will work the same way on a real log.

Fact. Many Python 3 functions are already lazy, like generators: range, map, filter, zip and enumerate. In Python 2, almost all of them returned full lists, and xrange was the lazy version of range; today xrange no longer exists.

Decorators

A decorator is a function that takes a function and returns another one that wraps it. You use it to add shared behavior, such as logging calls, timing or retrying, without changing the original code.

def log_calls(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with {args}")
        return func(*args, **kwargs)
    return wrapper

def show(text):
    print(text)

show("hello")                        # → hello
log_calls(show)("hello")
# → Calling show with ('hello',)
# → hello

@log_calls
def connect(host):
    """Simulates an SSH connection."""
    return f"connected to {host}"

print(connect("10.0.0.1"))
# → Calling connect with ('10.0.0.1',)
# → connected to 10.0.0.1
print(connect.__name__)              # → wrapper
print(connect.__doc__)               # → None

log_calls creates the wrapper function and returns it. When you call it, wrapper prints the name of the original function, runs it with the same arguments and returns its result. Thanks to *args and **kwargs, it works for functions with any signature.

log_calls(show)("hello") works, but it's hard to read. The @log_calls syntax above the def does the same thing permanently: it's equivalent to writing connect = log_calls(connect) right after defining it.

The last two lines show a problem: the decorated function has lost its name and its docstring, because it's now wrapper. That confuses debuggers, help() and logs. The fix is functools.wraps, which copies that metadata:

import functools
import time

def timed(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        duration = time.perf_counter() - start
        print(f"{func.__name__} took {duration:.2f} s")
        return result
    return wrapper

def log_calls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

@log_calls
@timed
def backup(host):
    """Simulates backing up a device's configuration."""
    time.sleep(0.2)
    return f"{host}.cfg"

print(backup("R1"))
print(backup.__name__)   # → backup
print(backup.__doc__)    # → Simulates backing up a device's configuration.

The call's output is:

Calling backup
backup took 0.20 s
R1.cfg

You can stack several decorators, one per line. They're applied from the bottom up: first timed wraps backup, and then log_calls wraps the result. When you call it, the order flips: the first to run is log_calls, the topmost one.

Python 3.14 update. The book's decorator used print as a statement and only accepted *args. In Python 3, print is a function, f-strings simplify the messages, and the usual practice is to accept *args, **kwargs and always apply @functools.wraps. The @ syntax has existed since Python 2.4.

Challenge

Answer before you open the solution.

1. You write r = map(str.upper, ["r1", "r2"]) and then print(r). Why don't you see the list?

Because map returns a lazy iterator. To see the values, convert it: print(list(r)).

2. How do you get the VLANs greater than 100 from vlans with a comprehension?

[v for v in vlans if v > 100]. The if clause does the job of filter.

3. Your Python 2 script calls reduce(...) and now fails with NameError. What's missing?

from functools import reduce. In Python 3, reduce is no longer a built-in function.

4. You need to process a 20 GB log and count the %LINK- events. List or generator? Why?

Generator. It produces one line at a time and doesn't load the whole file into memory. For example: sum(1 for l in lines if "%LINK-" in l).

5. You decorated a function, and now help() shows the name wrapper. How do you fix it?

With @functools.wraps(func) on the inner function. It copies the name, the docstring and other metadata from the original.

Key takeaways

  • In Python, functions are objects: you can store them, pass them and return them.
  • map and filter return iterators; reduce lives in functools.
  • lambda creates anonymous single-expression functions; ideal for key=.
  • List, dictionary and set comprehensions are the preferred way to transform and filter.
  • Generators, with yield or in parentheses, produce values on demand and save memory.
  • A decorator wraps a function; always apply functools.wraps.

In the next chapter, you'll handle errors with exceptions. That way, a device that doesn't respond won't stop your whole script.

Official resources

Source and credits. This course is based on the book Python para todos by Raúl González Duque, published under the Creative Commons Attribution 2.5 Spain license. The original book was written for Python 2.5. Jesús Espinoza, with AI assistance, brought it to Python 3.14: he rewrote every chapter in his own words, replaced the examples with networking cases, updated the syntax and the modules that no longer exist, fixed errors in the original and tested all the code with Python 3.14.6 against the official documentation.

Navigate