summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/howto%2Ffunctional.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/howto%2Ffunctional.html')
-rw-r--r--devdocs/python~3.12/howto%2Ffunctional.html379
1 files changed, 379 insertions, 0 deletions
diff --git a/devdocs/python~3.12/howto%2Ffunctional.html b/devdocs/python~3.12/howto%2Ffunctional.html
new file mode 100644
index 00000000..b8b2c56f
--- /dev/null
+++ b/devdocs/python~3.12/howto%2Ffunctional.html
@@ -0,0 +1,379 @@
+ <h1>Functional Programming HOWTO</h1> <dl class="field-list simple"> <dt class="field-odd">Author</dt> <dd class="field-odd">
+<p>A. M. Kuchling</p> </dd> <dt class="field-even">Release</dt> <dd class="field-even">
+<p>0.32</p> </dd> </dl> <p>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 <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a>s and <a class="reference internal" href="../glossary#term-generator"><span class="xref std std-term">generator</span></a>s and relevant library modules such as <a class="reference internal" href="../library/itertools#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code>itertools</code></a> and <a class="reference internal" href="../library/functools#module-functools" title="functools: Higher-order functions and operations on callable objects."><code>functools</code></a>.</p> <section id="introduction"> <h2>Introduction</h2> <p>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 on <a class="reference internal" href="#functional-howto-iterators"><span class="std std-ref">Iterators</span></a>.</p> <p>Programming languages support decomposing problems in several different ways:</p> <ul class="simple"> <li>Most programming languages are <strong>procedural</strong>: programs are lists of instructions that tell the computer what to do with the program’s input. C, Pascal, and even Unix shells are procedural languages.</li> <li>In <strong>declarative</strong> languages, you write a specification that describes the problem to be solved, and the language implementation figures out how to perform the computation efficiently. SQL is the declarative language you’re most likely to be familiar with; a SQL query describes the data set you want to retrieve, and the SQL engine decides whether to scan tables or use indexes, which subclauses should be performed first, etc.</li> <li>
+<strong>Object-oriented</strong> programs manipulate collections of objects. Objects have internal state and support methods that query or modify this internal state in some way. Smalltalk and Java are object-oriented languages. C++ and Python are languages that support object-oriented programming, but don’t force the use of object-oriented features.</li> <li>
+<strong>Functional</strong> programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell.</li> </ul> <p>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.</p> <p>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 <strong>purely functional</strong>. 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.</p> <p>Some languages are very strict about purity and don’t even have assignment statements such as <code>a=3</code> or <code>c = a + b</code>, but it’s difficult to avoid all side effects, such as printing to the screen or writing to a disk file. Another example is a call to the <a class="reference internal" href="../library/functions#print" title="print"><code>print()</code></a> or <a class="reference internal" href="../library/time#time.sleep" title="time.sleep"><code>time.sleep()</code></a> function, neither of which returns a useful value. Both are called only for their side effects of sending some text to the screen or pausing execution for a second.</p> <p>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.</p> <p>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.).</p> <p>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:</p> <ul class="simple"> <li>Formal provability.</li> <li>Modularity.</li> <li>Composability.</li> <li>Ease of debugging and testing.</li> </ul> <section id="formal-provability"> <h3>Formal provability</h3> <p>A theoretical benefit is that it’s easier to construct a mathematical proof that a functional program is correct.</p> <p>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.</p> <p>The technique used to prove programs correct is to write down <strong>invariants</strong>, 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 <strong>before</strong> the line is executed, the slightly different invariants X’ and Y’ are true <strong>after</strong> 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.</p> <p>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.</p> <p>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.</p> </section> <section id="modularity"> <h3>Modularity</h3> <p>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.</p> </section> <section id="ease-of-debugging-and-testing"> <h3>Ease of debugging and testing</h3> <p>Testing and debugging a functional-style program is easier.</p> <p>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.</p> <p>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.</p> </section> <section id="composability"> <h3>Composability</h3> <p>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.</p> <p>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.</p> </section> </section> <section id="iterators"> <span id="functional-howto-iterators"></span><h2>Iterators</h2> <p>I’ll start by looking at a Python language feature that’s an important foundation for writing functional-style programs: iterators.</p> <p>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 <a class="reference internal" href="../library/stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> that takes no arguments and always returns the next element of the stream. If there are no more elements in the stream, <a class="reference internal" href="../library/stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> must raise the <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> exception. Iterators don’t have to be finite, though; it’s perfectly reasonable to write an iterator that produces an infinite stream of data.</p> <p>The built-in <a class="reference internal" href="../library/functions#iter" title="iter"><code>iter()</code></a> function takes an arbitrary object and tries to return an iterator that will return the object’s contents or elements, raising <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if the object doesn’t support iteration. Several of Python’s built-in data types support iteration, the most common being lists and dictionaries. An object is called <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> if you can get an iterator for it.</p> <p>You can experiment with the iteration interface manually:</p> <pre data-language="python">&gt;&gt;&gt; L = [1, 2, 3]
+&gt;&gt;&gt; it = iter(L)
+&gt;&gt;&gt; it
+&lt;...iterator object at ...&gt;
+&gt;&gt;&gt; it.__next__() # same as next(it)
+1
+&gt;&gt;&gt; next(it)
+2
+&gt;&gt;&gt; next(it)
+3
+&gt;&gt;&gt; next(it)
+Traceback (most recent call last):
+ File "&lt;stdin&gt;", line 1, in &lt;module&gt;
+StopIteration
+&gt;&gt;&gt;
+</pre> <p>Python expects iterable objects in several different contexts, the most important being the <a class="reference internal" href="../reference/compound_stmts#for"><code>for</code></a> statement. In the statement <code>for X in Y</code>, Y must be an iterator or some object for which <a class="reference internal" href="../library/functions#iter" title="iter"><code>iter()</code></a> can create an iterator. These two statements are equivalent:</p> <pre data-language="python">for i in iter(obj):
+ print(i)
+
+for i in obj:
+ print(i)
+</pre> <p>Iterators can be materialized as lists or tuples by using the <a class="reference internal" href="../library/stdtypes#list" title="list"><code>list()</code></a> or <a class="reference internal" href="../library/stdtypes#tuple" title="tuple"><code>tuple()</code></a> constructor functions:</p> <pre data-language="python">&gt;&gt;&gt; L = [1, 2, 3]
+&gt;&gt;&gt; iterator = iter(L)
+&gt;&gt;&gt; t = tuple(iterator)
+&gt;&gt;&gt; t
+(1, 2, 3)
+</pre> <p>Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple:</p> <pre data-language="python">&gt;&gt;&gt; L = [1, 2, 3]
+&gt;&gt;&gt; iterator = iter(L)
+&gt;&gt;&gt; a, b, c = iterator
+&gt;&gt;&gt; a, b, c
+(1, 2, 3)
+</pre> <p>Built-in functions such as <a class="reference internal" href="../library/functions#max" title="max"><code>max()</code></a> and <a class="reference internal" href="../library/functions#min" title="min"><code>min()</code></a> can take a single iterator argument and will return the largest or smallest element. The <code>"in"</code> and <code>"not in"</code> operators also support iterators: <code>X in iterator</code> is true if X is found in the stream returned by the iterator. You’ll run into obvious problems if the iterator is infinite; <a class="reference internal" href="../library/functions#max" title="max"><code>max()</code></a>, <a class="reference internal" href="../library/functions#min" title="min"><code>min()</code></a> will never return, and if the element X never appears in the stream, the <code>"in"</code> and <code>"not in"</code> operators won’t return either.</p> <p>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 <a class="reference internal" href="../library/stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method. Functions may therefore consume all of the iterator’s output, and if you need to do something different with the same stream, you’ll have to create a new iterator.</p> <section id="data-types-that-support-iterators"> <h3>Data Types That Support Iterators</h3> <p>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.</p> <p>Calling <a class="reference internal" href="../library/functions#iter" title="iter"><code>iter()</code></a> on a dictionary returns an iterator that will loop over the dictionary’s keys:</p> <pre data-language="python">&gt;&gt;&gt; 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}
+&gt;&gt;&gt; for key in m:
+... print(key, m[key])
+Jan 1
+Feb 2
+Mar 3
+Apr 4
+May 5
+Jun 6
+Jul 7
+Aug 8
+Sep 9
+Oct 10
+Nov 11
+Dec 12
+</pre> <p>Note that starting with Python 3.7, dictionary iteration order is guaranteed to be the same as the insertion order. In earlier versions, the behaviour was unspecified and could vary between implementations.</p> <p>Applying <a class="reference internal" href="../library/functions#iter" title="iter"><code>iter()</code></a> to a dictionary always loops over the keys, but dictionaries have methods that return other iterators. If you want to iterate over values or key/value pairs, you can explicitly call the <a class="reference internal" href="../library/stdtypes#dict.values" title="dict.values"><code>values()</code></a> or <a class="reference internal" href="../library/stdtypes#dict.items" title="dict.items"><code>items()</code></a> methods to get an appropriate iterator.</p> <p>The <a class="reference internal" href="../library/stdtypes#dict" title="dict"><code>dict()</code></a> constructor can accept an iterator that returns a finite stream of <code>(key, value)</code> tuples:</p> <pre data-language="python">&gt;&gt;&gt; L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
+&gt;&gt;&gt; dict(iter(L))
+{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
+</pre> <p>Files also support iteration by calling the <a class="reference internal" href="../library/io#io.TextIOBase.readline" title="io.TextIOBase.readline"><code>readline()</code></a> method until there are no more lines in the file. This means you can read each line of a file like this:</p> <pre data-language="python">for line in file:
+ # do something for each line
+ ...
+</pre> <p>Sets can take their contents from an iterable and let you iterate over the set’s elements:</p> <pre data-language="python">&gt;&gt;&gt; S = {2, 3, 5, 7, 11, 13}
+&gt;&gt;&gt; for i in S:
+... print(i)
+2
+3
+5
+7
+11
+13
+</pre> </section> </section> <section id="generator-expressions-and-list-comprehensions"> <h2>Generator expressions and list comprehensions</h2> <p>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.</p> <p>List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (<a class="reference external" href="https://www.haskell.org/">https://www.haskell.org/</a>). You can strip all the whitespace from a stream of strings with the following code:</p> <pre data-language="python">&gt;&gt;&gt; line_list = [' line 1\n', 'line 2 \n', ' \n', '']
+
+&gt;&gt;&gt; # Generator expression -- returns iterator
+&gt;&gt;&gt; stripped_iter = (line.strip() for line in line_list)
+
+&gt;&gt;&gt; # List comprehension -- returns list
+&gt;&gt;&gt; stripped_list = [line.strip() for line in line_list]
+</pre> <p>You can select only certain elements by adding an <code>"if"</code> condition:</p> <pre data-language="python">&gt;&gt;&gt; stripped_list = [line.strip() for line in line_list
+... if line != ""]
+</pre> <p>With a list comprehension, you get back a Python list; <code>stripped_list</code> is a list containing the resulting lines, not an iterator. Generator expressions return an iterator that computes the values as necessary, not needing to materialize all the values at once. This means that list comprehensions aren’t useful if you’re working with iterators that return an infinite stream or a very large amount of data. Generator expressions are preferable in these situations.</p> <p>Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form:</p> <pre data-language="python">( 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 )
+</pre> <p>Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses).</p> <p>The elements of the generated output will be the successive values of <code>expression</code>. The <code>if</code> clauses are all optional; if present, <code>expression</code> is only evaluated and added to the result when <code>condition</code> is true.</p> <p>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:</p> <pre data-language="python">obj_total = sum(obj.count for obj in list_all_objects())
+</pre> <p>The <code>for...in</code> clauses contain the sequences to be iterated over. The sequences do not have to be the same length, because they are iterated over from left to right, <strong>not</strong> in parallel. For each element in <code>sequence1</code>, <code>sequence2</code> is looped over from the beginning. <code>sequence3</code> is then looped over for each resulting pair of elements from <code>sequence1</code> and <code>sequence2</code>.</p> <p>To put it another way, a list comprehension or generator expression is equivalent to the following Python code:</p> <pre data-language="python">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.
+</pre> <p>This means that when there are multiple <code>for...in</code> clauses but no <code>if</code> clauses, the length of the resulting output will be equal to the product of the lengths of all the sequences. If you have two lists of length 3, the output list is 9 elements long:</p> <pre data-language="python">&gt;&gt;&gt; seq1 = 'abc'
+&gt;&gt;&gt; seq2 = (1, 2, 3)
+&gt;&gt;&gt; [(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)]
+</pre> <p>To avoid introducing an ambiguity into Python’s grammar, if <code>expression</code> is creating a tuple, it must be surrounded with parentheses. The first list comprehension below is a syntax error, while the second one is correct:</p> <pre data-language="python"># Syntax error
+[x, y for x in seq1 for y in seq2]
+# Correct
+[(x, y) for x in seq1 for y in seq2]
+</pre> </section> <section id="generators"> <h2>Generators</h2> <p>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.</p> <p>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 <code>return</code> statement, the local variables are destroyed and the value is returned to the caller. A later call to the same function creates a new private namespace and a fresh set of local variables. But, what if the local variables weren’t thrown away on exiting a function? What if you could later resume the function where it left off? This is what generators provide; they can be thought of as resumable functions.</p> <p>Here’s the simplest example of a generator function:</p> <pre data-language="python">&gt;&gt;&gt; def generate_ints(N):
+... for i in range(N):
+... yield i
+</pre> <p>Any function containing a <a class="reference internal" href="../reference/simple_stmts#yield"><code>yield</code></a> keyword is a generator function; this is detected by Python’s <a class="reference internal" href="../glossary#term-bytecode"><span class="xref std std-term">bytecode</span></a> compiler which compiles the function specially as a result.</p> <p>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 <code>yield</code> expression, the generator outputs the value of <code>i</code>, similar to a <code>return</code> statement. The big difference between <code>yield</code> and a <code>return</code> statement is that on reaching a <code>yield</code> the generator’s state of execution is suspended and local variables are preserved. On the next call to the generator’s <a class="reference internal" href="../reference/expressions#generator.__next__" title="generator.__next__"><code>__next__()</code></a> method, the function will resume executing.</p> <p>Here’s a sample usage of the <code>generate_ints()</code> generator:</p> <pre data-language="python">&gt;&gt;&gt; gen = generate_ints(3)
+&gt;&gt;&gt; gen
+&lt;generator object generate_ints at ...&gt;
+&gt;&gt;&gt; next(gen)
+0
+&gt;&gt;&gt; next(gen)
+1
+&gt;&gt;&gt; next(gen)
+2
+&gt;&gt;&gt; next(gen)
+Traceback (most recent call last):
+ File "stdin", line 1, in &lt;module&gt;
+ File "stdin", line 2, in generate_ints
+StopIteration
+</pre> <p>You could equally write <code>for i in generate_ints(5)</code>, or <code>a, b, c =
+generate_ints(3)</code>.</p> <p>Inside a generator function, <code>return value</code> causes <code>StopIteration(value)</code> to be raised from the <a class="reference internal" href="../reference/expressions#generator.__next__" title="generator.__next__"><code>__next__()</code></a> method. Once this happens, or the bottom of the function is reached, the procession of values ends and the generator cannot yield any further values.</p> <p>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 <code>self.count</code> to 0, and having the <a class="reference internal" href="../library/stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method increment <code>self.count</code> and return it. However, for a moderately complicated generator, writing a corresponding class can be much messier.</p> <p>The test suite included with Python’s library, <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/test/test_generators.py">Lib/test/test_generators.py</a>, contains a number of more interesting examples. Here’s one generator that implements an in-order traversal of a tree using generators recursively.</p> <pre data-language="python"># 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
+</pre> <p>Two other examples in <code>test_generators.py</code> produce solutions for the N-Queens problem (placing N queens on an NxN chess board so that no queen threatens another) and the Knight’s Tour (finding a route that takes a knight to every square of an NxN chessboard without visiting any square twice).</p> <section id="passing-values-into-a-generator"> <h3>Passing values into a generator</h3> <p>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.</p> <p>In Python 2.5 there’s a simple way to pass values into a generator. <a class="reference internal" href="../reference/simple_stmts#yield"><code>yield</code></a> became an expression, returning a value that can be assigned to a variable or otherwise operated on:</p> <pre data-language="python">val = (yield i)
+</pre> <p>I recommend that you <strong>always</strong> put parentheses around a <code>yield</code> expression when you’re doing something with the returned value, as in the above example. The parentheses aren’t always necessary, but it’s easier to always add them instead of having to remember when they’re needed.</p> <p>(<span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a> explains the exact rules, which are that a <code>yield</code>-expression must always be parenthesized except when it occurs at the top-level expression on the right-hand side of an assignment. This means you can write <code>val = yield i</code> but have to use parentheses when there’s an operation, as in <code>val = (yield i)
++ 12</code>.)</p> <p>Values are sent into a generator by calling its <a class="reference internal" href="../reference/expressions#generator.send" title="generator.send"><code>send(value)</code></a> method. This method resumes the generator’s code and the <code>yield</code> expression returns the specified value. If the regular <a class="reference internal" href="../reference/expressions#generator.__next__" title="generator.__next__"><code>__next__()</code></a> method is called, the <code>yield</code> returns <code>None</code>.</p> <p>Here’s a simple counter that increments by 1 and allows changing the value of the internal counter.</p> <pre data-language="python">def counter(maximum):
+ i = 0
+ while i &lt; maximum:
+ val = (yield i)
+ # If value provided, change counter
+ if val is not None:
+ i = val
+ else:
+ i += 1
+</pre> <p>And here’s an example of changing the counter:</p> <pre data-language="python">&gt;&gt;&gt; it = counter(10)
+&gt;&gt;&gt; next(it)
+0
+&gt;&gt;&gt; next(it)
+1
+&gt;&gt;&gt; it.send(8)
+8
+&gt;&gt;&gt; next(it)
+9
+&gt;&gt;&gt; next(it)
+Traceback (most recent call last):
+ File "t.py", line 15, in &lt;module&gt;
+ it.next()
+StopIteration
+</pre> <p>Because <code>yield</code> will often be returning <code>None</code>, you should always check for this case. Don’t just use its value in expressions unless you’re sure that the <a class="reference internal" href="../reference/expressions#generator.send" title="generator.send"><code>send()</code></a> method will be the only method used to resume your generator function.</p> <p>In addition to <a class="reference internal" href="../reference/expressions#generator.send" title="generator.send"><code>send()</code></a>, there are two other methods on generators:</p> <ul> <li>
+<a class="reference internal" href="../reference/expressions#generator.throw" title="generator.throw"><code>throw(value)</code></a> is used to raise an exception inside the generator; the exception is raised by the <code>yield</code> expression where the generator’s execution is paused.</li> <li>
+<p><a class="reference internal" href="../reference/expressions#generator.close" title="generator.close"><code>close()</code></a> raises a <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> exception inside the generator to terminate the iteration. On receiving this exception, the generator’s code must either raise <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> or <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a>; catching the exception and doing anything else is illegal and will trigger a <a class="reference internal" href="../library/exceptions#RuntimeError" title="RuntimeError"><code>RuntimeError</code></a>. <a class="reference internal" href="../reference/expressions#generator.close" title="generator.close"><code>close()</code></a> will also be called by Python’s garbage collector when the generator is garbage-collected.</p> <p>If you need to run cleanup code when a <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a> occurs, I suggest using a <code>try: ... finally:</code> suite instead of catching <a class="reference internal" href="../library/exceptions#GeneratorExit" title="GeneratorExit"><code>GeneratorExit</code></a>.</p> </li> </ul> <p>The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers.</p> <p>Generators also become <strong>coroutines</strong>, a more generalized form of subroutines. Subroutines are entered at one point and exited at another point (the top of the function, and a <code>return</code> statement), but coroutines can be entered, exited, and resumed at many different points (the <code>yield</code> statements).</p> </section> </section> <section id="built-in-functions"> <h2>Built-in functions</h2> <p>Let’s look in more detail at built-in functions often used with iterators.</p> <p>Two of Python’s built-in functions, <a class="reference internal" href="../library/functions#map" title="map"><code>map()</code></a> and <a class="reference internal" href="../library/functions#filter" title="filter"><code>filter()</code></a> duplicate the features of generator expressions:</p> <dl> <dt>
+<code>map(f, iterA, iterB, ...) returns an iterator over the sequence</code> </dt>
+<dd>
+<p><code>f(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...</code>.</p> <pre data-language="python">&gt;&gt;&gt; def upper(s):
+... return s.upper()
+</pre> <pre data-language="python">&gt;&gt;&gt; list(map(upper, ['sentence', 'fragment']))
+['SENTENCE', 'FRAGMENT']
+&gt;&gt;&gt; [upper(s) for s in ['sentence', 'fragment']]
+['SENTENCE', 'FRAGMENT']
+</pre> </dd> </dl> <p>You can of course achieve the same effect with a list comprehension.</p> <p><a class="reference internal" href="../library/functions#filter" title="filter"><code>filter(predicate, iter)</code></a> returns an iterator over all the sequence elements that meet a certain condition, and is similarly duplicated by list comprehensions. A <strong>predicate</strong> is a function that returns the truth value of some condition; for use with <a class="reference internal" href="../library/functions#filter" title="filter"><code>filter()</code></a>, the predicate must take a single value.</p> <pre data-language="python">&gt;&gt;&gt; def is_even(x):
+... return (x % 2) == 0
+</pre> <pre data-language="python">&gt;&gt;&gt; list(filter(is_even, range(10)))
+[0, 2, 4, 6, 8]
+</pre> <p>This can also be written as a list comprehension:</p> <pre data-language="python">&gt;&gt;&gt; list(x for x in range(10) if is_even(x))
+[0, 2, 4, 6, 8]
+</pre> <p><a class="reference internal" href="../library/functions#enumerate" title="enumerate"><code>enumerate(iter, start=0)</code></a> counts off the elements in the iterable returning 2-tuples containing the count (from <em>start</em>) and each element.</p> <pre data-language="python">&gt;&gt;&gt; for item in enumerate(['subject', 'verb', 'object']):
+... print(item)
+(0, 'subject')
+(1, 'verb')
+(2, 'object')
+</pre> <p><a class="reference internal" href="../library/functions#enumerate" title="enumerate"><code>enumerate()</code></a> is often used when looping through a list and recording the indexes at which certain conditions are met:</p> <pre data-language="python">f = open('data.txt', 'r')
+for i, line in enumerate(f):
+ if line.strip() == '':
+ print('Blank line at line #%i' % i)
+</pre> <p><a class="reference internal" href="../library/functions#sorted" title="sorted"><code>sorted(iterable, key=None, reverse=False)</code></a> collects all the elements of the iterable into a list, sorts the list, and returns the sorted result. The <em>key</em> and <em>reverse</em> arguments are passed through to the constructed list’s <a class="reference internal" href="../library/stdtypes#list.sort" title="list.sort"><code>sort()</code></a> method.</p> <pre data-language="python">&gt;&gt;&gt; import random
+&gt;&gt;&gt; # Generate 8 random numbers between [0, 10000)
+&gt;&gt;&gt; rand_list = random.sample(range(10000), 8)
+&gt;&gt;&gt; rand_list
+[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
+&gt;&gt;&gt; sorted(rand_list)
+[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
+&gt;&gt;&gt; sorted(rand_list, reverse=True)
+[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
+</pre> <p>(For a more detailed discussion of sorting, see the <a class="reference internal" href="sorting#sortinghowto"><span class="std std-ref">Sorting HOW TO</span></a>.)</p> <p>The <a class="reference internal" href="../library/functions#any" title="any"><code>any(iter)</code></a> and <a class="reference internal" href="../library/functions#all" title="all"><code>all(iter)</code></a> built-ins look at the truth values of an iterable’s contents. <a class="reference internal" href="../library/functions#any" title="any"><code>any()</code></a> returns <code>True</code> if any element in the iterable is a true value, and <a class="reference internal" href="../library/functions#all" title="all"><code>all()</code></a> returns <code>True</code> if all of the elements are true values:</p> <pre data-language="python">&gt;&gt;&gt; any([0, 1, 0])
+True
+&gt;&gt;&gt; any([0, 0, 0])
+False
+&gt;&gt;&gt; any([1, 1, 1])
+True
+&gt;&gt;&gt; all([0, 1, 0])
+False
+&gt;&gt;&gt; all([0, 0, 0])
+False
+&gt;&gt;&gt; all([1, 1, 1])
+True
+</pre> <p><a class="reference internal" href="../library/functions#zip" title="zip"><code>zip(iterA, iterB, ...)</code></a> takes one element from each iterable and returns them in a tuple:</p> <pre data-language="python">zip(['a', 'b', 'c'], (1, 2, 3)) =&gt;
+ ('a', 1), ('b', 2), ('c', 3)
+</pre> <p>It doesn’t construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they’re requested. (The technical term for this behaviour is <a class="reference external" href="https://en.wikipedia.org/wiki/Lazy_evaluation">lazy evaluation</a>.)</p> <p>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.</p> <pre data-language="python">zip(['a', 'b'], (1, 2, 3)) =&gt;
+ ('a', 1), ('b', 2)
+</pre> <p>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.</p> </section> <section id="the-itertools-module"> <h2>The itertools module</h2> <p>The <a class="reference internal" href="../library/itertools#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code>itertools</code></a> module contains a number of commonly used iterators as well as functions for combining several iterators. This section will introduce the module’s contents by showing small examples.</p> <p>The module’s functions fall into a few broad classes:</p> <ul class="simple"> <li>Functions that create a new iterator based on an existing iterator.</li> <li>Functions for treating an iterator’s elements as function arguments.</li> <li>Functions for selecting portions of an iterator’s output.</li> <li>A function for grouping an iterator’s output.</li> </ul> <section id="creating-new-iterators"> <h3>Creating new iterators</h3> <p><a class="reference internal" href="../library/itertools#itertools.count" title="itertools.count"><code>itertools.count(start, step)</code></a> returns an infinite stream of evenly spaced values. You can optionally supply the starting number, which defaults to 0, and the interval between numbers, which defaults to 1:</p> <pre data-language="python">itertools.count() =&gt;
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
+itertools.count(10) =&gt;
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
+itertools.count(10, 5) =&gt;
+ 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.cycle" title="itertools.cycle"><code>itertools.cycle(iter)</code></a> saves a copy of the contents of a provided iterable and returns a new iterator that returns its elements from first to last. The new iterator will repeat these elements infinitely.</p> <pre data-language="python">itertools.cycle([1, 2, 3, 4, 5]) =&gt;
+ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.repeat" title="itertools.repeat"><code>itertools.repeat(elem, [n])</code></a> returns the provided element <em>n</em> times, or returns the element endlessly if <em>n</em> is not provided.</p> <pre data-language="python">itertools.repeat('abc') =&gt;
+ abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
+itertools.repeat('abc', 5) =&gt;
+ abc, abc, abc, abc, abc
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.chain" title="itertools.chain"><code>itertools.chain(iterA, iterB, ...)</code></a> takes an arbitrary number of iterables as input, and returns all the elements of the first iterator, then all the elements of the second, and so on, until all of the iterables have been exhausted.</p> <pre data-language="python">itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =&gt;
+ a, b, c, 1, 2, 3
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.islice" title="itertools.islice"><code>itertools.islice(iter, [start], stop, [step])</code></a> returns a stream that’s a slice of the iterator. With a single <em>stop</em> argument, it will return the first <em>stop</em> elements. If you supply a starting index, you’ll get <em>stop-start</em> elements, and if you supply a value for <em>step</em>, elements will be skipped accordingly. Unlike Python’s string and list slicing, you can’t use negative values for <em>start</em>, <em>stop</em>, or <em>step</em>.</p> <pre data-language="python">itertools.islice(range(10), 8) =&gt;
+ 0, 1, 2, 3, 4, 5, 6, 7
+itertools.islice(range(10), 2, 8) =&gt;
+ 2, 3, 4, 5, 6, 7
+itertools.islice(range(10), 2, 8, 2) =&gt;
+ 2, 4, 6
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.tee" title="itertools.tee"><code>itertools.tee(iter, [n])</code></a> replicates an iterator; it returns <em>n</em> independent iterators that will all return the contents of the source iterator. If you don’t supply a value for <em>n</em>, the default is 2. Replicating iterators requires saving some of the contents of the source iterator, so this can consume significant memory if the iterator is large and one of the new iterators is consumed more than the others.</p> <pre data-language="python">itertools.tee( itertools.count() ) =&gt;
+ iterA, iterB
+
+where iterA -&gt;
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
+
+and iterB -&gt;
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
+</pre> </section> <section id="calling-functions-on-elements"> <h3>Calling functions on elements</h3> <p>The <a class="reference internal" href="../library/operator#module-operator" title="operator: Functions corresponding to the standard operators."><code>operator</code></a> module contains a set of functions corresponding to Python’s operators. Some examples are <a class="reference internal" href="../library/operator#operator.add" title="operator.add"><code>operator.add(a, b)</code></a> (adds two values), <a class="reference internal" href="../library/operator#operator.ne" title="operator.ne"><code>operator.ne(a, b)</code></a> (same as <code>a != b</code>), and <a class="reference internal" href="../library/operator#operator.attrgetter" title="operator.attrgetter"><code>operator.attrgetter('id')</code></a> (returns a callable that fetches the <code>.id</code> attribute).</p> <p><a class="reference internal" href="../library/itertools#itertools.starmap" title="itertools.starmap"><code>itertools.starmap(func, iter)</code></a> assumes that the iterable will return a stream of tuples, and calls <em>func</em> using these tuples as the arguments:</p> <pre data-language="python">itertools.starmap(os.path.join,
+ [('/bin', 'python'), ('/usr', 'bin', 'java'),
+ ('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
+=&gt;
+ /bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
+</pre> </section> <section id="selecting-elements"> <h3>Selecting elements</h3> <p>Another group of functions chooses a subset of an iterator’s elements based on a predicate.</p> <p><a class="reference internal" href="../library/itertools#itertools.filterfalse" title="itertools.filterfalse"><code>itertools.filterfalse(predicate, iter)</code></a> is the opposite of <a class="reference internal" href="../library/functions#filter" title="filter"><code>filter()</code></a>, returning all elements for which the predicate returns false:</p> <pre data-language="python">itertools.filterfalse(is_even, itertools.count()) =&gt;
+ 1, 3, 5, 7, 9, 11, 13, 15, ...
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.takewhile" title="itertools.takewhile"><code>itertools.takewhile(predicate, iter)</code></a> returns elements for as long as the predicate returns true. Once the predicate returns false, the iterator will signal the end of its results.</p> <pre data-language="python">def less_than_10(x):
+ return x &lt; 10
+
+itertools.takewhile(less_than_10, itertools.count()) =&gt;
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
+
+itertools.takewhile(is_even, itertools.count()) =&gt;
+ 0
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.dropwhile" title="itertools.dropwhile"><code>itertools.dropwhile(predicate, iter)</code></a> discards elements while the predicate returns true, and then returns the rest of the iterable’s results.</p> <pre data-language="python">itertools.dropwhile(less_than_10, itertools.count()) =&gt;
+ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
+
+itertools.dropwhile(is_even, itertools.count()) =&gt;
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.compress" title="itertools.compress"><code>itertools.compress(data, selectors)</code></a> takes two iterators and returns only those elements of <em>data</em> for which the corresponding element of <em>selectors</em> is true, stopping whenever either one is exhausted:</p> <pre data-language="python">itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =&gt;
+ 1, 2, 5
+</pre> </section> <section id="combinatoric-functions"> <h3>Combinatoric functions</h3> <p>The <a class="reference internal" href="../library/itertools#itertools.combinations" title="itertools.combinations"><code>itertools.combinations(iterable, r)</code></a> returns an iterator giving all possible <em>r</em>-tuple combinations of the elements contained in <em>iterable</em>.</p> <pre data-language="python">itertools.combinations([1, 2, 3, 4, 5], 2) =&gt;
+ (1, 2), (1, 3), (1, 4), (1, 5),
+ (2, 3), (2, 4), (2, 5),
+ (3, 4), (3, 5),
+ (4, 5)
+
+itertools.combinations([1, 2, 3, 4, 5], 3) =&gt;
+ (1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
+ (2, 3, 4), (2, 3, 5), (2, 4, 5),
+ (3, 4, 5)
+</pre> <p>The elements within each tuple remain in the same order as <em>iterable</em> returned them. For example, the number 1 is always before 2, 3, 4, or 5 in the examples above. A similar function, <a class="reference internal" href="../library/itertools#itertools.permutations" title="itertools.permutations"><code>itertools.permutations(iterable, r=None)</code></a>, removes this constraint on the order, returning all possible arrangements of length <em>r</em>:</p> <pre data-language="python">itertools.permutations([1, 2, 3, 4, 5], 2) =&gt;
+ (1, 2), (1, 3), (1, 4), (1, 5),
+ (2, 1), (2, 3), (2, 4), (2, 5),
+ (3, 1), (3, 2), (3, 4), (3, 5),
+ (4, 1), (4, 2), (4, 3), (4, 5),
+ (5, 1), (5, 2), (5, 3), (5, 4)
+
+itertools.permutations([1, 2, 3, 4, 5]) =&gt;
+ (1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
+ ...
+ (5, 4, 3, 2, 1)
+</pre> <p>If you don’t supply a value for <em>r</em> the length of the iterable is used, meaning that all the elements are permuted.</p> <p>Note that these functions produce all of the possible combinations by position and don’t require that the contents of <em>iterable</em> are unique:</p> <pre data-language="python">itertools.permutations('aba', 3) =&gt;
+ ('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
+ ('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
+</pre> <p>The identical tuple <code>('a', 'a', 'b')</code> occurs twice, but the two ‘a’ strings came from different positions.</p> <p>The <a class="reference internal" href="../library/itertools#itertools.combinations_with_replacement" title="itertools.combinations_with_replacement"><code>itertools.combinations_with_replacement(iterable, r)</code></a> function relaxes a different constraint: elements can be repeated within a single tuple. Conceptually an element is selected for the first position of each tuple and then is replaced before the second element is selected.</p> <pre data-language="python">itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =&gt;
+ (1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
+ (2, 2), (2, 3), (2, 4), (2, 5),
+ (3, 3), (3, 4), (3, 5),
+ (4, 4), (4, 5),
+ (5, 5)
+</pre> </section> <section id="grouping-elements"> <h3>Grouping elements</h3> <p>The last function I’ll discuss, <a class="reference internal" href="../library/itertools#itertools.groupby" title="itertools.groupby"><code>itertools.groupby(iter, key_func=None)</code></a>, is the most complicated. <code>key_func(elem)</code> is a function that can compute a key value for each element returned by the iterable. If you don’t supply a key function, the key is simply each element itself.</p> <p><a class="reference internal" href="../library/itertools#itertools.groupby" title="itertools.groupby"><code>groupby()</code></a> collects all the consecutive elements from the underlying iterable that have the same key value, and returns a stream of 2-tuples containing a key value and an iterator for the elements with that key.</p> <pre data-language="python">city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
+ ('Anchorage', 'AK'), ('Nome', 'AK'),
+ ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
+ ...
+ ]
+
+def get_state(city_state):
+ return city_state[1]
+
+itertools.groupby(city_list, get_state) =&gt;
+ ('AL', iterator-1),
+ ('AK', iterator-2),
+ ('AZ', iterator-3), ...
+
+where
+iterator-1 =&gt;
+ ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
+iterator-2 =&gt;
+ ('Anchorage', 'AK'), ('Nome', 'AK')
+iterator-3 =&gt;
+ ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
+</pre> <p><a class="reference internal" href="../library/itertools#itertools.groupby" title="itertools.groupby"><code>groupby()</code></a> assumes that the underlying iterable’s contents will already be sorted based on the key. Note that the returned iterators also use the underlying iterable, so you have to consume the results of iterator-1 before requesting iterator-2 and its corresponding key.</p> </section> </section> <section id="the-functools-module"> <h2>The functools module</h2> <p>The <a class="reference internal" href="../library/functools#module-functools" title="functools: Higher-order functions and operations on callable objects."><code>functools</code></a> module contains some higher-order functions. A <strong>higher-order function</strong> takes one or more functions as input and returns a new function. The most useful tool in this module is the <a class="reference internal" href="../library/functools#functools.partial" title="functools.partial"><code>functools.partial()</code></a> function.</p> <p>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 <code>f(a, b, c)</code>; you may wish to create a new function <code>g(b, c)</code> that’s equivalent to <code>f(1, b, c)</code>; you’re filling in a value for one of <code>f()</code>’s parameters. This is called “partial function application”.</p> <p>The constructor for <a class="reference internal" href="../library/functools#functools.partial" title="functools.partial"><code>partial()</code></a> takes the arguments <code>(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)</code>. The resulting object is callable, so you can just call it to invoke <code>function</code> with the filled-in arguments.</p> <p>Here’s a small but realistic example:</p> <pre data-language="python">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')
+</pre> <p><a class="reference internal" href="../library/functools#functools.reduce" title="functools.reduce"><code>functools.reduce(func, iter, [initial_value])</code></a> cumulatively performs an operation on all the iterable’s elements and, therefore, can’t be applied to infinite iterables. <em>func</em> must be a function that takes two elements and returns a single value. <a class="reference internal" href="../library/functools#functools.reduce" title="functools.reduce"><code>functools.reduce()</code></a> takes the first two elements A and B returned by the iterator and calculates <code>func(A, B)</code>. It then requests the third element, C, calculates <code>func(func(A, B), C)</code>, combines this result with the fourth element returned, and continues until the iterable is exhausted. If the iterable returns no values at all, a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> exception is raised. If the initial value is supplied, it’s used as a starting point and <code>func(initial_value, A)</code> is the first calculation.</p> <pre data-language="python">&gt;&gt;&gt; import operator, functools
+&gt;&gt;&gt; functools.reduce(operator.concat, ['A', 'BB', 'C'])
+'ABBC'
+&gt;&gt;&gt; functools.reduce(operator.concat, [])
+Traceback (most recent call last):
+ ...
+TypeError: reduce() of empty sequence with no initial value
+&gt;&gt;&gt; functools.reduce(operator.mul, [1, 2, 3], 1)
+6
+&gt;&gt;&gt; functools.reduce(operator.mul, [], 1)
+1
+</pre> <p>If you use <a class="reference internal" href="../library/operator#operator.add" title="operator.add"><code>operator.add()</code></a> with <a class="reference internal" href="../library/functools#functools.reduce" title="functools.reduce"><code>functools.reduce()</code></a>, you’ll add up all the elements of the iterable. This case is so common that there’s a special built-in called <a class="reference internal" href="../library/functions#sum" title="sum"><code>sum()</code></a> to compute it:</p> <pre data-language="python">&gt;&gt;&gt; import functools, operator
+&gt;&gt;&gt; functools.reduce(operator.add, [1, 2, 3, 4], 0)
+10
+&gt;&gt;&gt; sum([1, 2, 3, 4])
+10
+&gt;&gt;&gt; sum([])
+0
+</pre> <p>For many uses of <a class="reference internal" href="../library/functools#functools.reduce" title="functools.reduce"><code>functools.reduce()</code></a>, though, it can be clearer to just write the obvious <a class="reference internal" href="../reference/compound_stmts#for"><code>for</code></a> loop:</p> <pre data-language="python">import functools
+# Instead of:
+product = functools.reduce(operator.mul, [1, 2, 3], 1)
+
+# You can write:
+product = 1
+for i in [1, 2, 3]:
+ product *= i
+</pre> <p>A related function is <a class="reference internal" href="../library/itertools#itertools.accumulate" title="itertools.accumulate"><code>itertools.accumulate(iterable, func=operator.add)</code></a>. It performs the same calculation, but instead of returning only the final result, <a class="reference internal" href="../library/itertools#itertools.accumulate" title="itertools.accumulate"><code>accumulate()</code></a> returns an iterator that also yields each partial result:</p> <pre data-language="python">itertools.accumulate([1, 2, 3, 4, 5]) =&gt;
+ 1, 3, 6, 10, 15
+
+itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =&gt;
+ 1, 2, 6, 24, 120
+</pre> <section id="the-operator-module"> <h3>The operator module</h3> <p>The <a class="reference internal" href="../library/operator#module-operator" title="operator: Functions corresponding to the standard operators."><code>operator</code></a> module was mentioned earlier. It contains a set of functions corresponding to Python’s operators. These functions are often useful in functional-style code because they save you from writing trivial functions that perform a single operation.</p> <p>Some of the functions in this module are:</p> <ul class="simple"> <li>Math operations: <code>add()</code>, <code>sub()</code>, <code>mul()</code>, <code>floordiv()</code>, <code>abs()</code>, …</li> <li>Logical operations: <code>not_()</code>, <code>truth()</code>.</li> <li>Bitwise operations: <code>and_()</code>, <code>or_()</code>, <code>invert()</code>.</li> <li>Comparisons: <code>eq()</code>, <code>ne()</code>, <code>lt()</code>, <code>le()</code>, <code>gt()</code>, and <code>ge()</code>.</li> <li>Object identity: <code>is_()</code>, <code>is_not()</code>.</li> </ul> <p>Consult the operator module’s documentation for a complete list.</p> </section> </section> <section id="small-functions-and-the-lambda-expression"> <h2>Small functions and the lambda expression</h2> <p>When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way.</p> <p>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:</p> <pre data-language="python">stripped_lines = [line.strip() for line in lines]
+existing_files = filter(os.path.exists, file_list)
+</pre> <p>If the function you need doesn’t exist, you need to write it. One way to write small functions is to use the <a class="reference internal" href="../reference/expressions#lambda"><code>lambda</code></a> expression. <code>lambda</code> takes a number of parameters and an expression combining these parameters, and creates an anonymous function that returns the value of the expression:</p> <pre data-language="python">adder = lambda x, y: x+y
+
+print_assign = lambda name, value: name + '=' + str(value)
+</pre> <p>An alternative is to just use the <code>def</code> statement and define a function in the usual way:</p> <pre data-language="python">def adder(x, y):
+ return x + y
+
+def print_assign(name, value):
+ return name + '=' + str(value)
+</pre> <p>Which alternative is preferable? That’s a style question; my usual course is to avoid using <code>lambda</code>.</p> <p>One reason for my preference is that <code>lambda</code> is quite limited in the functions it can define. The result has to be computable as a single expression, which means you can’t have multiway <code>if... elif... else</code> comparisons or <code>try... except</code> statements. If you try to do too much in a <code>lambda</code> statement, you’ll end up with an overly complicated expression that’s hard to read. Quick, what’s the following code doing?</p> <pre data-language="python">import functools
+total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
+</pre> <p>You can figure it out, but it takes time to disentangle the expression to figure out what’s going on. Using a short nested <code>def</code> statements makes things a little bit better:</p> <pre data-language="python">import functools
+def combine(a, b):
+ return 0, a[1] + b[1]
+
+total = functools.reduce(combine, items)[1]
+</pre> <p>But it would be best of all if I had simply used a <code>for</code> loop:</p> <pre data-language="python">total = 0
+for a, b in items:
+ total += b
+</pre> <p>Or the <a class="reference internal" href="../library/functions#sum" title="sum"><code>sum()</code></a> built-in and a generator expression:</p> <pre data-language="python">total = sum(b for a, b in items)
+</pre> <p>Many uses of <a class="reference internal" href="../library/functools#functools.reduce" title="functools.reduce"><code>functools.reduce()</code></a> are clearer when written as <code>for</code> loops.</p> <p>Fredrik Lundh once suggested the following set of rules for refactoring uses of <code>lambda</code>:</p> <ol class="arabic simple"> <li>Write a lambda function.</li> <li>Write a comment explaining what the heck that lambda does.</li> <li>Study the comment for a while, and think of a name that captures the essence of the comment.</li> <li>Convert the lambda to a def statement, using that name.</li> <li>Remove the comment.</li> </ol> <p>I really like these rules, but you’re free to disagree about whether this lambda-free style is better.</p> </section> <section id="revision-history-and-acknowledgements"> <h2>Revision History and Acknowledgements</h2> <p>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.</p> <p>Version 0.1: posted June 30 2006.</p> <p>Version 0.11: posted July 1 2006. Typo fixes.</p> <p>Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes.</p> <p>Version 0.21: Added more references suggested on the tutor mailing list.</p> <p>Version 0.30: Adds a section on the <code>functional</code> module written by Collin Winter; adds short section on the operator module; a few other edits.</p> </section> <section id="references"> <h2>References</h2> <section id="general"> <h3>General</h3> <p><strong>Structure and Interpretation of Computer Programs</strong>, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. The book can be found at <a class="reference external" href="https://mitpress.mit.edu/sicp">https://mitpress.mit.edu/sicp</a>. 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.</p> <p><a class="reference external" href="https://www.defmacro.org/ramblings/fp.html">https://www.defmacro.org/ramblings/fp.html</a>: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction.</p> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Functional_programming">https://en.wikipedia.org/wiki/Functional_programming</a>: General Wikipedia entry describing functional programming.</p> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Coroutine">https://en.wikipedia.org/wiki/Coroutine</a>: Entry for coroutines.</p> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Partial_application">https://en.wikipedia.org/wiki/Partial_application</a>: Entry for the concept of partial function application.</p> <p><a class="reference external" href="https://en.wikipedia.org/wiki/Currying">https://en.wikipedia.org/wiki/Currying</a>: Entry for the concept of currying.</p> </section> <section id="python-specific"> <h3>Python-specific</h3> <p><a class="reference external" href="https://gnosis.cx/TPiP/">https://gnosis.cx/TPiP/</a>: The first chapter of David Mertz’s book <code>Text Processing in Python</code> discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Processing”.</p> <p>Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see <a class="reference external" href="https://developer.ibm.com/articles/l-prog/">part 1</a>, <a class="reference external" href="https://developer.ibm.com/tutorials/l-prog2/">part 2</a>, and <a class="reference external" href="https://developer.ibm.com/tutorials/l-prog3/">part 3</a>,</p> </section> <section id="python-documentation"> <h3>Python documentation</h3> <p>Documentation for the <a class="reference internal" href="../library/itertools#module-itertools" title="itertools: Functions creating iterators for efficient looping."><code>itertools</code></a> module.</p> <p>Documentation for the <a class="reference internal" href="../library/functools#module-functools" title="functools: Higher-order functions and operations on callable objects."><code>functools</code></a> module.</p> <p>Documentation for the <a class="reference internal" href="../library/operator#module-operator" title="operator: Functions corresponding to the standard operators."><code>operator</code></a> module.</p> <p><span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0289/"><strong>PEP 289</strong></a>: “Generator Expressions”</p> <p><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0342/"><strong>PEP 342</strong></a>: “Coroutines via Enhanced Generators” describes the new generator features in Python 2.5.</p> </section> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/howto/functional.html" class="_attribution-link">https://docs.python.org/3.12/howto/functional.html</a>
+ </p>
+</div>