GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing docs.python.org — Functional Programming HOWTO — Python 2.7.18 documentation
This document is for an old version of Python that is no longer supported.
You should upgrade and read the
Python documentation for the current stable release.
Functional Programming HOWTO¶
In this document, we’ll take a tour of Python’s features suitable for
implementing programs in a functional style. After an introduction to the
concepts of functional programming, we’ll look at language features such as
iterators and generators and relevant library modules such as
Introduction¶This section explains the basic concept of functional programming; if you’re just interested in learning about Python language features, skip to the next section. Programming languages support decomposing problems in several different ways:
The designers of some computer languages choose to emphasize one particular approach to programming. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example. In a functional program, input flows through a set of functions. Each function operates on its input and produces some output. Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value. Functions that have no side effects at all are called purely functional. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input. Some languages are very strict about purity and don’t even have assignment
statements such as Python programs written in functional style usually won’t go to the extreme of avoiding all I/O or all assignments; instead, they’ll provide a functional-appearing interface but will use non-functional features internally. For example, the implementation of a function will still use assignments to local variables, but won’t modify global variables or have other side effects. Functional programming can be considered the opposite of object-oriented programming. Objects are little capsules containing some internal state along with a collection of method calls that let you modify this state, and programs consist of making the right set of state changes. Functional programming wants to avoid state changes as much as possible and works with data flowing between functions. In Python you might combine the two approaches by writing functions that take and return instances representing objects in your application (e-mail messages, transactions, etc.). Functional design may seem like an odd constraint to work under. Why should you avoid objects and side effects? There are theoretical and practical advantages to the functional style:
Formal provability¶A theoretical benefit is that it’s easier to construct a mathematical proof that a functional program is correct. For a long time researchers have been interested in finding ways to mathematically prove programs correct. This is different from testing a program on numerous inputs and concluding that its output is usually correct, or reading a program’s source code and concluding that the code looks right; the goal is instead a rigorous proof that a program produces the right result for all possible inputs. The technique used to prove programs correct is to write down invariants, properties of the input data and of the program’s variables that are always true. For each line of code, you then show that if invariants X and Y are true before the line is executed, the slightly different invariants X’ and Y’ are true after the line is executed. This continues until you reach the end of the program, at which point the invariants should match the desired conditions on the program’s output. Functional programming’s avoidance of assignments arose because assignments are difficult to handle with this technique; assignments can break invariants that were true before the assignment without producing any new invariants that can be propagated onward. Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there’s an error in it, and you wrongly believe you’ve proved the program correct. Modularity¶A more practical benefit of functional programming is that it forces you to break apart your problem into small pieces. Programs are more modular as a result. It’s easier to specify and write a small function that does one thing than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors. Ease of debugging and testing¶Testing and debugging a functional-style program is easier. Debugging is simplified because functions are generally small and clearly specified. When a program doesn’t work, each function is an interface point where you can check that the data are correct. You can look at the intermediate inputs and outputs to quickly isolate the function that’s responsible for a bug. Testing is easier because each function is a potential subject for a unit test. Functions don’t depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations. Composability¶As you work on a functional-style program, you’ll write a number of functions with varying inputs and outputs. Some of these functions will be unavoidably specialized to a particular application, but others will be useful in a wide variety of programs. For example, a function that takes a directory path and returns all the XML files in the directory, or a function that takes a filename and returns its contents, can be applied to many different situations. Over time you’ll form a personal library of utilities. Often you’ll assemble new programs by arranging existing functions in a new configuration and writing a few functions specialized for the current task. Iterators¶I’ll start by looking at a Python language feature that’s an important foundation for writing functional-style programs: iterators. An iterator is an object representing a stream of data; this object returns the
data one element at a time. A Python iterator must support a method called
The built-in You can experiment with the iteration interface manually: >>> L = [1,2,3] >>> it = iter(L) >>> print it <...iterator object at ...> >>> it.next() 1 >>> it.next() 2 >>> it.next() 3 >>> it.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> Python expects iterable objects in several different contexts, the most
important being the for i in iter(obj): print i for i in obj: print i Iterators can be materialized as lists or tuples by using the >>> L = [1,2,3] >>> iterator = iter(L) >>> t = tuple(iterator) >>> t (1, 2, 3) Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple: >>> L = [1,2,3] >>> iterator = iter(L) >>> a,b,c = iterator >>> a,b,c (1, 2, 3) Built-in functions such as Note that you can only go forward in an iterator; there’s no way to get the
previous element, reset the iterator, or make a copy of it. Iterator objects
can optionally provide these additional capabilities, but the iterator protocol
only specifies the Data Types That Support Iterators¶We’ve already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator. Calling >>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6, ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12} >>> for key in m: ... print key, m[key] Mar 3 Feb 2 Aug 8 Sep 9 Apr 4 Jun 6 Jul 7 Jan 1 May 5 Nov 11 Dec 12 Oct 10 Note that the order is essentially random, because it’s based on the hash ordering of the objects in the dictionary. Applying The >>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')] >>> dict(iter(L)) {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'} Files also support iteration by calling the for line in file: # do something for each line ... Sets can take their contents from an iterable and let you iterate over the set’s elements: S = set((2, 3, 5, 7, 11, 13)) for i in S: print i Generator expressions and list comprehensions¶Two common operations on an iterator’s output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring. List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (https://www.haskell.org/). You can strip all the whitespace from a stream of strings with the following code: line_list = [' line 1\n', 'line 2 \n', ...] # Generator expression -- returns iterator stripped_iter = (line.strip() for line in line_list) # List comprehension -- returns list stripped_list = [line.strip() for line in line_list] You can select only certain elements by adding an stripped_list = [line.strip() for line in line_list if line != ""] With a list comprehension, you get back a Python list; Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form: ( expression for expr in sequence1 if condition1 for expr2 in sequence2 if condition2 for expr3 in sequence3 ... if condition3 for exprN in sequenceN if conditionN ) Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses). The elements of the generated output will be the successive values of
Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write: obj_total = sum(obj.count for obj in list_all_objects()) The To put it another way, a list comprehension or generator expression is equivalent to the following Python code: for expr1 in sequence1: if not (condition1): continue # Skip this element for expr2 in sequence2: if not (condition2): continue # Skip this element ... for exprN in sequenceN: if not (conditionN): continue # Skip this element # Output the value of # the expression. This means that when there are multiple >>> seq1 = 'abc' >>> seq2 = (1,2,3) >>> [(x,y) for x in seq1 for y in seq2] [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3), ('c', 1), ('c', 2), ('c', 3)] To avoid introducing an ambiguity into Python’s grammar, if # Syntax error [ x,y for x in seq1 for y in seq2] # Correct [ (x,y) for x in seq1 for y in seq2] Generators¶Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values. You’re doubtless familiar with how regular function calls work in Python or C.
When you call a function, it gets a private namespace where its local variables
are created. When the function reaches a Here’s the simplest example of a generator function: def generate_ints(N): for i in range(N): yield i Any function containing a When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol. On executing
the Here’s a sample usage of the >>> gen = generate_ints(3) >>> gen <generator object generate_ints at ...> >>> gen.next() 0 >>> gen.next() 1 >>> gen.next() 2 >>> gen.next() Traceback (most recent call last): File "stdin", line 1, in <module> File "stdin", line 2, in generate_ints StopIteration You could equally write Inside a generator function, the You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables. For
example, returning a list of integers could be done by setting The test suite included with Python’s library, # A recursive generator that generates Tree leaves in in-order. def inorder(t): if t: for x in inorder(t.left): yield x yield t.label for x in inorder(t.right): yield x Two other examples in Passing values into a generator¶In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy. In Python 2.5 there’s a simple way to pass values into a generator.
val = (yield i) I recommend that you always put parentheses around a (PEP 342 explains the exact rules, which are that a Values are sent into a generator by calling its Here’s a simple counter that increments by 1 and allows changing the value of the internal counter. def counter (maximum): i = 0 while i < maximum: val = (yield i) # If value provided, change counter if val is not None: i = val else: i += 1 And here’s an example of changing the counter: >>> it = counter(10) >>> print it.next() 0 >>> print it.next() 1 >>> print it.send(8) 8 >>> print it.next() 9 >>> print it.next() Traceback (most recent call last): File "t.py", line 15, in <module> print it.next() StopIteration Because In addition to
The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers. Generators also become coroutines, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a Built-in functions¶Let’s look in more detail at built-in functions often used with iterators. Two of Python’s built-in functions,
>>> def upper(s): ... return s.upper() >>> map(upper, ['sentence', 'fragment']) ['SENTENCE', 'FRAGMENT'] >>> [upper(s) for s in ['sentence', 'fragment']] ['SENTENCE', 'FRAGMENT'] As shown above, you can achieve the same effect with a list comprehension. The
>>> def is_even(x): ... return (x % 2) == 0 >>> filter(is_even, range(10)) [0, 2, 4, 6, 8] This can also be written as a list comprehension: >>> [x for x in range(10) if is_even(x)] [0, 2, 4, 6, 8]
>>> import operator >>> reduce(operator.concat, ['A', 'BB', 'C']) 'ABBC' >>> reduce(operator.concat, []) Traceback (most recent call last): ... TypeError: reduce() of empty sequence with no initial value >>> reduce(operator.mul, [1,2,3], 1) 6 >>> reduce(operator.mul, [], 1) 1 If you use >>> reduce(operator.add, [1,2,3,4], 0) 10 >>> sum([1,2,3,4]) 10 >>> sum([]) 0 For many uses of # Instead of: product = reduce(operator.mul, [1,2,3], 1) # You can write: product = 1 for i in [1,2,3]: product *= i
>>> for item in enumerate(['subject', 'verb', 'object']): ... print item (0, 'subject') (1, 'verb') (2, 'object')
f = open('data.txt', 'r') for i, line in enumerate(f): if line.strip() == '': print 'Blank line at line #%i' % i
>>> import random >>> # Generate 8 random numbers between [0, 10000) >>> rand_list = random.sample(range(10000), 8) >>> rand_list [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207] >>> sorted(rand_list) [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878] >>> sorted(rand_list, reverse=True) [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769] (For a more detailed discussion of sorting, see the Sorting mini-HOWTO in the Python wiki at https://wiki.python.org/moin/HowTo/Sorting.) The >>> any([0,1,0]) True >>> any([0,0,0]) False >>> any([1,1,1]) True >>> all([0,1,0]) False >>> all([0,0,0]) False >>> all([1,1,1]) True Small functions and the lambda expression¶When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way. If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all: stripped_lines = [line.strip() for line in lines] existing_files = filter(os.path.exists, file_list) If the function you need doesn’t exist, you need to write it. One way to write
small functions is to use the lowercase = lambda x: x.lower() print_assign = lambda name, value: name + '=' + str(value) adder = lambda x, y: x+y An alternative is to just use the def lowercase(x): return x.lower() def print_assign(name, value): return name + '=' + str(value) def adder(x,y): return x + y Which alternative is preferable? That’s a style question; my usual course is to
avoid using One reason for my preference is that total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1] You can figure it out, but it takes time to disentangle the expression to figure
out what’s going on. Using a short nested def combine (a, b): return 0, a[1] + b[1] total = reduce(combine, items)[1] But it would be best of all if I had simply used a total = 0 for a, b in items: total += b Or the total = sum(b for a,b in items) Many uses of Fredrik Lundh once suggested the following set of rules for refactoring uses of
I really like these rules, but you’re free to disagree about whether this lambda-free style is better. The itertools module¶The The module’s functions fall into a few broad classes:
Creating new iterators¶
itertools.count() => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... itertools.count(10) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.cycle([1,2,3,4,5]) => 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
itertools.repeat('abc') => abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ... itertools.repeat('abc', 5) => abc, abc, abc, abc, abc
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) => a, b, c, 1, 2, 3
itertools.izip(['a', 'b', 'c'], (1, 2, 3)) => ('a', 1), ('b', 2), ('c', 3) It’s similar to the built-in This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable. itertools.izip(['a', 'b'], (1, 2, 3)) => ('a', 1), ('b', 2) You should avoid doing this, though, because an element may be taken from the longer iterators and discarded. This means you can’t go on to use the iterators further because you risk skipping a discarded element.
itertools.islice(range(10), 8) => 0, 1, 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8) => 2, 3, 4, 5, 6, 7 itertools.islice(range(10), 2, 8, 2) => 2, 4, 6
itertools.tee( itertools.count() ) => iterA, iterB where iterA -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... and iterB -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ... Calling functions on elements¶Two functions are used for calling other functions on the contents of an iterable.
itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) => 6, 8, 8 The
itertools.starmap(os.path.join, [('/usr', 'bin', 'java'), ('/bin', 'python'), ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')]) => /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby Selecting elements¶Another group of functions chooses a subset of an iterator’s elements based on a predicate.
def is_even(x): return (x % 2) == 0 itertools.ifilter(is_even, itertools.count()) => 0, 2, 4, 6, 8, 10, 12, 14, ...
itertools.ifilterfalse(is_even, itertools.count()) => 1, 3, 5, 7, 9, 11, 13, 15, ...
def less_than_10(x): return (x < 10) itertools.takewhile(less_than_10, itertools.count()) => 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 itertools.takewhile(is_even, itertools.count()) => 0
itertools.dropwhile(less_than_10, itertools.count()) => 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ... itertools.dropwhile(is_even, itertools.count()) => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ... Grouping elements¶The last function I’ll discuss,
city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), ('Anchorage', 'AK'), ('Nome', 'AK'), ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), ... ] def get_state ((city, state)): return state itertools.groupby(city_list, get_state) => ('AL', iterator-1), ('AK', iterator-2), ('AZ', iterator-3), ... where iterator-1 => ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL') iterator-2 => ('Anchorage', 'AK'), ('Nome', 'AK') iterator-3 => ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
The functools module¶The For programs written in a functional style, you’ll sometimes want to construct
variants of existing functions that have some of the parameters filled in.
Consider a Python function The constructor for Here’s a small but realistic example: import functools def log (message, subsystem): "Write the contents of 'message' to the specified subsystem." print '%s: %s' % (subsystem, message) ... server_log = functools.partial(log, subsystem='server') server_log('Unable to open socket') The operator module¶The Some of the functions in this module are:
Consult the operator module’s documentation for a complete list. Revision History and Acknowledgements¶The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton. Version 0.1: posted June 30 2006. Version 0.11: posted July 1 2006. Typo fixes. Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes. Version 0.21: Added more references suggested on the tutor mailing list. Version 0.30: Adds a section on the References¶General¶Structure and Interpretation of Computer Programs, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. Full text at https://mitpress.mit.edu/sicp/. In this classic textbook of computer science, chapters 2 and 3 discuss the use of sequences and streams to organize the data flow inside a program. The book uses Scheme for its examples, but many of the design approaches described in these chapters are applicable to functional-style Python code. http://www.defmacro.org/ramblings/fp.html: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction. https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry describing functional programming. https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines. https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying. Python-specific¶http://gnosis.cx/TPiP/: The first chapter of David Mertz’s book Text Processing in Python discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Processing”. Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see
© Copyright 1990-2020, Python Software Foundation.
The Python Software Foundation is a non-profit corporation. Please donate. Last updated on Jun 19, 2020. Found a bug? Created using Sphinx 2.3.1. |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |