summaryrefslogtreecommitdiff
path: root/tests/lexers/rst
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2021-01-18 21:24:00 +0100
committerGeorg Brandl <georg@python.org>2021-01-18 22:08:36 +0100
commit2a3d3a7d5b9c60dedf6638d876161d9563faebcf (patch)
tree809c0b4a686db98f5954afa1944404cd9652c6b2 /tests/lexers/rst
parentf0445be718da83541ea3401aad882f3937147263 (diff)
downloadpygments-git-examplefiles.tar.gz
Move test_examplefiles to new tests/lexers scheme.examplefiles
Diffstat (limited to 'tests/lexers/rst')
-rw-r--r--tests/lexers/rst/example.txt5586
-rw-r--r--tests/lexers/rst/example2.txt4628
2 files changed, 10214 insertions, 0 deletions
diff --git a/tests/lexers/rst/example.txt b/tests/lexers/rst/example.txt
new file mode 100644
index 00000000..211b1060
--- /dev/null
+++ b/tests/lexers/rst/example.txt
@@ -0,0 +1,5586 @@
+---input---
+Functional Programming HOWTO
+================================
+
+**Version 0.30**
+
+(This is a first draft. Please send comments/error
+reports/suggestions to amk@amk.ca. This URL is probably not going to
+be the final location of the document, so be careful about linking to
+it -- you may want to add a disclaimer.)
+
+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 ``itertools`` and ``functools``.
+
+
+.. contents::
+
+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:
+
+* Most programming languages are **procedural**:
+ 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.
+
+* In **declarative** 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.
+
+* **Object-oriented** 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.
+
+* **Functional** 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.
+
+The designers of some computer languages have chosen one approach to
+programming that's emphasized. 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 frowns upon 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 ``a=3`` or ``c = a + b``, but it's
+difficult to avoid all side effects. Printing to the screen or
+writing to a disk file are side effects, for example. For example, in
+Python a ``print`` statement or a ``time.sleep(1)`` both return no
+useful value; they're only called for their side effects of sending
+some text to the screen or pausing execution for a second.
+
+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.
+* Modularity.
+* Composability.
+* Ease of debugging and testing.
+
+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 ``next()`` that takes no arguments and always
+returns the next element of the stream. If there are no more elements
+in the stream, ``next()`` must raise the ``StopIteration`` exception.
+Iterators don't have to be finite, though; it's perfectly reasonable
+to write an iterator that produces an infinite stream of data.
+
+The built-in ``iter()`` function takes an arbitrary object and tries
+to return an iterator that will return the object's contents or
+elements, raising ``TypeError`` 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
+an **iterable** object if you can get an iterator for it.
+
+You can experiment with the iteration interface manually::
+
+ >>> L = [1,2,3]
+ >>> it = iter(L)
+ >>> print it
+ <iterator object at 0x8116870>
+ >>> it.next()
+ 1
+ >>> it.next()
+ 2
+ >>> it.next()
+ 3
+ >>> it.next()
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in ?
+ StopIteration
+ >>>
+
+Python expects iterable objects in several different contexts, the
+most important being the ``for`` statement. In the statement ``for X in Y``,
+Y must be an iterator or some object for which ``iter()`` can create
+an iterator. These two statements are equivalent::
+
+ for i in iter(obj):
+ print i
+
+ for i in obj:
+ print i
+
+Iterators can be materialized as lists or tuples by using the
+``list()`` or ``tuple()`` constructor functions::
+
+ >>> 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 ``max()`` and ``min()`` can take a single
+iterator argument and will return the largest or smallest element.
+The ``"in"`` and ``"not in"`` operators also support iterators: ``X in
+iterator`` is true if X is found in the stream returned by the
+iterator. You'll run into obvious problems if the iterator is
+infinite; ``max()``, ``min()``, and ``"not in"`` will never return, and
+if the element X never appears in the stream, the ``"in"`` operator
+won't return either.
+
+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 ``next()`` 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.
+
+
+
+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 ``iter()`` on a dictionary returns an iterator that will loop
+over the dictionary's keys::
+
+ >>> 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
+ May 5
+ Jun 6
+ Jul 7
+ Jan 1
+ Apr 4
+ 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 ``iter()`` to a dictionary always loops over the keys, but
+dictionaries have methods that return other iterators. If you want to
+iterate over keys, values, or key/value pairs, you can explicitly call
+the ``iterkeys()``, ``itervalues()``, or ``iteritems()`` methods to
+get an appropriate iterator.
+
+The ``dict()`` constructor can accept an iterator that returns a
+finite stream of ``(key, value)`` tuples::
+
+ >>> 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 ``readline()``
+method until there are no more lines in the file. This means you can
+read each line of a file like this::
+
+ 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
+(http://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 ``"if"`` condition::
+
+ stripped_list = [line.strip() for line in line_list
+ if line != ""]
+
+With a list comprehension, you get back a Python list;
+``stripped_list`` 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.
+
+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
+``expression``. The ``if`` clauses are all optional; if present,
+``expression`` is only evaluated and added to the result when
+``condition`` is true.
+
+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 ``for...in`` 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, **not** in parallel. For each
+element in ``sequence1``, ``sequence2`` is looped over from the
+beginning. ``sequence3`` is then looped over for each
+resulting pair of elements from ``sequence1`` and ``sequence2``.
+
+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 ``for...in`` clauses but no
+``if`` 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::
+
+ 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
+``expression`` 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::
+
+ # 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
+``return`` 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.
+
+Here's the simplest example of a generator function::
+
+ def generate_ints(N):
+ for i in range(N):
+ yield i
+
+Any function containing a ``yield`` keyword is a generator function;
+this is detected by Python's bytecode compiler which compiles the
+function specially as a result.
+
+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 ``yield`` expression, the generator
+outputs the value of ``i``, similar to a ``return``
+statement. The big difference between ``yield`` and a
+``return`` statement is that on reaching a ``yield`` the
+generator's state of execution is suspended and local variables are
+preserved. On the next call to the generator's ``.next()`` method,
+the function will resume executing.
+
+Here's a sample usage of the ``generate_ints()`` generator::
+
+ >>> gen = generate_ints(3)
+ >>> gen
+ <generator object at 0x8117f90>
+ >>> gen.next()
+ 0
+ >>> gen.next()
+ 1
+ >>> gen.next()
+ 2
+ >>> gen.next()
+ Traceback (most recent call last):
+ File "stdin", line 1, in ?
+ File "stdin", line 2, in generate_ints
+ StopIteration
+
+You could equally write ``for i in generate_ints(5)``, or
+``a,b,c = generate_ints(3)``.
+
+Inside a generator function, the ``return`` statement can only be used
+without a value, and signals the end of the procession of values;
+after executing a ``return`` the generator cannot return any further
+values. ``return`` with a value, such as ``return 5``, is a syntax
+error inside a generator function. The end of the generator's results
+can also be indicated by raising ``StopIteration`` manually, or by
+just letting the flow of execution fall off the bottom of the
+function.
+
+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 ``self.count`` to 0, and having the
+``next()`` method increment ``self.count`` and return it.
+However, for a moderately complicated generator, writing a
+corresponding class can be much messier.
+
+The test suite included with Python's library, ``test_generators.py``,
+contains a number of more interesting examples. Here's one generator
+that implements an in-order traversal of a tree using generators
+recursively.
+
+::
+
+ # 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 ``test_generators.py`` 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).
+
+
+
+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.
+``yield`` became an expression, returning a value that can be assigned
+to a variable or otherwise operated on::
+
+ val = (yield i)
+
+I recommend that you **always** put parentheses around a ``yield``
+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.
+
+(PEP 342 explains the exact rules, which are that a
+``yield``-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 ``val = yield i`` but have to
+use parentheses when there's an operation, as in ``val = (yield i)
++ 12``.)
+
+Values are sent into a generator by calling its
+``send(value)`` method. This method resumes the
+generator's code and the ``yield`` expression returns the specified
+value. If the regular ``next()`` method is called, the
+``yield`` returns ``None``.
+
+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 ?
+ print it.next()
+ StopIteration
+
+Because ``yield`` will often be returning ``None``, you
+should always check for this case. Don't just use its value in
+expressions unless you're sure that the ``send()`` method
+will be the only method used resume your generator function.
+
+In addition to ``send()``, there are two other new methods on
+generators:
+
+* ``throw(type, value=None, traceback=None)`` is used to raise an exception inside the
+ generator; the exception is raised by the ``yield`` expression
+ where the generator's execution is paused.
+
+* ``close()`` raises a ``GeneratorExit``
+ exception inside the generator to terminate the iteration.
+ On receiving this
+ exception, the generator's code must either raise
+ ``GeneratorExit`` or ``StopIteration``; catching the
+ exception and doing anything else is illegal and will trigger
+ a ``RuntimeError``. ``close()`` will also be called by
+ Python's garbage collector when the generator is garbage-collected.
+
+ If you need to run cleanup code when a ``GeneratorExit`` occurs,
+ I suggest using a ``try: ... finally:`` suite instead of
+ catching ``GeneratorExit``.
+
+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 ``return``
+statement), but coroutines can be entered, exited, and resumed at
+many different points (the ``yield`` statements).
+
+
+Built-in functions
+----------------------------------------------
+
+Let's look in more detail at built-in functions often used with iterators.
+
+Two Python's built-in functions, ``map()`` and ``filter()``, are
+somewhat obsolete; they duplicate the features of list comprehensions
+but return actual lists instead of iterators.
+
+``map(f, iterA, iterB, ...)`` returns a list containing ``f(iterA[0],
+iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...``.
+
+::
+
+ 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 ``itertools.imap()`` function does the same thing
+but can handle infinite iterators; it'll be discussed later, in the section on
+the ``itertools`` module.
+
+``filter(predicate, iter)`` returns a list
+that contains all the sequence elements that meet a certain condition,
+and is similarly duplicated by list comprehensions.
+A **predicate** is a function that returns the truth value of
+some condition; for use with ``filter()``, the predicate must take a
+single value.
+
+::
+
+ 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]
+
+``filter()`` also has a counterpart in the ``itertools`` module,
+``itertools.ifilter()``, that returns an iterator and
+can therefore handle infinite sequences just as ``itertools.imap()`` can.
+
+``reduce(func, iter, [initial_value])`` doesn't have a counterpart in
+the ``itertools`` module because it cumulatively performs an operation
+on all the iterable's elements and therefore can't be applied to
+infinite iterables. ``func`` must be a function that takes two elements
+and returns a single value. ``reduce()`` takes the first two elements
+A and B returned by the iterator and calculates ``func(A, B)``. It
+then requests the third element, C, calculates ``func(func(A, B),
+C)``, combines this result with the fourth element returned, and
+continues until the iterable is exhausted. If the iterable returns no
+values at all, a ``TypeError`` exception is raised. If the initial
+value is supplied, it's used as a starting point and
+``func(initial_value, A)`` is the first calculation.
+
+::
+
+ import operator
+ reduce(operator.concat, ['A', 'BB', 'C']) =>
+ 'ABBC'
+ reduce(operator.concat, []) =>
+ 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 ``operator.add`` with ``reduce()``, you'll add up all the
+elements of the iterable. This case is so common that there's a special
+built-in called ``sum()`` to compute it::
+
+ reduce(operator.add, [1,2,3,4], 0) =>
+ 10
+ sum([1,2,3,4]) =>
+ 10
+ sum([]) =>
+ 0
+
+For many uses of ``reduce()``, though, it can be clearer to just write
+the obvious ``for`` loop::
+
+ # Instead of:
+ product = reduce(operator.mul, [1,2,3], 1)
+
+ # You can write:
+ product = 1
+ for i in [1,2,3]:
+ product *= i
+
+
+``enumerate(iter)`` counts off the elements in the iterable, returning
+2-tuples containing the count and each element.
+
+::
+
+ enumerate(['subject', 'verb', 'object']) =>
+ (0, 'subject'), (1, 'verb'), (2, 'object')
+
+``enumerate()`` is often used when looping through a list
+and recording the indexes at which certain conditions are met::
+
+ f = open('data.txt', 'r')
+ for i, line in enumerate(f):
+ if line.strip() == '':
+ print 'Blank line at line #%i' % i
+
+``sorted(iterable, [cmp=None], [key=None], [reverse=False)``
+collects all the elements of the iterable into a list, sorts
+the list, and returns the sorted result. The ``cmp``, ``key``,
+and ``reverse`` arguments are passed through to the
+constructed list's ``.sort()`` method.
+
+::
+
+ 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 http://wiki.python.org/moin/HowTo/Sorting.)
+
+The ``any(iter)`` and ``all(iter)`` built-ins look at
+the truth values of an iterable's contents. ``any()`` returns
+True if any element in the iterable is a true value, and ``all()``
+returns True if all of the elements are true values::
+
+ 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 statement
+----------------------------------------------
+
+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 ``lambda`` statement. ``lambda``
+takes a number of parameters and an expression combining these parameters,
+and creates a small function that returns the value of the expression::
+
+ 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`` statement and define a
+function in the usual way::
+
+ 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 ``lambda``.
+
+One reason for my preference is that ``lambda`` 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
+``if... elif... else`` comparisons or ``try... except`` statements.
+If you try to do too much in a ``lambda`` statement, you'll end up
+with an overly complicated expression that's hard to read. Quick,
+what's the following code doing?
+
+::
+
+ 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`` statements makes things a little bit better::
+
+ 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 ``for`` loop::
+
+ total = 0
+ for a, b in items:
+ total += b
+
+Or the ``sum()`` built-in and a generator expression::
+
+ total = sum(b for a,b in items)
+
+Many uses of ``reduce()`` are clearer when written as ``for`` loops.
+
+Fredrik Lundh once suggested the following set of rules for refactoring
+uses of ``lambda``:
+
+1) Write a lambda function.
+2) Write a comment explaining what the heck that lambda does.
+3) Study the comment for a while, and think of a name that captures
+ the essence of the comment.
+4) Convert the lambda to a def statement, using that name.
+5) Remove the comment.
+
+I really like these rules, but you're free to disagree that this
+lambda-free style is better.
+
+
+The itertools module
+-----------------------
+
+The ``itertools`` 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.
+
+The module's functions fall into a few broad classes:
+
+* Functions that create a new iterator based on an existing iterator.
+* Functions for treating an iterator's elements as function arguments.
+* Functions for selecting portions of an iterator's output.
+* A function for grouping an iterator's output.
+
+Creating new iterators
+''''''''''''''''''''''
+
+``itertools.count(n)`` returns an infinite stream of
+integers, increasing by 1 each time. You can optionally supply the
+starting number, which defaults to 0::
+
+ 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(iter)`` 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.
+
+::
+
+ itertools.cycle([1,2,3,4,5]) =>
+ 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
+
+``itertools.repeat(elem, [n])`` returns the provided element ``n``
+times, or returns the element endlessly if ``n`` is not provided.
+
+::
+
+ itertools.repeat('abc') =>
+ abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
+ itertools.repeat('abc', 5) =>
+ abc, abc, abc, abc, abc
+
+``itertools.chain(iterA, iterB, ...)`` 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.
+
+::
+
+ itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
+ a, b, c, 1, 2, 3
+
+``itertools.izip(iterA, iterB, ...)`` takes one element from each iterable
+and returns them in a tuple::
+
+ itertools.izip(['a', 'b', 'c'], (1, 2, 3)) =>
+ ('a', 1), ('b', 2), ('c', 3)
+
+It's similiar to the built-in ``zip()`` function, but 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
+`lazy evaluation <http://en.wikipedia.org/wiki/Lazy_evaluation>`__.)
+
+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(iter, [start], stop, [step])`` returns a stream
+that's a slice of the iterator. With a single ``stop`` argument,
+it will return the first ``stop``
+elements. If you supply a starting index, you'll get ``stop-start``
+elements, and if you supply a value for ``step``, elements will be
+skipped accordingly. Unlike Python's string and list slicing, you
+can't use negative values for ``start``, ``stop``, or ``step``.
+
+::
+
+ 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(iter, [n])`` replicates an iterator; it returns ``n``
+independent iterators that will all return the contents of the source
+iterator. If you don't supply a value for ``n``, 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.
+
+::
+
+ 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(f, iterA, iterB, ...)`` returns
+a stream containing ``f(iterA[0], iterB[0]), f(iterA[1], iterB[1]),
+f(iterA[2], iterB[2]), ...``::
+
+ itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) =>
+ 6, 8, 8
+
+The ``operator`` module contains a set of functions
+corresponding to Python's operators. Some examples are
+``operator.add(a, b)`` (adds two values),
+``operator.ne(a, b)`` (same as ``a!=b``),
+and
+``operator.attrgetter('id')`` (returns a callable that
+fetches the ``"id"`` attribute).
+
+``itertools.starmap(func, iter)`` assumes that the iterable will
+return a stream of tuples, and calls ``f()`` using these tuples as the
+arguments::
+
+ 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.
+
+``itertools.ifilter(predicate, iter)`` returns all the elements for
+which the predicate returns true::
+
+ def is_even(x):
+ return (x % 2) == 0
+
+ itertools.ifilter(is_even, itertools.count()) =>
+ 0, 2, 4, 6, 8, 10, 12, 14, ...
+
+``itertools.ifilterfalse(predicate, iter)`` is the opposite,
+returning all elements for which the predicate returns false::
+
+ itertools.ifilterfalse(is_even, itertools.count()) =>
+ 1, 3, 5, 7, 9, 11, 13, 15, ...
+
+``itertools.takewhile(predicate, iter)`` returns elements for as long
+as the predicate returns true. Once the predicate returns false,
+the iterator will signal the end of its results.
+
+::
+
+ 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(predicate, iter)`` discards elements while the
+predicate returns true, and then returns the rest of the iterable's
+results.
+
+::
+
+ 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, ``itertools.groupby(iter,
+key_func=None)``, is the most complicated. ``key_func(elem)`` 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.
+
+``groupby()`` 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.
+
+::
+
+ 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')
+
+``groupby()`` 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.
+
+
+The functools module
+----------------------------------------------
+
+The ``functools`` module in Python 2.5 contains some higher-order
+functions. A **higher-order function** takes one or more functions as
+input and returns a new function. The most useful tool in this module
+is the ``partial()`` function.
+
+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 ``f(a, b, c)``; you
+may wish to create a new function ``g(b, c)`` that's equivalent to
+``f(1, b, c)``; you're filling in a value for one of ``f()``'s parameters.
+This is called "partial function application".
+
+The constructor for ``partial`` takes the arguments ``(function, arg1,
+arg2, ... kwarg1=value1, kwarg2=value2)``. The resulting object is
+callable, so you can just call it to invoke ``function`` with the
+filled-in arguments.
+
+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 ``operator`` 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.
+
+Some of the functions in this module are:
+
+* Math operations: ``add()``, ``sub()``, ``mul()``, ``div()``, ``floordiv()``,
+ ``abs()``, ...
+* Logical operations: ``not_()``, ``truth()``.
+* Bitwise operations: ``and_()``, ``or_()``, ``invert()``.
+* Comparisons: ``eq()``, ``ne()``, ``lt()``, ``le()``, ``gt()``, and ``ge()``.
+* Object identity: ``is_()``, ``is_not()``.
+
+Consult `the operator module's documentation <http://docs.python.org/lib/module-operator.html>`__ for a complete
+list.
+
+
+
+The functional module
+---------------------
+
+Collin Winter's `functional module <http://oakwinter.com/code/functional/>`__
+provides a number of more
+advanced tools for functional programming. It also reimplements
+several Python built-ins, trying to make them more intuitive to those
+used to functional programming in other languages.
+
+This section contains an introduction to some of the most important
+functions in ``functional``; full documentation can be found at `the
+project's website <http://oakwinter.com/code/functional/documentation/>`__.
+
+``compose(outer, inner, unpack=False)``
+
+The ``compose()`` function implements function composition.
+In other words, it returns a wrapper around the ``outer`` and ``inner`` callables, such
+that the return value from ``inner`` is fed directly to ``outer``. That is,
+
+::
+
+ >>> def add(a, b):
+ ... return a + b
+ ...
+ >>> def double(a):
+ ... return 2 * a
+ ...
+ >>> compose(double, add)(5, 6)
+ 22
+
+is equivalent to
+
+::
+
+ >>> double(add(5, 6))
+ 22
+
+The ``unpack`` keyword is provided to work around the fact that Python functions are not always
+`fully curried <http://en.wikipedia.org/wiki/Currying>`__.
+By default, it is expected that the ``inner`` function will return a single object and that the ``outer``
+function will take a single argument. Setting the ``unpack`` argument causes ``compose`` to expect a
+tuple from ``inner`` which will be expanded before being passed to ``outer``. Put simply,
+
+::
+
+ compose(f, g)(5, 6)
+
+is equivalent to::
+
+ f(g(5, 6))
+
+while
+
+::
+
+ compose(f, g, unpack=True)(5, 6)
+
+is equivalent to::
+
+ f(*g(5, 6))
+
+Even though ``compose()`` only accepts two functions, it's trivial to
+build up a version that will compose any number of functions. We'll
+use ``reduce()``, ``compose()`` and ``partial()`` (the last of which
+is provided by both ``functional`` and ``functools``).
+
+::
+
+ from functional import compose, partial
+
+ multi_compose = partial(reduce, compose)
+
+
+We can also use ``map()``, ``compose()`` and ``partial()`` to craft a
+version of ``"".join(...)`` that converts its arguments to string::
+
+ from functional import compose, partial
+
+ join = compose("".join, partial(map, str))
+
+
+``flip(func)``
+
+``flip()`` wraps the callable in ``func`` and
+causes it to receive its non-keyword arguments in reverse order.
+
+::
+
+ >>> def triple(a, b, c):
+ ... return (a, b, c)
+ ...
+ >>> triple(5, 6, 7)
+ (5, 6, 7)
+ >>>
+ >>> flipped_triple = flip(triple)
+ >>> flipped_triple(5, 6, 7)
+ (7, 6, 5)
+
+``foldl(func, start, iterable)``
+
+``foldl()`` takes a binary function, a starting value (usually some kind of 'zero'), and an iterable.
+The function is applied to the starting value and the first element of the list, then the result of
+that and the second element of the list, then the result of that and the third element of the list,
+and so on.
+
+This means that a call such as::
+
+ foldl(f, 0, [1, 2, 3])
+
+is equivalent to::
+
+ f(f(f(0, 1), 2), 3)
+
+
+``foldl()`` is roughly equivalent to the following recursive function::
+
+ def foldl(func, start, seq):
+ if len(seq) == 0:
+ return start
+
+ return foldl(func, func(start, seq[0]), seq[1:])
+
+Speaking of equivalence, the above ``foldl`` call can be expressed in terms of the built-in ``reduce`` like
+so::
+
+ reduce(f, [1, 2, 3], 0)
+
+
+We can use ``foldl()``, ``operator.concat()`` and ``partial()`` to
+write a cleaner, more aesthetically-pleasing version of Python's
+``"".join(...)`` idiom::
+
+ from functional import foldl, partial
+ from operator import concat
+
+ join = partial(foldl, concat, "")
+
+
+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 ``functional`` module written by
+Collin Winter; adds short section on the operator module; a few other
+edits.
+
+
+References
+--------------------
+
+General
+'''''''''''''''
+
+**Structure and Interpretation of Computer Programs**, by
+Harold Abelson and Gerald Jay Sussman with Julie Sussman.
+Full text at http://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.
+
+http://en.wikipedia.org/wiki/Functional_programming:
+General Wikipedia entry describing functional programming.
+
+http://en.wikipedia.org/wiki/Coroutine:
+Entry for coroutines.
+
+http://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 :title-reference:`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
+`part 1 <http://www-128.ibm.com/developerworks/library/l-prog.html>`__,
+`part 2 <http://www-128.ibm.com/developerworks/library/l-prog2.html>`__, and
+`part 3 <http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>`__,
+
+
+Python documentation
+'''''''''''''''''''''''''''
+
+http://docs.python.org/lib/module-itertools.html:
+Documentation for the ``itertools`` module.
+
+http://docs.python.org/lib/module-operator.html:
+Documentation for the ``operator`` module.
+
+http://www.python.org/dev/peps/pep-0289/:
+PEP 289: "Generator Expressions"
+
+http://www.python.org/dev/peps/pep-0342/
+PEP 342: "Coroutines via Enhanced Generators" describes the new generator
+features in Python 2.5.
+
+.. comment
+
+ Topics to place
+ -----------------------------
+
+ XXX os.walk()
+
+ XXX Need a large example.
+
+ But will an example add much? I'll post a first draft and see
+ what the comments say.
+
+.. comment
+
+ Original outline:
+ Introduction
+ Idea of FP
+ Programs built out of functions
+ Functions are strictly input-output, no internal state
+ Opposed to OO programming, where objects have state
+
+ Why FP?
+ Formal provability
+ Assignment is difficult to reason about
+ Not very relevant to Python
+ Modularity
+ Small functions that do one thing
+ Debuggability:
+ Easy to test due to lack of state
+ Easy to verify output from intermediate steps
+ Composability
+ You assemble a toolbox of functions that can be mixed
+
+ Tackling a problem
+ Need a significant example
+
+ Iterators
+ Generators
+ The itertools module
+ List comprehensions
+ Small functions and the lambda statement
+ Built-in functions
+ map
+ filter
+ reduce
+
+.. comment
+
+ Handy little function for printing part of an iterator -- used
+ while writing this document.
+
+ import itertools
+ def print_iter(it):
+ slice = itertools.islice(it, 10)
+ for elem in slice[:-1]:
+ sys.stdout.write(str(elem))
+ sys.stdout.write(', ')
+ print elem[-1]
+
+
+
+---tokens---
+'Functional Programming HOWTO' Generic.Heading
+'\n' Text
+
+'================================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'**Version 0.30**' Generic.Strong
+'\n' Text
+
+'\n' Text
+
+'(This is a first draft. Please send comments/error' Text
+'\n' Text
+
+'reports/suggestions to amk@amk.ca. This URL is probably not going to' Text
+'\n' Text
+
+'be the final location of the document, so be careful about linking to' Text
+'\n' Text
+
+'it -- you may want to add a disclaimer.)' Text
+'\n' Text
+
+'\n' Text
+
+"In this document, we'll take a tour of Python's features suitable for" Text
+'\n' Text
+
+'implementing programs in a functional style. After an introduction to' Text
+'\n' Text
+
+"the concepts of functional programming, we'll look at language" Text
+'\n' Text
+
+'features such as iterators and generators and relevant library modules' Text
+'\n' Text
+
+'such as ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'functools' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'contents' Operator.Word
+'::' Punctuation
+'\n' Text
+
+'\n' Text
+
+'Introduction' Generic.Heading
+'\n' Text
+
+'----------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'This section explains the basic concept of functional programming; if' Text
+'\n' Text
+
+"you're just interested in learning about Python language features," Text
+'\n' Text
+
+'skip to the next section.' Text
+'\n' Text
+
+'\n' Text
+
+'Programming languages support decomposing problems in several different ' Text
+'\n' Text
+
+'ways' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' Most programming languages are ' Text
+'**procedural**' Generic.Strong
+':' Text
+' ' Text
+'\n' Text
+
+' programs are lists of instructions that tell the computer what to' Text
+'\n' Text
+
+" do with the program's input." Text
+'\n' Text
+
+' C, Pascal, and even Unix shells are procedural languages.' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' In ' Text
+'**declarative**' Generic.Strong
+' languages, you write a specification that describes ' Text
+'\n' Text
+
+' the problem to be solved, and the language implementation figures out ' Text
+'\n' Text
+
+' how to perform the computation efficiently. SQL is the declarative ' Text
+'\n' Text
+
+" language you're most likely to be familiar with; a SQL query describes" Text
+'\n' Text
+
+' the data set you want to retrieve, and the SQL engine decides whether to ' Text
+'\n' Text
+
+' scan tables or use indexes, which subclauses should be performed first,' Text
+'\n' Text
+
+' etc.' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' ' Text
+'**Object-oriented**' Generic.Strong
+' programs manipulate collections of objects.' Text
+'\n' Text
+
+' Objects have internal state and support methods that query or modify' Text
+'\n' Text
+
+' this internal state in some way. Smalltalk and Java are' Text
+'\n' Text
+
+' object-oriented languages. C++ and Python are languages that' Text
+'\n' Text
+
+" support object-oriented programming, but don't force the use " Text
+'\n' Text
+
+' of object-oriented features.' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' ' Text
+'**Functional**' Generic.Strong
+' programming decomposes a problem into a set of functions.' Text
+'\n' Text
+
+" Ideally, functions only take inputs and produce outputs, and don't have any " Text
+'\n' Text
+
+' internal state that affects the output produced for a given input.' Text
+'\n' Text
+
+' Well-known functional languages include the ML family (Standard ML,' Text
+'\n' Text
+
+' OCaml, and other variants) and Haskell.' Text
+'\n' Text
+
+'\n' Text
+
+'The designers of some computer languages have chosen one approach to ' Text
+'\n' Text
+
+"programming that's emphasized. This often makes it difficult to" Text
+'\n' Text
+
+'write programs that use a different approach. Other languages are' Text
+'\n' Text
+
+'multi-paradigm languages that support several different approaches. Lisp,' Text
+'\n' Text
+
+'C++, and Python are multi-paradigm; you can write programs or' Text
+'\n' Text
+
+'libraries that are largely procedural, object-oriented, or functional' Text
+'\n' Text
+
+'in all of these languages. In a large program, different sections' Text
+'\n' Text
+
+'might be written using different approaches; the GUI might be object-oriented' Text
+'\n' Text
+
+'while the processing logic is procedural or functional, for example.' Text
+'\n' Text
+
+'\n' Text
+
+'In a functional program, input flows through a set of functions. Each' Text
+'\n' Text
+
+'function operates on its input and produces some output. Functional' Text
+'\n' Text
+
+'style frowns upon functions with side effects that modify internal' Text
+'\n' Text
+
+"state or make other changes that aren't visible in the function's" Text
+'\n' Text
+
+'return value. Functions that have no side effects at all are ' Text
+'\n' Text
+
+'called ' Text
+'**purely functional**' Generic.Strong
+'.' Text
+'\n' Text
+
+'Avoiding side effects means not using data structures' Text
+'\n' Text
+
+"that get updated as a program runs; every function's output " Text
+'\n' Text
+
+'must only depend on its input.' Text
+'\n' Text
+
+'\n' Text
+
+"Some languages are very strict about purity and don't even have" Text
+'\n' Text
+
+'assignment statements such as ' Text
+'``' Literal.String
+'a=3' Literal.String
+'``' Literal.String
+' or ' Text
+'``' Literal.String
+'c = a + b' Literal.String
+'``' Literal.String
+", but it's" Text
+'\n' Text
+
+'difficult to avoid all side effects. Printing to the screen or' Text
+'\n' Text
+
+'writing to a disk file are side effects, for example. For example, in' Text
+'\n' Text
+
+'Python a ' Text
+'``' Literal.String
+'print' Literal.String
+'``' Literal.String
+' statement or a ' Text
+'``' Literal.String
+'time.sleep(1)' Literal.String
+'``' Literal.String
+' both return no' Text
+'\n' Text
+
+"useful value; they're only called for their side effects of sending" Text
+'\n' Text
+
+'some text to the screen or pausing execution for a second.' Text
+'\n' Text
+
+'\n' Text
+
+"Python programs written in functional style usually won't go to the" Text
+'\n' Text
+
+"extreme of avoiding all I/O or all assignments; instead, they'll" Text
+'\n' Text
+
+'provide a functional-appearing interface but will use non-functional' Text
+'\n' Text
+
+'features internally. For example, the implementation of a function' Text
+'\n' Text
+
+"will still use assignments to local variables, but won't modify global" Text
+'\n' Text
+
+'variables or have other side effects.' Text
+'\n' Text
+
+'\n' Text
+
+'Functional programming can be considered the opposite of' Text
+'\n' Text
+
+'object-oriented programming. Objects are little capsules containing' Text
+'\n' Text
+
+'some internal state along with a collection of method calls that let' Text
+'\n' Text
+
+'you modify this state, and programs consist of making the right set of' Text
+'\n' Text
+
+'state changes. Functional programming wants to avoid state changes as' Text
+'\n' Text
+
+'much as possible and works with data flowing between functions. In' Text
+'\n' Text
+
+'Python you might combine the two approaches by writing functions that' Text
+'\n' Text
+
+'take and return instances representing objects in your application' Text
+'\n' Text
+
+'(e-mail messages, transactions, etc.).' Text
+'\n' Text
+
+'\n' Text
+
+'Functional design may seem like an odd constraint to work under. Why' Text
+'\n' Text
+
+'should you avoid objects and side effects? There are theoretical and' Text
+'\n' Text
+
+'practical advantages to the functional style' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' Formal provability.' Text
+'\n' Text
+
+'*' Literal.Number
+' Modularity.' Text
+'\n' Text
+
+'*' Literal.Number
+' Composability.' Text
+'\n' Text
+
+'*' Literal.Number
+' Ease of debugging and testing.' Text
+'\n' Text
+
+'\n' Text
+
+'Formal provability' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"A theoretical benefit is that it's easier to construct a mathematical proof" Text
+'\n' Text
+
+'that a functional program is correct.' Text
+'\n' Text
+
+'\n' Text
+
+'For a long time researchers have been interested in finding ways to' Text
+'\n' Text
+
+'mathematically prove programs correct. This is different from testing' Text
+'\n' Text
+
+'a program on numerous inputs and concluding that its output is usually' Text
+'\n' Text
+
+"correct, or reading a program's source code and concluding that the" Text
+'\n' Text
+
+'code looks right; the goal is instead a rigorous proof that a program' Text
+'\n' Text
+
+'produces the right result for all possible inputs.' Text
+'\n' Text
+
+'\n' Text
+
+'The technique used to prove programs correct is to write down ' Text
+'\n' Text
+
+'**invariants**' Generic.Strong
+", properties of the input data and of the program's " Text
+'\n' Text
+
+'variables that are always true. For each line of code, you then show ' Text
+'\n' Text
+
+'that if invariants X and Y are true ' Text
+'**before**' Generic.Strong
+' the line is executed, ' Text
+'\n' Text
+
+"the slightly different invariants X' and Y' are true " Text
+'**after**' Generic.Strong
+'\n' Text
+
+'the line is executed. This continues until you reach the end of the' Text
+'\n' Text
+
+'program, at which point the invariants should match the desired ' Text
+'\n' Text
+
+"conditions on the program's output." Text
+'\n' Text
+
+'\n' Text
+
+"Functional programming's avoidance of assignments arose because " Text
+'\n' Text
+
+'assignments are difficult to handle with this technique; ' Text
+'\n' Text
+
+'assignments can break invariants that were true before the assignment' Text
+'\n' Text
+
+'without producing any new invariants that can be propagated onward.' Text
+'\n' Text
+
+'\n' Text
+
+'Unfortunately, proving programs correct is largely impractical and not' Text
+'\n' Text
+
+'relevant to Python software. Even trivial programs require proofs that' Text
+'\n' Text
+
+'are several pages long; the proof of correctness for a moderately' Text
+'\n' Text
+
+'complicated program would be enormous, and few or none of the programs' Text
+'\n' Text
+
+'you use daily (the Python interpreter, your XML parser, your web' Text
+'\n' Text
+
+'browser) could be proven correct. Even if you wrote down or generated' Text
+'\n' Text
+
+'a proof, there would then be the question of verifying the proof;' Text
+'\n' Text
+
+"maybe there's an error in it, and you wrongly believe you've proved" Text
+'\n' Text
+
+'the program correct.' Text
+'\n' Text
+
+'\n' Text
+
+'Modularity' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'A more practical benefit of functional programming is that it forces' Text
+'\n' Text
+
+'you to break apart your problem into small pieces. Programs are more' Text
+'\n' Text
+
+"modular as a result. It's easier to specify and write a small" Text
+'\n' Text
+
+'function that does one thing than a large function that performs a' Text
+'\n' Text
+
+'complicated transformation. Small functions are also easier to read' Text
+'\n' Text
+
+'and to check for errors.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Ease of debugging and testing ' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Testing and debugging a functional-style program is easier.' Text
+'\n' Text
+
+'\n' Text
+
+'Debugging is simplified because functions are generally small and' Text
+'\n' Text
+
+"clearly specified. When a program doesn't work, each function is an" Text
+'\n' Text
+
+'interface point where you can check that the data are correct. You' Text
+'\n' Text
+
+'can look at the intermediate inputs and outputs to quickly isolate the' Text
+'\n' Text
+
+"function that's responsible for a bug." Text
+'\n' Text
+
+'\n' Text
+
+'Testing is easier because each function is a potential subject for a' Text
+'\n' Text
+
+"unit test. Functions don't depend on system state that needs to be" Text
+'\n' Text
+
+'replicated before running a test; instead you only have to synthesize' Text
+'\n' Text
+
+'the right input and then check that the output matches expectations.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Composability' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"As you work on a functional-style program, you'll write a number of" Text
+'\n' Text
+
+'functions with varying inputs and outputs. Some of these functions' Text
+'\n' Text
+
+'will be unavoidably specialized to a particular application, but' Text
+'\n' Text
+
+'others will be useful in a wide variety of programs. For example, a' Text
+'\n' Text
+
+'function that takes a directory path and returns all the XML files in' Text
+'\n' Text
+
+'the directory, or a function that takes a filename and returns its' Text
+'\n' Text
+
+'contents, can be applied to many different situations.' Text
+'\n' Text
+
+'\n' Text
+
+"Over time you'll form a personal library of utilities. Often you'll" Text
+'\n' Text
+
+'assemble new programs by arranging existing functions in a new' Text
+'\n' Text
+
+'configuration and writing a few functions specialized for the current' Text
+'\n' Text
+
+'task.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Iterators' Generic.Heading
+'\n' Text
+
+'-----------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"I'll start by looking at a Python language feature that's an important" Text
+'\n' Text
+
+'foundation for writing functional-style programs' Text
+':' Text
+' iterators.' Text
+'\n' Text
+
+'\n' Text
+
+'An iterator is an object representing a stream of data; this object' Text
+'\n' Text
+
+'returns the data one element at a time. A Python iterator must' Text
+'\n' Text
+
+'support a method called ' Text
+'``' Literal.String
+'next()' Literal.String
+'``' Literal.String
+' that takes no arguments and always' Text
+'\n' Text
+
+'returns the next element of the stream. If there are no more elements' Text
+'\n' Text
+
+'in the stream, ' Text
+'``' Literal.String
+'next()' Literal.String
+'``' Literal.String
+' must raise the ' Text
+'``' Literal.String
+'StopIteration' Literal.String
+'``' Literal.String
+' exception.' Text
+'\n' Text
+
+"Iterators don't have to be finite, though; it's perfectly reasonable" Text
+'\n' Text
+
+'to write an iterator that produces an infinite stream of data.' Text
+'\n' Text
+
+'\n' Text
+
+'The built-in ' Text
+'``' Literal.String
+'iter()' Literal.String
+'``' Literal.String
+' function takes an arbitrary object and tries' Text
+'\n' Text
+
+"to return an iterator that will return the object's contents or" Text
+'\n' Text
+
+'elements, raising ' Text
+'``' Literal.String
+'TypeError' Literal.String
+'``' Literal.String
+" if the object doesn't support" Text
+'\n' Text
+
+"iteration. Several of Python's built-in data types support iteration," Text
+'\n' Text
+
+'the most common being lists and dictionaries. An object is called ' Text
+'\n' Text
+
+'an ' Text
+'**iterable**' Generic.Strong
+' object if you can get an iterator for it.' Text
+'\n' Text
+
+'\n' Text
+
+'You can experiment with the iteration interface manually' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> L = [1,2,3]' Literal.String
+'\n' Text
+
+' >>> it = iter(L)\n >>> print it\n <iterator object at 0x8116870>\n >>> it.next()\n 1\n >>> it.next()\n 2\n >>> it.next()\n 3\n >>> it.next()\n Traceback (most recent call last):\n File "<stdin>", line 1, in ?\n StopIteration\n >>> \n\n' Literal.String
+
+'Python expects iterable objects in several different contexts, the ' Text
+'\n' Text
+
+'most important being the ' Text
+'``' Literal.String
+'for' Literal.String
+'``' Literal.String
+' statement. In the statement ' Text
+'``' Literal.String
+'for X in Y' Literal.String
+'``' Literal.String
+',' Text
+'\n' Text
+
+'Y must be an iterator or some object for which ' Text
+'``' Literal.String
+'iter()' Literal.String
+'``' Literal.String
+' can create ' Text
+'\n' Text
+
+'an iterator. These two statements are equivalent' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'for i in iter(obj):' Literal.String
+'\n' Text
+
+' print i\n\n for i in obj:\n print i\n\n' Literal.String
+
+'Iterators can be materialized as lists or tuples by using the' Text
+'\n' Text
+
+'``' Literal.String
+'list()' Literal.String
+'``' Literal.String
+' or ' Text
+'``' Literal.String
+'tuple()' Literal.String
+'``' Literal.String
+' constructor functions' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> L = [1,2,3]' Literal.String
+'\n' Text
+
+' >>> iterator = iter(L)\n >>> t = tuple(iterator)\n >>> t\n (1, 2, 3)\n\n' Literal.String
+
+'Sequence unpacking also supports iterators' Text
+':' Text
+' if you know an iterator ' Text
+'\n' Text
+
+'will return N elements, you can unpack them into an N-tuple' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> L = [1,2,3]' Literal.String
+'\n' Text
+
+' >>> iterator = iter(L)\n >>> a,b,c = iterator\n >>> a,b,c\n (1, 2, 3)\n\n' Literal.String
+
+'Built-in functions such as ' Text
+'``' Literal.String
+'max()' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'min()' Literal.String
+'``' Literal.String
+' can take a single' Text
+'\n' Text
+
+'iterator argument and will return the largest or smallest element.' Text
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'"in"' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'"not in"' Literal.String
+'``' Literal.String
+' operators also support iterators' Text
+':' Text
+' ' Text
+'``' Literal.String
+'X in\niterator' Literal.String
+'``' Literal.String
+' is true if X is found in the stream returned by the' Text
+'\n' Text
+
+"iterator. You'll run into obvious problems if the iterator is" Text
+'\n' Text
+
+'infinite; ' Text
+'``' Literal.String
+'max()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'min()' Literal.String
+'``' Literal.String
+', and ' Text
+'``' Literal.String
+'"not in"' Literal.String
+'``' Literal.String
+' will never return, and' Text
+'\n' Text
+
+'if the element X never appears in the stream, the ' Text
+'``' Literal.String
+'"in"' Literal.String
+'``' Literal.String
+' operator' Text
+'\n' Text
+
+"won't return either." Text
+'\n' Text
+
+'\n' Text
+
+"Note that you can only go forward in an iterator; there's no way to" Text
+'\n' Text
+
+'get the previous element, reset the iterator, or make a copy of it.' Text
+'\n' Text
+
+'Iterator objects can optionally provide these additional capabilities,' Text
+'\n' Text
+
+'but the iterator protocol only specifies the ' Text
+'``' Literal.String
+'next()' Literal.String
+'``' Literal.String
+' method.' Text
+'\n' Text
+
+"Functions may therefore consume all of the iterator's output, and if" Text
+'\n' Text
+
+"you need to do something different with the same stream, you'll have" Text
+'\n' Text
+
+'to create a new iterator.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Data Types That Support Iterators' Generic.Heading
+'\n' Text
+
+"'''''''''''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"We've already seen how lists and tuples support iterators. In fact," Text
+'\n' Text
+
+'any Python sequence type, such as strings, will automatically support' Text
+'\n' Text
+
+'creation of an iterator.' Text
+'\n' Text
+
+'\n' Text
+
+'Calling ' Text
+'``' Literal.String
+'iter()' Literal.String
+'``' Literal.String
+' on a dictionary returns an iterator that will loop' Text
+'\n' Text
+
+"over the dictionary's keys" Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+">>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6," Literal.String
+'\n' Text
+
+" ... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}\n >>> for key in m:\n ... print key, m[key]\n Mar 3\n Feb 2\n Aug 8\n Sep 9\n May 5\n Jun 6\n Jul 7\n Jan 1\n Apr 4\n Nov 11\n Dec 12\n Oct 10\n\n" Literal.String
+
+"Note that the order is essentially random, because it's based on the" Text
+'\n' Text
+
+'hash ordering of the objects in the dictionary.' Text
+'\n' Text
+
+'\n' Text
+
+'Applying ' Text
+'``' Literal.String
+'iter()' Literal.String
+'``' Literal.String
+' to a dictionary always loops over the keys, but' Text
+'\n' Text
+
+'dictionaries have methods that return other iterators. If you want to' Text
+'\n' Text
+
+'iterate over keys, values, or key/value pairs, you can explicitly call' Text
+'\n' Text
+
+'the ' Text
+'``' Literal.String
+'iterkeys()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'itervalues()' Literal.String
+'``' Literal.String
+', or ' Text
+'``' Literal.String
+'iteritems()' Literal.String
+'``' Literal.String
+' methods to' Text
+'\n' Text
+
+'get an appropriate iterator.' Text
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'dict()' Literal.String
+'``' Literal.String
+' constructor can accept an iterator that returns a' Text
+'\n' Text
+
+'finite stream of ' Text
+'``' Literal.String
+'(key, value)' Literal.String
+'``' Literal.String
+' tuples' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+">>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]" Literal.String
+'\n' Text
+
+" >>> dict(iter(L))\n {'Italy': 'Rome', 'US': 'Washington DC', 'France': 'Paris'}\n\n" Literal.String
+
+'Files also support iteration by calling the ' Text
+'``' Literal.String
+'readline()' Literal.String
+'``' Literal.String
+'\n' Text
+
+'method until there are no more lines in the file. This means you can' Text
+'\n' Text
+
+'read each line of a file like this' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'for line in file:' Literal.String
+'\n' Text
+
+' # do something for each line\n ...\n\n' Literal.String
+
+'Sets can take their contents from an iterable and let you iterate over' Text
+'\n' Text
+
+"the set's elements" Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'S = set((2, 3, 5, 7, 11, 13))' Literal.String
+'\n' Text
+
+' for i in S:\n print i\n\n\n\n' Literal.String
+
+'Generator expressions and list comprehensions' Generic.Heading
+'\n' Text
+
+'----------------------------------------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"Two common operations on an iterator's output are 1) performing some" Text
+'\n' Text
+
+'operation for every element, 2) selecting a subset of elements that' Text
+'\n' Text
+
+'meet some condition. For example, given a list of strings, you might' Text
+'\n' Text
+
+'want to strip off trailing whitespace from each line or extract all' Text
+'\n' Text
+
+'the strings containing a given substring.' Text
+'\n' Text
+
+'\n' Text
+
+'List comprehensions and generator expressions (short form' Text
+':' Text
+' "listcomps"' Text
+'\n' Text
+
+'and "genexps") are a concise notation for such operations, borrowed' Text
+'\n' Text
+
+'from the functional programming language Haskell' Text
+'\n' Text
+
+'(http' Text
+':' Text
+'//www.haskell.org). You can strip all the whitespace from a' Text
+'\n' Text
+
+'stream of strings with the following code' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"line_list = [' line 1\\n', 'line 2 \\n', ...]" Literal.String
+'\n' Text
+
+'\n # Generator expression -- returns iterator\n stripped_iter = (line.strip() for line in line_list)\n\n # List comprehension -- returns list\n stripped_list = [line.strip() for line in line_list]\n\n' Literal.String
+
+'You can select only certain elements by adding an ' Text
+'``' Literal.String
+'"if"' Literal.String
+'``' Literal.String
+' condition' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'stripped_list = [line.strip() for line in line_list' Literal.String
+'\n' Text
+
+' if line != ""]\n\n' Literal.String
+
+'With a list comprehension, you get back a Python list;' Text
+'\n' Text
+
+'``' Literal.String
+'stripped_list' Literal.String
+'``' Literal.String
+' is a list containing the resulting lines, not an' Text
+'\n' Text
+
+'iterator. Generator expressions return an iterator that computes the' Text
+'\n' Text
+
+'values as necessary, not needing to materialize all the values at' Text
+'\n' Text
+
+"once. This means that list comprehensions aren't useful if you're" Text
+'\n' Text
+
+'working with iterators that return an infinite stream or a very large' Text
+'\n' Text
+
+'amount of data. Generator expressions are preferable in these' Text
+'\n' Text
+
+'situations.' Text
+'\n' Text
+
+'\n' Text
+
+'Generator expressions are surrounded by parentheses ("()") and list' Text
+'\n' Text
+
+'comprehensions are surrounded by square brackets ("' Text
+'[' Text
+']"). Generator' Text
+'\n' Text
+
+'expressions have the form' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'( expression for expr in sequence1 ' Literal.String
+'\n' Text
+
+' if condition1\n for expr2 in sequence2\n if condition2\n for expr3 in sequence3 ...\n if condition3\n for exprN in sequenceN\n if conditionN )\n\n' Literal.String
+
+'Again, for a list comprehension only the outside brackets are' Text
+'\n' Text
+
+'different (square brackets instead of parentheses).' Text
+'\n' Text
+
+'\n' Text
+
+'The elements of the generated output will be the successive values of' Text
+'\n' Text
+
+'``' Literal.String
+'expression' Literal.String
+'``' Literal.String
+'. The ' Text
+'``' Literal.String
+'if' Literal.String
+'``' Literal.String
+' clauses are all optional; if present,' Text
+'\n' Text
+
+'``' Literal.String
+'expression' Literal.String
+'``' Literal.String
+' is only evaluated and added to the result when' Text
+'\n' Text
+
+'``' Literal.String
+'condition' Literal.String
+'``' Literal.String
+' is true.' Text
+'\n' Text
+
+'\n' Text
+
+'Generator expressions always have to be written inside parentheses,' Text
+'\n' Text
+
+'but the parentheses signalling a function call also count. If you' Text
+'\n' Text
+
+'want to create an iterator that will be immediately passed to a' Text
+'\n' Text
+
+'function you can write' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'obj_total = sum(obj.count for obj in list_all_objects())' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'The ' Text
+'``' Literal.String
+'for...in' Literal.String
+'``' Literal.String
+' clauses contain the sequences to be iterated over.' Text
+'\n' Text
+
+'The sequences do not have to be the same length, because they are' Text
+'\n' Text
+
+'iterated over from left to right, ' Text
+'**not**' Generic.Strong
+' in parallel. For each' Text
+'\n' Text
+
+'element in ' Text
+'``' Literal.String
+'sequence1' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'sequence2' Literal.String
+'``' Literal.String
+' is looped over from the' Text
+'\n' Text
+
+'beginning. ' Text
+'``' Literal.String
+'sequence3' Literal.String
+'``' Literal.String
+' is then looped over for each ' Text
+'\n' Text
+
+'resulting pair of elements from ' Text
+'``' Literal.String
+'sequence1' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'sequence2' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'To put it another way, a list comprehension or generator expression is' Text
+'\n' Text
+
+'equivalent to the following Python code' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'for expr1 in sequence1:' Literal.String
+'\n' Text
+
+' if not (condition1):\n continue # Skip this element\n for expr2 in sequence2:\n if not (condition2):\n continue # Skip this element\n ...\n for exprN in sequenceN:\n if not (conditionN):\n continue # Skip this element\n\n # Output the value of \n # the expression.\n\n' Literal.String
+
+'This means that when there are multiple ' Text
+'``' Literal.String
+'for...in' Literal.String
+'``' Literal.String
+' clauses but no' Text
+'\n' Text
+
+'``' Literal.String
+'if' Literal.String
+'``' Literal.String
+' clauses, the length of the resulting output will be equal to' Text
+'\n' Text
+
+'the product of the lengths of all the sequences. If you have two' Text
+'\n' Text
+
+'lists of length 3, the output list is 9 elements long' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"seq1 = 'abc'" Literal.String
+'\n' Text
+
+" seq2 = (1,2,3)\n >>> [ (x,y) for x in seq1 for y in seq2]\n [('a', 1), ('a', 2), ('a', 3), \n ('b', 1), ('b', 2), ('b', 3), \n ('c', 1), ('c', 2), ('c', 3)]\n\n" Literal.String
+
+"To avoid introducing an ambiguity into Python's grammar, if" Text
+'\n' Text
+
+'``' Literal.String
+'expression' Literal.String
+'``' Literal.String
+' is creating a tuple, it must be surrounded with' Text
+'\n' Text
+
+'parentheses. The first list comprehension below is a syntax error,' Text
+'\n' Text
+
+'while the second one is correct' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'# Syntax error' Literal.String
+'\n' Text
+
+' [ x,y for x in seq1 for y in seq2]\n # Correct\n [ (x,y) for x in seq1 for y in seq2]\n\n\n' Literal.String
+
+'Generators' Generic.Heading
+'\n' Text
+
+'-----------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Generators are a special class of functions that simplify the task of' Text
+'\n' Text
+
+'writing iterators. Regular functions compute a value and return it,' Text
+'\n' Text
+
+'but generators return an iterator that returns a stream of values.' Text
+'\n' Text
+
+'\n' Text
+
+"You're doubtless familiar with how regular function calls work in" Text
+'\n' Text
+
+'Python or C. When you call a function, it gets a private namespace' Text
+'\n' Text
+
+'where its local variables are created. When the function reaches a' Text
+'\n' Text
+
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+' statement, the local variables are destroyed and the' Text
+'\n' Text
+
+'value is returned to the caller. A later call to the same function' Text
+'\n' Text
+
+'creates a new private namespace and a fresh set of local' Text
+'\n' Text
+
+"variables. But, what if the local variables weren't thrown away on" Text
+'\n' Text
+
+'exiting a function? What if you could later resume the function where' Text
+'\n' Text
+
+'it left off? This is what generators provide; they can be thought of' Text
+'\n' Text
+
+'as resumable functions.' Text
+'\n' Text
+
+'\n' Text
+
+"Here's the simplest example of a generator function" Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def generate_ints(N):' Literal.String
+'\n' Text
+
+' for i in range(N):\n yield i\n\n' Literal.String
+
+'Any function containing a ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' keyword is a generator function;' Text
+'\n' Text
+
+"this is detected by Python's bytecode compiler which compiles the" Text
+'\n' Text
+
+'function specially as a result.' Text
+'\n' Text
+
+'\n' Text
+
+"When you call a generator function, it doesn't return a single value;" Text
+'\n' Text
+
+'instead it returns a generator object that supports the iterator' Text
+'\n' Text
+
+'protocol. On executing the ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' expression, the generator' Text
+'\n' Text
+
+'outputs the value of ' Text
+'``' Literal.String
+'i' Literal.String
+'``' Literal.String
+', similar to a ' Text
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+'\n' Text
+
+'statement. The big difference between ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' and a' Text
+'\n' Text
+
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+' statement is that on reaching a ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' the' Text
+'\n' Text
+
+"generator's state of execution is suspended and local variables are" Text
+'\n' Text
+
+"preserved. On the next call to the generator's " Text
+'``' Literal.String
+'.next()' Literal.String
+'``' Literal.String
+' method,' Text
+'\n' Text
+
+'the function will resume executing. ' Text
+'\n' Text
+
+'\n' Text
+
+"Here's a sample usage of the " Text
+'``' Literal.String
+'generate_ints()' Literal.String
+'``' Literal.String
+' generator' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> gen = generate_ints(3)' Literal.String
+'\n' Text
+
+' >>> gen\n <generator object at 0x8117f90>\n >>> gen.next()\n 0\n >>> gen.next()\n 1\n >>> gen.next()\n 2\n >>> gen.next()\n Traceback (most recent call last):\n File "stdin", line 1, in ?\n File "stdin", line 2, in generate_ints\n StopIteration\n\n' Literal.String
+
+'You could equally write ' Text
+'``' Literal.String
+'for i in generate_ints(5)' Literal.String
+'``' Literal.String
+', or' Text
+'\n' Text
+
+'``' Literal.String
+'a,b,c = generate_ints(3)' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Inside a generator function, the ' Text
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+' statement can only be used' Text
+'\n' Text
+
+'without a value, and signals the end of the procession of values;' Text
+'\n' Text
+
+'after executing a ' Text
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+' the generator cannot return any further' Text
+'\n' Text
+
+'values. ' Text
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+' with a value, such as ' Text
+'``' Literal.String
+'return 5' Literal.String
+'``' Literal.String
+', is a syntax' Text
+'\n' Text
+
+"error inside a generator function. The end of the generator's results" Text
+'\n' Text
+
+'can also be indicated by raising ' Text
+'``' Literal.String
+'StopIteration' Literal.String
+'``' Literal.String
+' manually, or by' Text
+'\n' Text
+
+'just letting the flow of execution fall off the bottom of the' Text
+'\n' Text
+
+'function.' Text
+'\n' Text
+
+'\n' Text
+
+'You could achieve the effect of generators manually by writing your' Text
+'\n' Text
+
+'own class and storing all the local variables of the generator as' Text
+'\n' Text
+
+'instance variables. For example, returning a list of integers could' Text
+'\n' Text
+
+'be done by setting ' Text
+'``' Literal.String
+'self.count' Literal.String
+'``' Literal.String
+' to 0, and having the' Text
+'\n' Text
+
+'``' Literal.String
+'next()' Literal.String
+'``' Literal.String
+' method increment ' Text
+'``' Literal.String
+'self.count' Literal.String
+'``' Literal.String
+' and return it.' Text
+'\n' Text
+
+'However, for a moderately complicated generator, writing a' Text
+'\n' Text
+
+'corresponding class can be much messier.' Text
+'\n' Text
+
+'\n' Text
+
+"The test suite included with Python's library, " Text
+'``' Literal.String
+'test_generators.py' Literal.String
+'``' Literal.String
+',' Text
+'\n' Text
+
+"contains a number of more interesting examples. Here's one generator" Text
+'\n' Text
+
+'that implements an in-order traversal of a tree using generators' Text
+'\n' Text
+
+'recursively.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'# A recursive generator that generates Tree leaves in in-order.' Literal.String
+'\n' Text
+
+' def inorder(t):\n if t:\n for x in inorder(t.left):\n yield x\n\n yield t.label\n\n for x in inorder(t.right):\n yield x\n\n' Literal.String
+
+'Two other examples in ' Text
+'``' Literal.String
+'test_generators.py' Literal.String
+'``' Literal.String
+' produce' Text
+'\n' Text
+
+'solutions for the N-Queens problem (placing N queens on an NxN' Text
+'\n' Text
+
+"chess board so that no queen threatens another) and the Knight's Tour" Text
+'\n' Text
+
+'(finding a route that takes a knight to every square of an NxN chessboard' Text
+'\n' Text
+
+'without visiting any square twice).' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Passing values into a generator' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'In Python 2.4 and earlier, generators only produced output. Once a' Text
+'\n' Text
+
+"generator's code was invoked to create an iterator, there was no way to" Text
+'\n' Text
+
+'pass any new information into the function when its execution is' Text
+'\n' Text
+
+'resumed. You could hack together this ability by making the' Text
+'\n' Text
+
+'generator look at a global variable or by passing in some mutable object' Text
+'\n' Text
+
+'that callers then modify, but these approaches are messy.' Text
+'\n' Text
+
+'\n' Text
+
+"In Python 2.5 there's a simple way to pass values into a generator." Text
+'\n' Text
+
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' became an expression, returning a value that can be assigned' Text
+'\n' Text
+
+'to a variable or otherwise operated on' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'val = (yield i)' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'I recommend that you ' Text
+'**always**' Generic.Strong
+' put parentheses around a ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+'\n' Text
+
+"expression when you're doing something with the returned value, as in" Text
+'\n' Text
+
+"the above example. The parentheses aren't always necessary, but it's" Text
+'\n' Text
+
+"easier to always add them instead of having to remember when they're" Text
+'\n' Text
+
+'needed.' Text
+'\n' Text
+
+'\n' Text
+
+'(PEP 342 explains the exact rules, which are that a' Text
+'\n' Text
+
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+'-expression must always be parenthesized except when it' Text
+'\n' Text
+
+'occurs at the top-level expression on the right-hand side of an' Text
+'\n' Text
+
+'assignment. This means you can write ' Text
+'``' Literal.String
+'val = yield i' Literal.String
+'``' Literal.String
+' but have to' Text
+'\n' Text
+
+"use parentheses when there's an operation, as in " Text
+'``' Literal.String
+'val = (yield i)\n+ 12' Literal.String
+'``' Literal.String
+'.)' Text
+'\n' Text
+
+'\n' Text
+
+'Values are sent into a generator by calling its' Text
+'\n' Text
+
+'``' Literal.String
+'send(value)' Literal.String
+'``' Literal.String
+' method. This method resumes the ' Text
+'\n' Text
+
+"generator's code and the " Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' expression returns the specified' Text
+'\n' Text
+
+'value. If the regular ' Text
+'``' Literal.String
+'next()' Literal.String
+'``' Literal.String
+' method is called, the' Text
+'\n' Text
+
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' returns ' Text
+'``' Literal.String
+'None' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+"Here's a simple counter that increments by 1 and allows changing the" Text
+'\n' Text
+
+'value of the internal counter.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def counter (maximum):' Literal.String
+'\n' Text
+
+' i = 0\n while i < maximum:\n val = (yield i)\n # If value provided, change counter\n if val is not None:\n i = val\n else:\n i += 1\n\n' Literal.String
+
+"And here's an example of changing the counter" Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+' >>> it = counter(10)' Text
+'\n' Text
+
+' >>> print it.next()' Text
+'\n' Text
+
+' 0' Text
+'\n' Text
+
+' >>> print it.next()' Text
+'\n' Text
+
+' 1' Text
+'\n' Text
+
+' >>> print it.send(8)' Text
+'\n' Text
+
+' 8' Text
+'\n' Text
+
+' >>> print it.next()' Text
+'\n' Text
+
+' 9' Text
+'\n' Text
+
+' >>> print it.next()' Text
+'\n' Text
+
+' Traceback (most recent call last)' Text
+':' Text
+'\n' Text
+
+' File ' Text
+'``' Literal.String
+"t.py'', line 15, in ?\n print it.next()\n StopIteration\n\nBecause " Literal.String
+'`' Literal.String
+'`' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' will often be returning ' Text
+'``' Literal.String
+'None' Literal.String
+'``' Literal.String
+', you' Text
+'\n' Text
+
+"should always check for this case. Don't just use its value in" Text
+'\n' Text
+
+"expressions unless you're sure that the " Text
+'``' Literal.String
+'send()' Literal.String
+'``' Literal.String
+' method' Text
+'\n' Text
+
+'will be the only method used resume your generator function.' Text
+'\n' Text
+
+'\n' Text
+
+'In addition to ' Text
+'``' Literal.String
+'send()' Literal.String
+'``' Literal.String
+', there are two other new methods on' Text
+'\n' Text
+
+'generators' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' ' Text
+'``' Literal.String
+'throw(type, value=None, traceback=None)' Literal.String
+'``' Literal.String
+' is used to raise an exception inside the' Text
+'\n' Text
+
+' generator; the exception is raised by the ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' expression' Text
+'\n' Text
+
+" where the generator's execution is paused." Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' ' Text
+'``' Literal.String
+'close()' Literal.String
+'``' Literal.String
+' raises a ' Text
+'``' Literal.String
+'GeneratorExit' Literal.String
+'``' Literal.String
+'\n' Text
+
+' exception inside the generator to terminate the iteration. ' Text
+'\n' Text
+
+' On receiving this' Text
+'\n' Text
+
+" exception, the generator's code must either raise" Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'GeneratorExit' Literal.String
+'``' Literal.String
+' or ' Text
+'``' Literal.String
+'StopIteration' Literal.String
+'``' Literal.String
+'; catching the ' Text
+'\n' Text
+
+' exception and doing anything else is illegal and will trigger' Text
+'\n' Text
+
+' a ' Text
+'``' Literal.String
+'RuntimeError' Literal.String
+'``' Literal.String
+'. ' Text
+'``' Literal.String
+'close()' Literal.String
+'``' Literal.String
+' will also be called by ' Text
+'\n' Text
+
+" Python's garbage collector when the generator is garbage-collected." Text
+'\n' Text
+
+'\n' Text
+
+' If you need to run cleanup code when a ' Text
+'``' Literal.String
+'GeneratorExit' Literal.String
+'``' Literal.String
+' occurs,' Text
+'\n' Text
+
+' I suggest using a ' Text
+'``' Literal.String
+'try: ... finally:' Literal.String
+'``' Literal.String
+' suite instead of ' Text
+'\n' Text
+
+' catching ' Text
+'``' Literal.String
+'GeneratorExit' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'The cumulative effect of these changes is to turn generators from' Text
+'\n' Text
+
+'one-way producers of information into both producers and consumers.' Text
+'\n' Text
+
+'\n' Text
+
+'Generators also become ' Text
+'**coroutines**' Generic.Strong
+', a more generalized form of' Text
+'\n' Text
+
+'subroutines. Subroutines are entered at one point and exited at' Text
+'\n' Text
+
+'another point (the top of the function, and a ' Text
+'``' Literal.String
+'return' Literal.String
+'``' Literal.String
+'\n' Text
+
+'statement), but coroutines can be entered, exited, and resumed at' Text
+'\n' Text
+
+'many different points (the ' Text
+'``' Literal.String
+'yield' Literal.String
+'``' Literal.String
+' statements). ' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Built-in functions' Generic.Heading
+'\n' Text
+
+'----------------------------------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"Let's look in more detail at built-in functions often used with iterators." Text
+'\n' Text
+
+'\n' Text
+
+"Two Python's built-in functions, " Text
+'``' Literal.String
+'map()' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'filter()' Literal.String
+'``' Literal.String
+', are' Text
+'\n' Text
+
+'somewhat obsolete; they duplicate the features of list comprehensions' Text
+'\n' Text
+
+'but return actual lists instead of iterators. ' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'map(f, iterA, iterB, ...)' Literal.String
+'``' Literal.String
+' returns a list containing ' Text
+'``' Literal.String
+'f(iterA[0],\niterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...' Literal.String
+'``' Literal.String
+'. ' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def upper(s):' Literal.String
+'\n' Text
+
+" return s.upper()\n map(upper, ['sentence', 'fragment']) =>\n ['SENTENCE', 'FRAGMENT']\n\n [upper(s) for s in ['sentence', 'fragment']] =>\n ['SENTENCE', 'FRAGMENT']\n\n" Literal.String
+
+'As shown above, you can achieve the same effect with a list' Text
+'\n' Text
+
+'comprehension. The ' Text
+'``' Literal.String
+'itertools.imap()' Literal.String
+'``' Literal.String
+' function does the same thing' Text
+'\n' Text
+
+"but can handle infinite iterators; it'll be discussed later, in the section on " Text
+'\n' Text
+
+'the ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' module.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'filter(predicate, iter)' Literal.String
+'``' Literal.String
+' returns a list ' Text
+'\n' Text
+
+'that contains all the sequence elements that meet a certain condition,' Text
+'\n' Text
+
+'and is similarly duplicated by list comprehensions.' Text
+'\n' Text
+
+'A ' Text
+'**predicate**' Generic.Strong
+' is a function that returns the truth value of' Text
+'\n' Text
+
+'some condition; for use with ' Text
+'``' Literal.String
+'filter()' Literal.String
+'``' Literal.String
+', the predicate must take a ' Text
+'\n' Text
+
+'single value. ' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def is_even(x):' Literal.String
+'\n' Text
+
+' return (x % 2) == 0\n\n filter(is_even, range(10)) =>\n [0, 2, 4, 6, 8]\n\n' Literal.String
+
+'This can also be written as a list comprehension' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> [x for x in range(10) if is_even(x)]' Literal.String
+'\n' Text
+
+' [0, 2, 4, 6, 8]\n\n' Literal.String
+
+'``' Literal.String
+'filter()' Literal.String
+'``' Literal.String
+' also has a counterpart in the ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' module,' Text
+'\n' Text
+
+'``' Literal.String
+'itertools.ifilter()' Literal.String
+'``' Literal.String
+', that returns an iterator and ' Text
+'\n' Text
+
+'can therefore handle infinite sequences just as ' Text
+'``' Literal.String
+'itertools.imap()' Literal.String
+'``' Literal.String
+' can.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'reduce(func, iter, [initial_value])' Literal.String
+'``' Literal.String
+" doesn't have a counterpart in" Text
+'\n' Text
+
+'the ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' module because it cumulatively performs an operation' Text
+'\n' Text
+
+"on all the iterable's elements and therefore can't be applied to" Text
+'\n' Text
+
+'infinite iterables. ' Text
+'``' Literal.String
+'func' Literal.String
+'``' Literal.String
+' must be a function that takes two elements' Text
+'\n' Text
+
+'and returns a single value. ' Text
+'``' Literal.String
+'reduce()' Literal.String
+'``' Literal.String
+' takes the first two elements' Text
+'\n' Text
+
+'A and B returned by the iterator and calculates ' Text
+'``' Literal.String
+'func(A, B)' Literal.String
+'``' Literal.String
+'. It' Text
+'\n' Text
+
+'then requests the third element, C, calculates ' Text
+'``' Literal.String
+'func(func(A, B),\nC)' Literal.String
+'``' Literal.String
+', combines this result with the fourth element returned, and' Text
+'\n' Text
+
+'continues until the iterable is exhausted. If the iterable returns no' Text
+'\n' Text
+
+'values at all, a ' Text
+'``' Literal.String
+'TypeError' Literal.String
+'``' Literal.String
+' exception is raised. If the initial' Text
+'\n' Text
+
+"value is supplied, it's used as a starting point and" Text
+'\n' Text
+
+'``' Literal.String
+'func(initial_value, A)' Literal.String
+'``' Literal.String
+' is the first calculation.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'import operator' Literal.String
+'\n' Text
+
+" reduce(operator.concat, ['A', 'BB', 'C']) =>\n 'ABBC'\n reduce(operator.concat, []) =>\n TypeError: reduce() of empty sequence with no initial value\n reduce(operator.mul, [1,2,3], 1) =>\n 6\n reduce(operator.mul, [], 1) =>\n 1\n\n" Literal.String
+
+'If you use ' Text
+'``' Literal.String
+'operator.add' Literal.String
+'``' Literal.String
+' with ' Text
+'``' Literal.String
+'reduce()' Literal.String
+'``' Literal.String
+", you'll add up all the " Text
+'\n' Text
+
+"elements of the iterable. This case is so common that there's a special" Text
+'\n' Text
+
+'built-in called ' Text
+'``' Literal.String
+'sum()' Literal.String
+'``' Literal.String
+' to compute it' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'reduce(operator.add, [1,2,3,4], 0) =>' Literal.String
+'\n' Text
+
+' 10\n sum([1,2,3,4]) =>\n 10\n sum([]) =>\n 0\n\n' Literal.String
+
+'For many uses of ' Text
+'``' Literal.String
+'reduce()' Literal.String
+'``' Literal.String
+', though, it can be clearer to just write' Text
+'\n' Text
+
+'the obvious ' Text
+'``' Literal.String
+'for' Literal.String
+'``' Literal.String
+' loop' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'# Instead of:' Literal.String
+'\n' Text
+
+' product = reduce(operator.mul, [1,2,3], 1)\n\n # You can write:\n product = 1\n for i in [1,2,3]:\n product *= i\n\n\n' Literal.String
+
+'``' Literal.String
+'enumerate(iter)' Literal.String
+'``' Literal.String
+' counts off the elements in the iterable, returning' Text
+'\n' Text
+
+'2-tuples containing the count and each element.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"enumerate(['subject', 'verb', 'object']) =>" Literal.String
+'\n' Text
+
+" (0, 'subject'), (1, 'verb'), (2, 'object')\n\n" Literal.String
+
+'``' Literal.String
+'enumerate()' Literal.String
+'``' Literal.String
+' is often used when looping through a list ' Text
+'\n' Text
+
+'and recording the indexes at which certain conditions are met' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"f = open('data.txt', 'r')" Literal.String
+'\n' Text
+
+" for i, line in enumerate(f):\n if line.strip() == '':\n print 'Blank line at line #%i' % i\n\n" Literal.String
+
+'``' Literal.String
+'sorted(iterable, [cmp=None], [key=None], [reverse=False)' Literal.String
+'``' Literal.String
+' ' Text
+'\n' Text
+
+'collects all the elements of the iterable into a list, sorts ' Text
+'\n' Text
+
+'the list, and returns the sorted result. The ' Text
+'``' Literal.String
+'cmp' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'key' Literal.String
+'``' Literal.String
+', ' Text
+'\n' Text
+
+'and ' Text
+'``' Literal.String
+'reverse' Literal.String
+'``' Literal.String
+' arguments are passed through to the ' Text
+'\n' Text
+
+"constructed list's " Text
+'``' Literal.String
+'.sort()' Literal.String
+'``' Literal.String
+' method.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'import random' Literal.String
+'\n' Text
+
+' # Generate 8 random numbers between [0, 10000)\n rand_list = random.sample(range(10000), 8)\n rand_list =>\n [769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]\n sorted(rand_list) =>\n [769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]\n sorted(rand_list, reverse=True) =>\n [9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]\n\n' Literal.String
+
+'(For a more detailed discussion of sorting, see the Sorting mini-HOWTO' Text
+'\n' Text
+
+'in the Python wiki at http' Text
+':' Text
+'//wiki.python.org/moin/HowTo/Sorting.)' Text
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'any(iter)' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'all(iter)' Literal.String
+'``' Literal.String
+' built-ins look at ' Text
+'\n' Text
+
+"the truth values of an iterable's contents. " Text
+'``' Literal.String
+'any()' Literal.String
+'``' Literal.String
+' returns ' Text
+'\n' Text
+
+'True if any element in the iterable is a true value, and ' Text
+'``' Literal.String
+'all()' Literal.String
+'``' Literal.String
+' ' Text
+'\n' Text
+
+'returns True if all of the elements are true values' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'any([0,1,0]) =>' Literal.String
+'\n' Text
+
+' True\n any([0,0,0]) =>\n False\n any([1,1,1]) =>\n True\n all([0,1,0]) =>\n False\n all([0,0,0]) => \n False\n all([1,1,1]) =>\n True\n\n\n' Literal.String
+
+'Small functions and the lambda statement' Generic.Heading
+'\n' Text
+
+'----------------------------------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"When writing functional-style programs, you'll often need little" Text
+'\n' Text
+
+'functions that act as predicates or that combine elements in some way.' Text
+'\n' Text
+
+'\n' Text
+
+"If there's a Python built-in or a module function that's suitable, you" Text
+'\n' Text
+
+"don't need to define a new function at all" Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'stripped_lines = [line.strip() for line in lines]' Literal.String
+'\n' Text
+
+' existing_files = filter(os.path.exists, file_list)\n\n' Literal.String
+
+"If the function you need doesn't exist, you need to write it. One way" Text
+'\n' Text
+
+'to write small functions is to use the ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+' statement. ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+'\n' Text
+
+'takes a number of parameters and an expression combining these parameters,' Text
+'\n' Text
+
+'and creates a small function that returns the value of the expression' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'lowercase = lambda x: x.lower()' Literal.String
+'\n' Text
+
+"\n print_assign = lambda name, value: name + '=' + str(value)\n\n adder = lambda x, y: x+y\n\n" Literal.String
+
+'An alternative is to just use the ' Text
+'``' Literal.String
+'def' Literal.String
+'``' Literal.String
+' statement and define a' Text
+'\n' Text
+
+'function in the usual way' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def lowercase(x):' Literal.String
+'\n' Text
+
+" return x.lower()\n\n def print_assign(name, value):\n return name + '=' + str(value)\n\n def adder(x,y):\n return x + y\n\n" Literal.String
+
+"Which alternative is preferable? That's a style question; my usual" Text
+'\n' Text
+
+'course is to avoid using ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'One reason for my preference is that ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+' is quite limited in' Text
+'\n' Text
+
+'the functions it can define. The result has to be computable as a' Text
+'\n' Text
+
+"single expression, which means you can't have multiway" Text
+'\n' Text
+
+'``' Literal.String
+'if... elif... else' Literal.String
+'``' Literal.String
+' comparisons or ' Text
+'``' Literal.String
+'try... except' Literal.String
+'``' Literal.String
+' statements.' Text
+'\n' Text
+
+'If you try to do too much in a ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+" statement, you'll end up" Text
+'\n' Text
+
+"with an overly complicated expression that's hard to read. Quick," Text
+'\n' Text
+
+"what's the following code doing?" Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'You can figure it out, but it takes time to disentangle the expression' Text
+'\n' Text
+
+"to figure out what's going on. Using a short nested" Text
+'\n' Text
+
+'``' Literal.String
+'def' Literal.String
+'``' Literal.String
+' statements makes things a little bit better' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def combine (a, b):' Literal.String
+'\n' Text
+
+' return 0, a[1] + b[1]\n\n total = reduce(combine, items)[1]\n\n' Literal.String
+
+'But it would be best of all if I had simply used a ' Text
+'``' Literal.String
+'for' Literal.String
+'``' Literal.String
+' loop' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'total = 0' Literal.String
+'\n' Text
+
+' for a, b in items:\n total += b\n\n' Literal.String
+
+'Or the ' Text
+'``' Literal.String
+'sum()' Literal.String
+'``' Literal.String
+' built-in and a generator expression' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'total = sum(b for a,b in items)' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'Many uses of ' Text
+'``' Literal.String
+'reduce()' Literal.String
+'``' Literal.String
+' are clearer when written as ' Text
+'``' Literal.String
+'for' Literal.String
+'``' Literal.String
+' loops.' Text
+'\n' Text
+
+'\n' Text
+
+'Fredrik Lundh once suggested the following set of rules for refactoring ' Text
+'\n' Text
+
+'uses of ' Text
+'``' Literal.String
+'lambda' Literal.String
+'``' Literal.String
+':' Text
+'\n' Text
+
+'\n' Text
+
+'1)' Literal.Number
+' Write a lambda function.' Text
+'\n' Text
+
+'2)' Literal.Number
+' Write a comment explaining what the heck that lambda does.' Text
+'\n' Text
+
+'3)' Literal.Number
+' Study the comment for a while, and think of a name that captures' Text
+'\n' Text
+
+' the essence of the comment.' Text
+'\n' Text
+
+'4)' Literal.Number
+' Convert the lambda to a def statement, using that name.' Text
+'\n' Text
+
+'5)' Literal.Number
+' Remove the comment.' Text
+'\n' Text
+
+'\n' Text
+
+"I really like these rules, but you're free to disagree that this " Text
+'\n' Text
+
+'lambda-free style is better.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'The itertools module' Generic.Heading
+'\n' Text
+
+'-----------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' module contains a number of commonly-used iterators' Text
+'\n' Text
+
+'as well as functions for combining several iterators. This section' Text
+'\n' Text
+
+"will introduce the module's contents by showing small examples." Text
+'\n' Text
+
+'\n' Text
+
+"The module's functions fall into a few broad classes" Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' Functions that create a new iterator based on an existing iterator.' Text
+'\n' Text
+
+'*' Literal.Number
+" Functions for treating an iterator's elements as function arguments." Text
+'\n' Text
+
+'*' Literal.Number
+" Functions for selecting portions of an iterator's output." Text
+'\n' Text
+
+'*' Literal.Number
+" A function for grouping an iterator's output." Text
+'\n' Text
+
+'\n' Text
+
+'Creating new iterators' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'itertools.count(n)' Literal.String
+'``' Literal.String
+' returns an infinite stream of' Text
+'\n' Text
+
+'integers, increasing by 1 each time. You can optionally supply the' Text
+'\n' Text
+
+'starting number, which defaults to 0' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.count() =>' Literal.String
+'\n' Text
+
+' 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n itertools.count(10) =>\n 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n\n' Literal.String
+
+'``' Literal.String
+'itertools.cycle(iter)' Literal.String
+'``' Literal.String
+' saves a copy of the contents of a provided' Text
+'\n' Text
+
+'iterable and returns a new iterator that returns its elements from' Text
+'\n' Text
+
+'first to last. The new iterator will repeat these elements infinitely.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.cycle([1,2,3,4,5]) =>' Literal.String
+'\n' Text
+
+' 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...\n\n' Literal.String
+
+'``' Literal.String
+'itertools.repeat(elem, [n])' Literal.String
+'``' Literal.String
+' returns the provided element ' Text
+'``' Literal.String
+'n' Literal.String
+'``' Literal.String
+'\n' Text
+
+'times, or returns the element endlessly if ' Text
+'``' Literal.String
+'n' Literal.String
+'``' Literal.String
+' is not provided.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"itertools.repeat('abc') =>" Literal.String
+'\n' Text
+
+" abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...\n itertools.repeat('abc', 5) =>\n abc, abc, abc, abc, abc\n\n" Literal.String
+
+'``' Literal.String
+'itertools.chain(iterA, iterB, ...)' Literal.String
+'``' Literal.String
+' takes an arbitrary number of' Text
+'\n' Text
+
+'iterables as input, and returns all the elements of the first' Text
+'\n' Text
+
+'iterator, then all the elements of the second, and so on, until all of' Text
+'\n' Text
+
+'the iterables have been exhausted.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>" Literal.String
+'\n' Text
+
+' a, b, c, 1, 2, 3\n\n' Literal.String
+
+'``' Literal.String
+'itertools.izip(iterA, iterB, ...)' Literal.String
+'``' Literal.String
+' takes one element from each iterable' Text
+'\n' Text
+
+'and returns them in a tuple' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"itertools.izip(['a', 'b', 'c'], (1, 2, 3)) =>" Literal.String
+'\n' Text
+
+" ('a', 1), ('b', 2), ('c', 3)\n\n" Literal.String
+
+"It's similiar to the built-in " Text
+'``' Literal.String
+'zip()' Literal.String
+'``' Literal.String
+" function, but doesn't" Text
+'\n' Text
+
+'construct an in-memory list and exhaust all the input iterators before' Text
+'\n' Text
+
+"returning; instead tuples are constructed and returned only if they're" Text
+'\n' Text
+
+'requested. (The technical term for this behaviour is ' Text
+'\n' Text
+
+'`lazy evaluation ' Literal.String
+'<http://en.wikipedia.org/wiki/Lazy_evaluation>' Literal.String.Interpol
+'`__' Literal.String
+'.)' Text
+'\n' Text
+
+'\n' Text
+
+'This iterator is intended to be used with iterables that are all of' Text
+'\n' Text
+
+'the same length. If the iterables are of different lengths, the' Text
+'\n' Text
+
+'resulting stream will be the same length as the shortest iterable.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"itertools.izip(['a', 'b'], (1, 2, 3)) =>" Literal.String
+'\n' Text
+
+" ('a', 1), ('b', 2)\n\n" Literal.String
+
+'You should avoid doing this, though, because an element may be taken' Text
+'\n' Text
+
+"from the longer iterators and discarded. This means you can't go on" Text
+'\n' Text
+
+'to use the iterators further because you risk skipping a discarded' Text
+'\n' Text
+
+'element.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'itertools.islice(iter, [start], stop, [step])' Literal.String
+'``' Literal.String
+' returns a stream' Text
+'\n' Text
+
+"that's a slice of the iterator. With a single " Text
+'``' Literal.String
+'stop' Literal.String
+'``' Literal.String
+' argument, ' Text
+'\n' Text
+
+'it will return the first ' Text
+'``' Literal.String
+'stop' Literal.String
+'``' Literal.String
+'\n' Text
+
+"elements. If you supply a starting index, you'll get " Text
+'``' Literal.String
+'stop-start' Literal.String
+'``' Literal.String
+'\n' Text
+
+'elements, and if you supply a value for ' Text
+'``' Literal.String
+'step' Literal.String
+'``' Literal.String
+', elements will be' Text
+'\n' Text
+
+"skipped accordingly. Unlike Python's string and list slicing, you" Text
+'\n' Text
+
+"can't use negative values for " Text
+'``' Literal.String
+'start' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'stop' Literal.String
+'``' Literal.String
+', or ' Text
+'``' Literal.String
+'step' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.islice(range(10), 8) =>' Literal.String
+'\n' Text
+
+' 0, 1, 2, 3, 4, 5, 6, 7\n itertools.islice(range(10), 2, 8) =>\n 2, 3, 4, 5, 6, 7\n itertools.islice(range(10), 2, 8, 2) =>\n 2, 4, 6\n\n' Literal.String
+
+'``' Literal.String
+'itertools.tee(iter, [n])' Literal.String
+'``' Literal.String
+' replicates an iterator; it returns ' Text
+'``' Literal.String
+'n' Literal.String
+'``' Literal.String
+'\n' Text
+
+'independent iterators that will all return the contents of the source' Text
+'\n' Text
+
+"iterator. If you don't supply a value for " Text
+'``' Literal.String
+'n' Literal.String
+'``' Literal.String
+', the default is 2.' Text
+'\n' Text
+
+'Replicating iterators requires saving some of the contents of the source' Text
+'\n' Text
+
+'iterator, so this can consume significant memory if the iterator is large' Text
+'\n' Text
+
+'and one of the new iterators is consumed more than the others.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.tee( itertools.count() ) =>' Literal.String
+'\n' Text
+
+' iterA, iterB\n\n where iterA ->\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n\n and iterB ->\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...\n\n\n' Literal.String
+
+'Calling functions on elements' Generic.Heading
+'\n' Text
+
+"'''''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Two functions are used for calling other functions on the contents of an' Text
+'\n' Text
+
+'iterable.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'itertools.imap(f, iterA, iterB, ...)' Literal.String
+'``' Literal.String
+' returns ' Text
+'\n' Text
+
+'a stream containing ' Text
+'``' Literal.String
+'f(iterA[0], iterB[0]), f(iterA[1], iterB[1]),\nf(iterA[2], iterB[2]), ...' Literal.String
+'``' Literal.String
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.imap(operator.add, [5, 6, 5], [1, 2, 3]) =>' Literal.String
+'\n' Text
+
+' 6, 8, 8\n\n' Literal.String
+
+'The ' Text
+'``' Literal.String
+'operator' Literal.String
+'``' Literal.String
+' module contains a set of functions ' Text
+'\n' Text
+
+"corresponding to Python's operators. Some examples are " Text
+'\n' Text
+
+'``' Literal.String
+'operator.add(a, b)' Literal.String
+'``' Literal.String
+' (adds two values), ' Text
+'\n' Text
+
+'``' Literal.String
+'operator.ne(a, b)' Literal.String
+'``' Literal.String
+' (same as ' Text
+'``' Literal.String
+'a!=b' Literal.String
+'``' Literal.String
+'),' Text
+'\n' Text
+
+'and ' Text
+'\n' Text
+
+'``' Literal.String
+"operator.attrgetter('id')" Literal.String
+'``' Literal.String
+' (returns a callable that' Text
+'\n' Text
+
+'fetches the ' Text
+'``' Literal.String
+'"id"' Literal.String
+'``' Literal.String
+' attribute).' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'itertools.starmap(func, iter)' Literal.String
+'``' Literal.String
+' assumes that the iterable will ' Text
+'\n' Text
+
+'return a stream of tuples, and calls ' Text
+'``' Literal.String
+'f()' Literal.String
+'``' Literal.String
+' using these tuples as the ' Text
+'\n' Text
+
+'arguments' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.starmap(os.path.join, ' Literal.String
+'\n' Text
+
+" [('/usr', 'bin', 'java'), ('/bin', 'python'),\n ('/usr', 'bin', 'perl'),('/usr', 'bin', 'ruby')])\n =>\n /usr/bin/java, /bin/python, /usr/bin/perl, /usr/bin/ruby\n\n\n" Literal.String
+
+'Selecting elements' Generic.Heading
+'\n' Text
+
+"''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"Another group of functions chooses a subset of an iterator's elements" Text
+'\n' Text
+
+'based on a predicate.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'itertools.ifilter(predicate, iter)' Literal.String
+'``' Literal.String
+' returns all the elements for' Text
+'\n' Text
+
+'which the predicate returns true' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def is_even(x):' Literal.String
+'\n' Text
+
+' return (x % 2) == 0\n\n itertools.ifilter(is_even, itertools.count()) =>\n 0, 2, 4, 6, 8, 10, 12, 14, ...\n\n' Literal.String
+
+'``' Literal.String
+'itertools.ifilterfalse(predicate, iter)' Literal.String
+'``' Literal.String
+' is the opposite, ' Text
+'\n' Text
+
+'returning all elements for which the predicate returns false' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.ifilterfalse(is_even, itertools.count()) =>' Literal.String
+'\n' Text
+
+' 1, 3, 5, 7, 9, 11, 13, 15, ...\n\n' Literal.String
+
+'``' Literal.String
+'itertools.takewhile(predicate, iter)' Literal.String
+'``' Literal.String
+' returns elements for as long' Text
+'\n' Text
+
+'as the predicate returns true. Once the predicate returns false, ' Text
+'\n' Text
+
+'the iterator will signal the end of its results.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def less_than_10(x):' Literal.String
+'\n' Text
+
+' return (x < 10)\n\n itertools.takewhile(less_than_10, itertools.count()) =>\n 0, 1, 2, 3, 4, 5, 6, 7, 8, 9\n\n itertools.takewhile(is_even, itertools.count()) =>\n 0\n\n' Literal.String
+
+'``' Literal.String
+'itertools.dropwhile(predicate, iter)' Literal.String
+'``' Literal.String
+' discards elements while the' Text
+'\n' Text
+
+"predicate returns true, and then returns the rest of the iterable's" Text
+'\n' Text
+
+'results.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'itertools.dropwhile(less_than_10, itertools.count()) =>' Literal.String
+'\n' Text
+
+' 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...\n\n itertools.dropwhile(is_even, itertools.count()) =>\n 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...\n\n\n' Literal.String
+
+'Grouping elements' Generic.Heading
+'\n' Text
+
+"'''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"The last function I'll discuss, " Text
+'``' Literal.String
+'itertools.groupby(iter,\nkey_func=None)' Literal.String
+'``' Literal.String
+', is the most complicated. ' Text
+'``' Literal.String
+'key_func(elem)' Literal.String
+'``' Literal.String
+' is a' Text
+'\n' Text
+
+'function that can compute a key value for each element returned by the' Text
+'\n' Text
+
+"iterable. If you don't supply a key function, the key is simply each" Text
+'\n' Text
+
+'element itself.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'groupby()' Literal.String
+'``' Literal.String
+' collects all the consecutive elements from the' Text
+'\n' Text
+
+'underlying iterable that have the same key value, and returns a stream' Text
+'\n' Text
+
+'of 2-tuples containing a key value and an iterator for the elements' Text
+'\n' Text
+
+'with that key. ' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+"city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'), " Literal.String
+'\n' Text
+
+" ('Anchorage', 'AK'), ('Nome', 'AK'),\n ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'), \n ...\n ]\n\n def get_state ((city, state)):\n return state\n\n itertools.groupby(city_list, get_state) =>\n ('AL', iterator-1),\n ('AK', iterator-2),\n ('AZ', iterator-3), ...\n\n where\n iterator-1 =>\n ('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')\n iterator-2 => \n ('Anchorage', 'AK'), ('Nome', 'AK')\n iterator-3 =>\n ('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')\n\n" Literal.String
+
+'``' Literal.String
+'groupby()' Literal.String
+'``' Literal.String
+" assumes that the underlying iterable's contents will" Text
+'\n' Text
+
+'already be sorted based on the key. Note that the returned iterators' Text
+'\n' Text
+
+'also use the underlying iterable, so you have to consume the results' Text
+'\n' Text
+
+'of iterator-1 before requesting iterator-2 and its corresponding key.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'The functools module' Generic.Heading
+'\n' Text
+
+'----------------------------------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'functools' Literal.String
+'``' Literal.String
+' module in Python 2.5 contains some higher-order' Text
+'\n' Text
+
+'functions. A ' Text
+'**higher-order function**' Generic.Strong
+' takes one or more functions as' Text
+'\n' Text
+
+'input and returns a new function. The most useful tool in this module' Text
+'\n' Text
+
+'is the ' Text
+'``' Literal.String
+'partial()' Literal.String
+'``' Literal.String
+' function.' Text
+'\n' Text
+
+'\n' Text
+
+"For programs written in a functional style, you'll sometimes want to" Text
+'\n' Text
+
+'construct variants of existing functions that have some of the' Text
+'\n' Text
+
+'parameters filled in. Consider a Python function ' Text
+'``' Literal.String
+'f(a, b, c)' Literal.String
+'``' Literal.String
+'; you' Text
+'\n' Text
+
+'may wish to create a new function ' Text
+'``' Literal.String
+'g(b, c)' Literal.String
+'``' Literal.String
+" that's equivalent to" Text
+'\n' Text
+
+'``' Literal.String
+'f(1, b, c)' Literal.String
+'``' Literal.String
+"; you're filling in a value for one of " Text
+'``' Literal.String
+'f()' Literal.String
+'``' Literal.String
+"'s parameters. " Text
+'\n' Text
+
+'This is called "partial function application".' Text
+'\n' Text
+
+'\n' Text
+
+'The constructor for ' Text
+'``' Literal.String
+'partial' Literal.String
+'``' Literal.String
+' takes the arguments ' Text
+'``' Literal.String
+'(function, arg1,\narg2, ... kwarg1=value1, kwarg2=value2)' Literal.String
+'``' Literal.String
+'. The resulting object is' Text
+'\n' Text
+
+'callable, so you can just call it to invoke ' Text
+'``' Literal.String
+'function' Literal.String
+'``' Literal.String
+' with the' Text
+'\n' Text
+
+'filled-in arguments.' Text
+'\n' Text
+
+'\n' Text
+
+"Here's a small but realistic example" Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'import functools' Literal.String
+'\n' Text
+
+'\n def log (message, subsystem):\n "Write the contents of \'message\' to the specified subsystem."\n print \'%s: %s\' % (subsystem, message)\n ...\n\n server_log = functools.partial(log, subsystem=\'server\')\n server_log(\'Unable to open socket\')\n\n\n' Literal.String
+
+'The operator module' Generic.Heading
+'\n' Text
+
+'-------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'operator' Literal.String
+'``' Literal.String
+' module was mentioned earlier. It contains a set of' Text
+'\n' Text
+
+"functions corresponding to Python's operators. These functions " Text
+'\n' Text
+
+'are often useful in functional-style code because they save you ' Text
+'\n' Text
+
+'from writing trivial functions that perform a single operation.' Text
+'\n' Text
+
+'\n' Text
+
+'Some of the functions in this module are' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' Math operations' Text
+':' Text
+' ' Text
+'``' Literal.String
+'add()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'sub()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'mul()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'div()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'floordiv()' Literal.String
+'``' Literal.String
+',' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'abs()' Literal.String
+'``' Literal.String
+', ...' Text
+'\n' Text
+
+'*' Literal.Number
+' Logical operations' Text
+':' Text
+' ' Text
+'``' Literal.String
+'not_()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'truth()' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'*' Literal.Number
+' Bitwise operations' Text
+':' Text
+' ' Text
+'``' Literal.String
+'and_()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'or_()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'invert()' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'*' Literal.Number
+' Comparisons' Text
+':' Text
+' ' Text
+'``' Literal.String
+'eq()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'ne()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'lt()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'le()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'gt()' Literal.String
+'``' Literal.String
+', and ' Text
+'``' Literal.String
+'ge()' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'*' Literal.Number
+' Object identity' Text
+':' Text
+' ' Text
+'``' Literal.String
+'is_()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'is_not()' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Consult ' Text
+"`the operator module's documentation " Literal.String
+'<http://docs.python.org/lib/module-operator.html>' Literal.String.Interpol
+'`__' Literal.String
+' for a complete' Text
+'\n' Text
+
+'list.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'The functional module' Generic.Heading
+'\n' Text
+
+'---------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"Collin Winter's " Text
+'`functional module ' Literal.String
+'<http://oakwinter.com/code/functional/>' Literal.String.Interpol
+'`__' Literal.String
+' ' Text
+'\n' Text
+
+'provides a number of more' Text
+'\n' Text
+
+'advanced tools for functional programming. It also reimplements' Text
+'\n' Text
+
+'several Python built-ins, trying to make them more intuitive to those' Text
+'\n' Text
+
+'used to functional programming in other languages.' Text
+'\n' Text
+
+'\n' Text
+
+'This section contains an introduction to some of the most important' Text
+'\n' Text
+
+'functions in ' Text
+'``' Literal.String
+'functional' Literal.String
+'``' Literal.String
+'; full documentation can be found at ' Text
+'`' Text
+'the' Text
+'\n' Text
+
+"project's website <http" Text
+':' Text
+'//oakwinter.com/code/functional/documentation/>' Text
+'`' Text
+'__.' Text
+'\n' Text
+
+'\n' Text
+
+'``' Literal.String
+'compose(outer, inner, unpack=False)' Literal.String
+'``' Literal.String
+'\n' Text
+
+'\n' Text
+
+'The ' Text
+'``' Literal.String
+'compose()' Literal.String
+'``' Literal.String
+' function implements function composition.' Text
+'\n' Text
+
+'In other words, it returns a wrapper around the ' Text
+'``' Literal.String
+'outer' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'inner' Literal.String
+'``' Literal.String
+' callables, such' Text
+'\n' Text
+
+'that the return value from ' Text
+'``' Literal.String
+'inner' Literal.String
+'``' Literal.String
+' is fed directly to ' Text
+'``' Literal.String
+'outer' Literal.String
+'``' Literal.String
+'. That is,' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> def add(a, b):' Literal.String
+'\n' Text
+
+' ... return a + b\n ...\n >>> def double(a):\n ... return 2 * a\n ...\n >>> compose(double, add)(5, 6)\n 22\n\n' Literal.String
+
+'is equivalent to' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> double(add(5, 6))' Literal.String
+'\n' Text
+
+' 22\n \n' Literal.String
+
+'The ' Text
+'``' Literal.String
+'unpack' Literal.String
+'``' Literal.String
+' keyword is provided to work around the fact that Python functions are not always' Text
+'\n' Text
+
+'`fully curried ' Literal.String
+'<http://en.wikipedia.org/wiki/Currying>' Literal.String.Interpol
+'`__' Literal.String
+'.' Text
+'\n' Text
+
+'By default, it is expected that the ' Text
+'``' Literal.String
+'inner' Literal.String
+'``' Literal.String
+' function will return a single object and that the ' Text
+'``' Literal.String
+'outer' Literal.String
+'``' Literal.String
+'\n' Text
+
+'function will take a single argument. Setting the ' Text
+'``' Literal.String
+'unpack' Literal.String
+'``' Literal.String
+' argument causes ' Text
+'``' Literal.String
+'compose' Literal.String
+'``' Literal.String
+' to expect a' Text
+'\n' Text
+
+'tuple from ' Text
+'``' Literal.String
+'inner' Literal.String
+'``' Literal.String
+' which will be expanded before being passed to ' Text
+'``' Literal.String
+'outer' Literal.String
+'``' Literal.String
+'. Put simply,' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'compose(f, g)(5, 6)' Literal.String
+'\n' Text
+
+' \n' Literal.String
+
+'is equivalent to' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'f(g(5, 6))' Literal.String
+'\n' Text
+
+' \n' Literal.String
+
+'while' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'compose(f, g, unpack=True)(5, 6)' Literal.String
+'\n' Text
+
+' \n' Literal.String
+
+'is equivalent to' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'f(*g(5, 6))' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'Even though ' Text
+'``' Literal.String
+'compose()' Literal.String
+'``' Literal.String
+" only accepts two functions, it's trivial to" Text
+'\n' Text
+
+"build up a version that will compose any number of functions. We'll" Text
+'\n' Text
+
+'use ' Text
+'``' Literal.String
+'reduce()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'compose()' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'partial()' Literal.String
+'``' Literal.String
+' (the last of which' Text
+'\n' Text
+
+'is provided by both ' Text
+'``' Literal.String
+'functional' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'functools' Literal.String
+'``' Literal.String
+').' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'from functional import compose, partial' Literal.String
+'\n' Text
+
+' \n multi_compose = partial(reduce, compose)\n \n' Literal.String
+
+' ' Text
+'\n' Text
+
+'We can also use ' Text
+'``' Literal.String
+'map()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'compose()' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'partial()' Literal.String
+'``' Literal.String
+' to craft a' Text
+'\n' Text
+
+'version of ' Text
+'``' Literal.String
+'"".join(...)' Literal.String
+'``' Literal.String
+' that converts its arguments to string' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'from functional import compose, partial' Literal.String
+'\n' Text
+
+' \n join = compose("".join, partial(map, str))\n\n\n' Literal.String
+
+'``' Literal.String
+'flip(func)' Literal.String
+'``' Literal.String
+'\n' Text
+
+' ' Text
+'\n' Text
+
+'``' Literal.String
+'flip()' Literal.String
+'``' Literal.String
+' wraps the callable in ' Text
+'``' Literal.String
+'func' Literal.String
+'``' Literal.String
+' and ' Text
+'\n' Text
+
+'causes it to receive its non-keyword arguments in reverse order.' Text
+'\n' Text
+
+'\n' Text
+
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'>>> def triple(a, b, c):' Literal.String
+'\n' Text
+
+' ... return (a, b, c)\n ...\n >>> triple(5, 6, 7)\n (5, 6, 7)\n >>>\n >>> flipped_triple = flip(triple)\n >>> flipped_triple(5, 6, 7)\n (7, 6, 5)\n\n' Literal.String
+
+'``' Literal.String
+'foldl(func, start, iterable)' Literal.String
+'``' Literal.String
+'\n' Text
+
+' ' Text
+'\n' Text
+
+'``' Literal.String
+'foldl()' Literal.String
+'``' Literal.String
+" takes a binary function, a starting value (usually some kind of 'zero'), and an iterable." Text
+'\n' Text
+
+'The function is applied to the starting value and the first element of the list, then the result of' Text
+'\n' Text
+
+'that and the second element of the list, then the result of that and the third element of the list,' Text
+'\n' Text
+
+'and so on.' Text
+'\n' Text
+
+'\n' Text
+
+'This means that a call such as' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'foldl(f, 0, [1, 2, 3])' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+'is equivalent to' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'f(f(f(0, 1), 2), 3)' Literal.String
+'\n' Text
+
+'\n' Literal.String
+
+' ' Text
+'\n' Text
+
+'``' Literal.String
+'foldl()' Literal.String
+'``' Literal.String
+' is roughly equivalent to the following recursive function' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'def foldl(func, start, seq):' Literal.String
+'\n' Text
+
+' if len(seq) == 0:\n return start\n\n return foldl(func, func(start, seq[0]), seq[1:])\n\n' Literal.String
+
+'Speaking of equivalence, the above ' Text
+'``' Literal.String
+'foldl' Literal.String
+'``' Literal.String
+' call can be expressed in terms of the built-in ' Text
+'``' Literal.String
+'reduce' Literal.String
+'``' Literal.String
+' like' Text
+'\n' Text
+
+'so' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'reduce(f, [1, 2, 3], 0)' Literal.String
+'\n' Text
+
+'\n\n' Literal.String
+
+'We can use ' Text
+'``' Literal.String
+'foldl()' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'operator.concat()' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'partial()' Literal.String
+'``' Literal.String
+' to' Text
+'\n' Text
+
+"write a cleaner, more aesthetically-pleasing version of Python's" Text
+'\n' Text
+
+'``' Literal.String
+'"".join(...)' Literal.String
+'``' Literal.String
+' idiom' Text
+'::' Literal.String.Escape
+'\n\n' Text
+
+' ' Literal.String
+'from functional import foldl, partial' Literal.String
+'\n' Text
+
+' from operator import concat\n \n join = partial(foldl, concat, "")\n\n\n' Literal.String
+
+'Revision History and Acknowledgements' Generic.Heading
+'\n' Text
+
+'------------------------------------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The author would like to thank the following people for offering' Text
+'\n' Text
+
+'suggestions, corrections and assistance with various drafts of this' Text
+'\n' Text
+
+'article' Text
+':' Text
+' Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger,' Text
+'\n' Text
+
+'Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, ' Text
+'\n' Text
+
+'Collin Winter, Blake Winton.' Text
+'\n' Text
+
+'\n' Text
+
+'Version 0.1' Text
+':' Text
+' posted June 30 2006.' Text
+'\n' Text
+
+'\n' Text
+
+'Version 0.11' Text
+':' Text
+' posted July 1 2006. Typo fixes.' Text
+'\n' Text
+
+'\n' Text
+
+'Version 0.2' Text
+':' Text
+' posted July 10 2006. Merged genexp and listcomp' Text
+'\n' Text
+
+'sections into one. Typo fixes.' Text
+'\n' Text
+
+'\n' Text
+
+'Version 0.21' Text
+':' Text
+' Added more references suggested on the tutor mailing list.' Text
+'\n' Text
+
+'\n' Text
+
+'Version 0.30' Text
+':' Text
+' Adds a section on the ' Text
+'``' Literal.String
+'functional' Literal.String
+'``' Literal.String
+' module written by' Text
+'\n' Text
+
+'Collin Winter; adds short section on the operator module; a few other' Text
+'\n' Text
+
+'edits.' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'References' Generic.Heading
+'\n' Text
+
+'--------------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'General' Generic.Heading
+'\n' Text
+
+"'''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'**Structure and Interpretation of Computer Programs**' Generic.Strong
+', by ' Text
+'\n' Text
+
+'Harold Abelson and Gerald Jay Sussman with Julie Sussman.' Text
+'\n' Text
+
+'Full text at http' Text
+':' Text
+'//mitpress.mit.edu/sicp/.' Text
+'\n' Text
+
+'In this classic textbook of computer science, chapters 2 and 3 discuss the' Text
+'\n' Text
+
+'use of sequences and streams to organize the data flow inside a' Text
+'\n' Text
+
+'program. The book uses Scheme for its examples, but many of the' Text
+'\n' Text
+
+'design approaches described in these chapters are applicable to' Text
+'\n' Text
+
+'functional-style Python code.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//www.defmacro.org/ramblings/fp.html' Text
+':' Text
+' A general ' Text
+'\n' Text
+
+'introduction to functional programming that uses Java examples' Text
+'\n' Text
+
+'and has a lengthy historical introduction.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//en.wikipedia.org/wiki/Functional_programming' Text
+':' Text
+'\n' Text
+
+'General Wikipedia entry describing functional programming.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//en.wikipedia.org/wiki/Coroutine' Text
+':' Text
+'\n' Text
+
+'Entry for coroutines.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//en.wikipedia.org/wiki/Currying' Text
+':' Text
+'\n' Text
+
+'Entry for the concept of currying.' Text
+'\n' Text
+
+'\n' Text
+
+'Python-specific' Generic.Heading
+'\n' Text
+
+"'''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//gnosis.cx/TPiP/' Text
+':' Text
+'\n' Text
+
+"The first chapter of David Mertz's book " Text
+':title-reference:' Name.Attribute
+'`Text Processing in Python`' Name.Variable
+' ' Text
+'\n' Text
+
+'discusses functional programming for text processing, in the section titled' Text
+'\n' Text
+
+'"Utilizing Higher-Order Functions in Text Processing".' Text
+'\n' Text
+
+'\n' Text
+
+'Mertz also wrote a 3-part series of articles on functional programming' Text
+'\n' Text
+
+"for IBM's DeveloperWorks site; see " Text
+'\n' Text
+
+'`part 1 ' Literal.String
+'<http://www-128.ibm.com/developerworks/library/l-prog.html>' Literal.String.Interpol
+'`__' Literal.String
+',' Text
+'\n' Text
+
+'`part 2 ' Literal.String
+'<http://www-128.ibm.com/developerworks/library/l-prog2.html>' Literal.String.Interpol
+'`__' Literal.String
+', and' Text
+'\n' Text
+
+'`part 3 ' Literal.String
+'<http://www-128.ibm.com/developerworks/linux/library/l-prog3.html>' Literal.String.Interpol
+'`__' Literal.String
+',' Text
+'\n' Text
+
+'\n' Text
+
+'\n' Text
+
+'Python documentation' Generic.Heading
+'\n' Text
+
+"'''''''''''''''''''''''''''" Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//docs.python.org/lib/module-itertools.html' Text
+':' Text
+'\n' Text
+
+'Documentation for the ' Text
+'``' Literal.String
+'itertools' Literal.String
+'``' Literal.String
+' module.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//docs.python.org/lib/module-operator.html' Text
+':' Text
+'\n' Text
+
+'Documentation for the ' Text
+'``' Literal.String
+'operator' Literal.String
+'``' Literal.String
+' module.' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//www.python.org/dev/peps/pep-0289/' Text
+':' Text
+'\n' Text
+
+'PEP 289' Text
+':' Text
+' "Generator Expressions"' Text
+'\n' Text
+
+'\n' Text
+
+'http' Text
+':' Text
+'//www.python.org/dev/peps/pep-0342/' Text
+'\n' Text
+
+'PEP 342' Text
+':' Text
+' "Coroutines via Enhanced Generators" describes the new generator' Text
+'\n' Text
+
+'features in Python 2.5.' Text
+'\n' Text
+
+'\n' Text
+
+".. comment\n\n Topics to place\n -----------------------------\n\n XXX os.walk()\n\n XXX Need a large example.\n\n But will an example add much? I'll post a first draft and see\n what the comments say.\n\n" Comment.Preproc
+
+'.. comment\n\n Original outline:\n Introduction\n Idea of FP\n Programs built out of functions\n Functions are strictly input-output, no internal state\n Opposed to OO programming, where objects have state\n\n Why FP?\n Formal provability\n Assignment is difficult to reason about\n Not very relevant to Python\n Modularity\n Small functions that do one thing\n Debuggability:\n Easy to test due to lack of state\n Easy to verify output from intermediate steps\n Composability\n You assemble a toolbox of functions that can be mixed\n\n Tackling a problem\n Need a significant example\n\n Iterators\n Generators\n The itertools module\n List comprehensions\n Small functions and the lambda statement\n Built-in functions\n map\n filter\n reduce\n\n' Comment.Preproc
+
+".. comment\n\n Handy little function for printing part of an iterator -- used\n while writing this document.\n\n import itertools\n def print_iter(it):\n slice = itertools.islice(it, 10)\n for elem in slice[:-1]:\n sys.stdout.write(str(elem))\n sys.stdout.write(', ')\n print elem[-1]\n" Comment.Preproc
diff --git a/tests/lexers/rst/example2.txt b/tests/lexers/rst/example2.txt
new file mode 100644
index 00000000..8194b8cd
--- /dev/null
+++ b/tests/lexers/rst/example2.txt
@@ -0,0 +1,4628 @@
+---input---
+======================
+Designer Documentation
+======================
+
+This part of the Jinja documentaton is meant for template designers.
+
+Basics
+======
+
+The Jinja template language is designed to strike a balance between content
+and application logic. Nevertheless you can use a python like statement
+language. You don't have to know how Python works to create Jinja templates,
+but if you know it you can use some additional statements you may know from
+Python.
+
+Here is a small example template:
+
+.. sourcecode:: html+jinja
+
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+ <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
+ <head>
+ <title>My Webpage</title>
+ </head>
+ <body>
+ <ul id="navigation">
+ {% for item in navigation %}
+ <li><a href="{{ item.href|e }}">{{ item.caption|e }}</a></li>
+ {% endfor %}
+ </ul>
+
+ <h1>My Webpage</h1>
+ {{ variable }}
+ </body>
+ </html>
+
+This covers the default settings. The application developer might have changed
+the syntax from ``{% foo %}`` to ``<% foo %>`` or something similar. This
+documentation just covers the default values.
+
+A variable looks like ``{{ foobar }}`` where foobar is the variable name. Inside
+of statements (``{% some content here %}``) variables are just normal names
+without the braces around it. In fact ``{{ foobar }}`` is just an alias for
+the statement ``{% print foobar %}``.
+
+Variables are coming from the context provided by the application. Normally there
+should be a documentation regarding the context contents but if you want to know
+the content of the current context, you can add this to your template:
+
+.. sourcecode:: html+jinja
+
+ <pre>{{ debug()|e }}</pre>
+
+A context isn't flat which means that each variable can has subvariables, as long
+as it is representable as python data structure. You can access attributes of
+a variable using the dot and bracket operators. The following examples show
+this:
+
+.. sourcecode:: jinja
+
+ {{ user.username }}
+ is the same as
+ {{ user['username'] }}
+ you can also use a variable to access an attribute:
+ {{ users[current_user].username }}
+ If you have numerical indices you have to use the [] syntax:
+ {{ users[0].username }}
+
+Filters
+=======
+
+In the examples above you might have noticed the pipe symbols. Pipe symbols tell
+the engine that it has to apply a filter on the variable. Here is a small example:
+
+.. sourcecode:: jinja
+
+ {{ variable|replace('foo', 'bar')|escape }}
+
+If you want, you can also put whitespace between the filters.
+
+This will look for a variable `variable`, pass it to the filter `replace`
+with the arguments ``'foo'`` and ``'bar'``, and pass the result to the filter
+`escape` that automatically XML-escapes the value. The `e` filter is an alias for
+`escape`. Here is the complete list of supported filters:
+
+[[list_of_filters]]
+
+.. admonition:: note
+
+ Filters have a pretty low priority. If you want to add fitered values
+ you have to put them into parentheses. The same applies if you want to access
+ attributes:
+
+ .. sourcecode:: jinja
+
+ correct:
+ {{ (foo|filter) + (bar|filter) }}
+ wrong:
+ {{ foo|filter + bar|filter }}
+
+ correct:
+ {{ (foo|filter).attribute }}
+ wrong:
+ {{ foo|filter.attribute }}
+
+Tests
+=====
+
+You can use the `is` operator to perform tests on a value:
+
+.. sourcecode:: jinja
+
+ {{ 42 is numeric }} -> true
+ {{ "foobar" is numeric }} -> false
+ {{ 'FOO' is upper }} -> true
+
+These tests are especially useful when used in `if` conditions.
+
+[[list_of_tests]]
+
+Global Functions
+================
+
+Test functions and filter functions live in their own namespace. Global
+functions not. They behave like normal objects in the context. Beside the
+functions added by the application or framewhere there are two functions
+available per default:
+
+`range`
+
+ Works like the python `range function`_ just that it doesn't support
+ ranges greater than ``1000000``.
+
+`debug`
+
+ Function that outputs the contents of the context.
+
+Loops
+=====
+
+To iterate over a sequence, you can use the `for` loop. It basically looks like a
+normal Python `for` loop and works pretty much the same:
+
+.. sourcecode:: html+jinja
+
+ <h1>Members</h1>
+ <ul>
+ {% for user in users %}
+ <li>{{ loop.index }} / {{ loop.length }} - {{ user.username|escape }}</li>
+ {% else %}
+ <li><em>no users found</em></li>
+ {% endfor %}
+ </ul>
+
+*Important* Contrary to Python is the optional ``else`` block only
+executed if there was no iteration because the sequence was empty.
+
+Inside of a `for` loop block you can access some special variables:
+
++----------------------+----------------------------------------+
+| Variable | Description |
++======================+========================================+
+| `loop.index` | The current iteration of the loop. |
++----------------------+----------------------------------------+
+| `loop.index0` | The current iteration of the loop, |
+| | starting counting by 0. |
++----------------------+----------------------------------------+
+| `loop.revindex` | The number of iterations from the end |
+| | of the loop. |
++----------------------+----------------------------------------+
+| `loop.revindex0` | The number of iterations from the end |
+| | of the loop, starting counting by 0. |
++----------------------+----------------------------------------+
+| `loop.first` | True if first iteration. |
++----------------------+----------------------------------------+
+| `loop.last` | True if last iteration. |
++----------------------+----------------------------------------+
+| `loop.even` | True if current iteration is even. |
++----------------------+----------------------------------------+
+| `loop.odd` | True if current iteration is odd. |
++----------------------+----------------------------------------+
+| `loop.length` | Total number of items in the sequence. |
++----------------------+----------------------------------------+
+| `loop.parent` | The context of the parent loop. |
++----------------------+----------------------------------------+
+
+Loops also support recursion. Let's assume you have a sitemap where each item
+might have a number of child items. A template for that could look like this:
+
+.. sourcecode:: html+jinja
+
+ <h1>Sitemap
+ <ul id="sitemap">
+ {% for item in sitemap recursive %}
+ <li><a href="{{ item.url|e }}">{{ item.title|e }}</a>
+ {% if item.children %}<ul>{{ loop(item.children) }}</ul>{% endif %}</li>
+ {% endfor %}
+ </ul>
+
+What happens here? Basically the first thing that is different to a normal
+loop is the additional ``recursive`` modifier in the `for`-loop declaration.
+It tells the template engine that we want recursion. If recursion is enabled
+the special `loop` variable is callable. If you call it with a sequence it will
+automatically render the loop at that position with the new sequence as argument.
+
+Cycling
+=======
+
+Sometimes you might want to have different text snippets for each row in a list,
+for example to have alternating row colors. You can easily do this by using the
+``{% cycle %}`` tag:
+
+.. sourcecode:: html+jinja
+
+ <ul id="messages">
+ {% for message in messages %}
+ <li class="{% cycle 'row1', 'row2' %}">{{ message|e }}</li>
+ {% endfor %}
+ </ul>
+
+Each time Jinja encounters a `cycle` tag it will cycle through the list
+of given items and return the next one. If you pass it one item jinja assumes
+that this item is a sequence from the context and uses this:
+
+.. sourcecode:: html+jinja
+
+ <li style="color: {% cycle rowcolors %}">...</li>
+
+Conditions
+==========
+
+Jinja supports Python-like `if` / `elif` / `else` constructs:
+
+.. sourcecode:: jinja
+
+ {% if user.active %}
+ user {{ user.name|e }} is active.
+ {% elif user.deleted %}
+ user {{ user.name|e }} was deleted some time ago.
+ {% else %}
+ i don't know what's wrong with {{ user.username|e }}
+ {% endif %}
+
+If the user is active the first block is rendered. If not and the user was
+deleted the second one, in all other cases the third one.
+
+You can also use comparison operators:
+
+.. sourcecode:: html+jinja
+
+ {% if amount < 0 %}
+ <span style="color: red">{{ amount }}</span>
+ {% else %}
+ <span style="color: black">{{ amount }}</span>
+ {% endif %}
+
+.. admonition:: Note
+
+ Of course you can use `or` / `and` and parentheses to create more complex
+ conditions, but usually the logic is already handled in the application and
+ you don't have to create such complex constructs in the template code. However
+ in some situations it might be a good thing to have the abilities to create
+ them.
+
+Operators
+=========
+
+Inside ``{{ variable }}`` blocks, `if` conditions and many other parts you can
+can use expressions. In expressions you can use any of the following operators:
+
+ ======= ===================================================================
+ ``+`` add the right operand to the left one.
+ ``{{ 1 + 2 }}`` would return ``3``.
+ ``-`` subtract the right operand from the left one.
+ ``{{ 1 - 1 }}`` would return ``0``.
+ ``/`` divide the left operand by the right one.
+ ``{{ 1 / 2 }}`` would return ``0.5``.
+ ``*`` multiply the left operand with the right one.
+ ``{{ 2 * 2 }}`` would return ``4``.
+ ``**`` raise the left operand to the power of the right
+ operand. ``{{ 2**3 }}`` would return ``8``.
+ ``in`` perform sequence membership test. ``{{ 1 in [1,2,3] }}`` would
+ return true.
+ ``is`` perform a test on the value. See the section about
+ tests for more information.
+ ``|`` apply a filter on the value. See the section about
+ filters for more information.
+ ``and`` return true if the left and the right operand is true.
+ ``or`` return true if the left or the right operand is true.
+ ``not`` negate a statement (see below)
+ ``()`` call a callable: ``{{ user.get_username() }}``. Inside of the
+ parentheses you can use variables: ``{{ user.get(username) }}``.
+ ======= ===================================================================
+
+Note that there is no support for any bit operations or something similar.
+
+* special note regarding `not`: The `is` and `in` operators support negation
+ using an infix notation too: ``foo is not bar`` and ``foo not in bar``
+ instead of ``not foo is bar`` and ``not foo in bar``. All other expressions
+ require a prefix notation: ``not (foo and bar)``.
+
+Boolean Values
+==============
+
+In If-Conditions Jinja performs a boolean check. All empty values (eg: empty
+lists ``[]``, empty dicts ``{}`` etc) evaluate to `false`. Numbers that are
+equal to `0`/`0.00` are considered `false` too. The boolean value of other
+objects depends on the behavior the application developer gave it. Usually
+items are `true`.
+
+Here some examples that should explain it:
+
+.. sourcecode:: jinja
+
+ {% if [] %}
+ will always be false because it's an empty list
+
+ {% if {} %}
+ false too.
+
+ {% if ['foo'] %}
+ this is true. Because the list is not empty.
+
+ {% if "foobar" %}
+ this is also true because the string is not empty.
+
+Slicing
+=======
+
+Some objects support slicing operations. For example lists:
+
+.. sourcecode:: jinja
+
+ {% for item in items[:5] %}
+ This will only iterate over the first 5 items of the list
+
+ {% for item in items[5:10] %}
+ This will only iterate from item 5 to 10.
+
+ {% for item in items[:10:2] %}
+ This will only yield items from start to ten and only returing
+ even items.
+
+For more informations about slicing have a look at the `slicing chapter`_
+in the "Dive into Python" e-book.
+
+Macros
+======
+
+If you want to use a partial template in more than one place, you might want to
+create a macro from it:
+
+.. sourcecode:: html+jinja
+
+ {% macro show_user user %}
+ <h1>{{ user.name|e }}</h1>
+ <div class="test">
+ {{ user.description }}
+ </div>
+ {% endmacro %}
+
+Now you can use it from everywhere in the code by passing it an item:
+
+.. sourcecode:: jinja
+
+ {% for user in users %}
+ {{ show_user(user) }}
+ {% endfor %}
+
+You can also specify more than one value:
+
+.. sourcecode:: html+jinja
+
+ {% macro show_dialog title, text %}
+ <div class="dialog">
+ <h1>{{ title|e }}</h1>
+ <div class="test">{{ text|e }}</div>
+ </div>
+ {% endmacro %}
+
+ {{ show_dialog('Warning', 'something went wrong i guess') }}
+
+Inheritance
+===========
+
+The most powerful part of Jinja is template inheritance. Template inheritance
+allows you to build a base "skeleton" template that contains all the common
+elements of your site and defines **blocks** that child templates can override.
+
+Sounds complicated but is very basic. It's easiest to understand it by starting
+with an example.
+
+Base Template
+-------------
+
+This template, which we'll call ``base.html``, defines a simple HTML skeleton
+document that you might use for a simple two-column page. It's the job of
+"child" templates to fill the empty blocks with content:
+
+.. sourcecode:: html+jinja
+
+ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+ <html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <link rel="stylesheet" href="style.css" />
+ <title>{% block title %}{% endblock %} - My Webpage</title>
+ {% block html_head %}{% endblock %}
+ </head>
+ <body>
+ <div id="content">
+ {% block content %}{% endblock %}
+ </div>
+
+ <div id="footer">
+ {% block footer %}
+ &copy; Copyright 2006 by <a href="http://mydomain.tld">myself</a>.
+ {% endblock %}
+ </div>
+ </body>
+
+In this example, the ``{% block %}`` tags define four blocks that child templates
+can fill in. All the `block` tag does is to tell the template engine that a
+child template may override those portions of the template.
+
+Child Template
+--------------
+
+A child template might look like this:
+
+.. sourcecode:: html+jinja
+
+ {% extends "base.html" %}
+ {% block title %}Index{% endblock %}
+
+ {% block html_head %}
+ <style type="text/css">
+ .important {
+ color: #336699;
+ }
+ </style>
+ {% endblock %}
+
+ {% block content %}
+ <h1>Index</h1>
+ <p class="important">
+ Welcome on my awsome homepage.
+ </p>
+ {% endblock %}
+
+The ``{% extends %}`` tag is the key here. It tells the template engine that
+this template "extends" another template. When the template system evaluates
+this template, first it locates the parent.
+
+The filename of the template depends on the template loader. For example the
+``FileSystemLoader`` allows you to access other templates by giving the
+filename. You can access templates in subdirectories with an slash:
+
+.. sourcecode:: jinja
+
+ {% extends "layout/default.html" %}
+
+But this behavior can depend on the application using Jinja.
+
+Note that since the child template didn't define the ``footer`` block, the
+value from the parent template is used instead.
+
+.. admonition:: Note
+
+ You can't define multiple ``{% block %}`` tags with the same name in the
+ same template. This limitation exists because a block tag works in "both"
+ directions. That is, a block tag doesn't just provide a hole to fill - it
+ also defines the content that fills the hole in the *parent*. If there were
+ two similarly-named ``{% block %}`` tags in a template, that template's
+ parent wouldn't know which one of the blocks' content to use.
+
+Template Inclusion
+==================
+
+You can load another template at a given position using ``{% include %}``.
+Usually it's a better idea to use inheritance but if you for example want to
+load macros, `include` works better than `extends`:
+
+.. sourcecode:: jinja
+
+ {% include "myhelpers.html" %}
+ {{ my_helper("foo") }}
+
+If you define a macro called ``my_helper`` in ``myhelpers.html``, you can now
+use it from the template as shown above.
+
+Filtering Blocks
+================
+
+Sometimes it could be a good idea to filter a complete block of text. For
+example, if you want to escape some html code:
+
+.. sourcecode:: jinja
+
+ {% filter escape %}
+ <html>
+ <code>goes here</code>
+ </html>
+ {% endfilter %}
+
+Of course you can chain filters too:
+
+.. sourcecode:: jinja
+
+ {% filter lower|escape %}
+ <B>SOME TEXT</B>
+ {% endfilter %}
+
+returns ``"&lt;b&gt;some text&lt;/b&gt;"``.
+
+Defining Variables
+==================
+
+You can also define variables in the namespace using the ``{% set %}`` tag:
+
+.. sourcecode:: jinja
+
+ {% set foo = 'foobar' %}
+ {{ foo }}
+
+This should ouput ``foobar``.
+
+Scopes
+======
+
+Jinja has multiple scopes. A scope is something like a new transparent foil on
+a stack of foils. You can only write to the outermost foil but read all of them
+since you can look through them. If you remove the top foil all data on that
+foil disappears. Some tags in Jinja add a new layer to the stack. Currently
+these are `block`, `for`, `macro` and `filter`. This means that variables and
+other elements defined inside a macro, loop or some of the other tags listed
+above will be only available in that block. Here an example:
+
+.. sourcecode:: jinja
+
+ {% macro angryhello name %}
+ {% set angryname = name|upper %}
+ Hello {{ name }}. Hello {{ name }}!
+ HELLO {{ angryname }}!!!!!!111
+ {% endmacro %}
+
+The variable ``angryname`` just exists inside the macro, not outside it.
+
+Defined macros appear on the context as variables. Because of this, they are
+affected by the scoping too. A macro defined inside of a macro is just available
+in those two macros (the macro itself and the macro it's defined in). For `set`
+and `macro` two additional rules exist: If a macro is defined in an extended
+template but outside of a visible block (thus outside of any block) will be
+available in all blocks below. This allows you to use `include` statements to
+load often used macros at once.
+
+Undefined Variables
+===================
+
+If you have already worked with python you probably know about the fact that
+undefined variables raise an exception. This is different in Jinja. There is a
+special value called `undefined` that represents values that do not exist.
+
+This special variable works complete different from any variables you maybe
+know. If you print it using ``{{ variable }}`` it will not appear because it's
+literally empty. If you try to iterate over it, it will work. But no items
+are returned. Comparing this value to any other value results in `false`.
+Even if you compare it to itself:
+
+.. sourcecode:: jinja
+
+ {{ undefined == undefined }}
+ will return false. Not even undefined is undefined :)
+ Use `is defined` / `is not defined`:
+
+ {{ undefined is not defined }}
+ will return true.
+
+There are also some additional rules regarding this special value. Any
+mathematical operators (``+``, ``-``, ``*``, ``/``) return the operand
+as result:
+
+.. sourcecode:: jinja
+
+ {{ undefined + "foo" }}
+ returns "foo"
+
+ {{ undefined - 42 }}
+ returns 42. Note: not -42!
+
+In any expression `undefined` evaluates to `false`. It has no length, all
+attribute calls return undefined, calling too:
+
+.. sourcecode:: jinja
+
+ {{ undefined.attribute().attribute_too[42] }}
+ still returns `undefined`.
+
+Escaping
+========
+
+Sometimes you might want to add Jinja syntax elements into the template
+without executing them. In that case you have quite a few possibilities.
+
+For small parts this might be a good way:
+
+.. sourcecode:: jinja
+
+ {{ "{{ foo }} is variable syntax and {% foo %} is block syntax" }}
+
+When you have multiple elements you can use the ``raw`` block:
+
+.. sourcecode:: jinja
+
+ {% raw %}
+ Filtering blocks works like this in Jinja:
+ {% filter escape %}
+ <html>
+ <code>goes here</code>
+ </html>
+ {% endfilter %}
+ {% endraw %}
+
+Reserved Keywords
+=================
+
+Jinja has some keywords you cannot use a variable names. This limitation
+exists to make look coherent. Syntax highlighters won't mess things up and
+you will don't have unexpected output.
+
+The following keywords exist and cannot be used as identifiers:
+
+ `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,
+ `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,
+ `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,
+ `raw`, `recursive`, `set`, `trans`
+
+If you want to use such a name you have to prefix or suffix it or use
+alternative names:
+
+.. sourcecode:: jinja
+
+ {% for macro_ in macros %}
+ {{ macro_('foo') }}
+ {% endfor %}
+
+If future Jinja releases add new keywords those will be "light" keywords which
+means that they won't raise an error for several releases but yield warnings
+on the application side. But it's very unlikely that new keywords will be
+added.
+
+Internationalization
+====================
+
+If the application is configured for i18n, you can define translatable blocks
+for translators using the `trans` tag or the special underscore function:
+
+.. sourcecode:: jinja
+
+ {% trans %}
+ this is a translatable block
+ {% endtrans %}
+
+ {% trans "This is a translatable string" %}
+
+ {{ _("This is a translatable string") }}
+
+The latter one is useful if you want translatable arguments for filters etc.
+
+If you want to have plural forms too, use the `pluralize` block:
+
+.. sourcecode:: jinja
+
+ {% trans users=users %}
+ One user found.
+ {% pluralize %}
+ {{ users }} users found.
+ {% endtrans %}
+
+ {% trans first=(users|first).username|escape, user=users|length %}
+ one user {{ first }} found.
+ {% pluralize users %}
+ {{ users }} users found, the first one is called {{ first }}.
+ {% endtrans %}
+
+If you have multiple arguments, the first one is assumed to be the indicator (the
+number that is used to determine the correct singular or plural form. If you
+don't have the indicator variable on position 1 you have to tell the `pluralize`
+tag the correct variable name.
+
+Inside translatable blocks you cannot use blocks or expressions (however you can
+still use the ``raw`` block which will work as expected). The variable
+print syntax (``{{ variablename }}``) is the only way to insert the variables
+defined in the ``trans`` header. Filters must be applied in the header.
+
+.. admonition:: note
+
+ Please make sure that you always use pluralize blocks where required.
+ Many languages have more complex plural forms than the English language.
+
+ Never try to workaround that issue by using something like this:
+
+ .. sourcecode:: jinja
+
+ {% if count != 1 %}
+ {{ count }} users found.
+ {% else %}
+ one user found.
+ {% endif %}
+
+.. _slicing chapter: http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
+.. _range function: http://docs.python.org/tut/node6.html#SECTION006300000000000000000
+
+---tokens---
+'======================' Generic.Heading
+'\n' Text
+
+'Designer Documentation' Generic.Heading
+'\n' Text
+
+'======================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'This part of the Jinja documentaton is meant for template designers.' Text
+'\n' Text
+
+'\n' Text
+
+'Basics' Generic.Heading
+'\n' Text
+
+'======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The Jinja template language is designed to strike a balance between content' Text
+'\n' Text
+
+'and application logic. Nevertheless you can use a python like statement' Text
+'\n' Text
+
+"language. You don't have to know how Python works to create Jinja templates," Text
+'\n' Text
+
+'but if you know it you can use some additional statements you may know from' Text
+'\n' Text
+
+'Python.' Text
+'\n' Text
+
+'\n' Text
+
+'Here is a small example template' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' Comment.Preproc
+
+' ' Text
+' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'html' Name.Tag
+' ' Text
+'xmlns' Name.Attribute
+'=' Operator
+'"http://www.w3.org/1999/xhtml"' Literal.String
+' ' Text
+'lang' Name.Attribute
+'=' Operator
+'"en"' Literal.String
+' ' Text
+'xml:lang' Name.Attribute
+'=' Operator
+'"en"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'head' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'title' Name.Tag
+'>' Punctuation
+'My Webpage' Text
+'<' Punctuation
+'/' Punctuation
+'title' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'head' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'body' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'ul' Name.Tag
+' ' Text
+'id' Name.Attribute
+'=' Operator
+'"navigation"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'item' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'navigation' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'<' Punctuation
+'a' Name.Tag
+' ' Text
+'href' Name.Attribute
+'=' Operator
+'"' Literal.String
+'{{' Comment.Preproc
+' ' Text
+'item' Name.Variable
+'.href' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'item' Name.Variable
+'.caption' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'a' Name.Tag
+'>' Punctuation
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'My Webpage' Text
+'<' Punctuation
+'/' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'variable' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'body' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'html' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'This covers the default settings. The application developer might have changed' Text
+'\n' Text
+
+'the syntax from ' Text
+'``' Literal.String
+'{% foo %}' Literal.String
+'``' Literal.String
+' to ' Text
+'``' Literal.String
+'<% foo %>' Literal.String
+'``' Literal.String
+' or something similar. This' Text
+'\n' Text
+
+'documentation just covers the default values.' Text
+'\n' Text
+
+'\n' Text
+
+'A variable looks like ' Text
+'``' Literal.String
+'{{ foobar }}' Literal.String
+'``' Literal.String
+' where foobar is the variable name. Inside' Text
+'\n' Text
+
+'of statements (' Text
+'``' Literal.String
+'{% some content here %}' Literal.String
+'``' Literal.String
+') variables are just normal names' Text
+'\n' Text
+
+'without the braces around it. In fact ' Text
+'``' Literal.String
+'{{ foobar }}' Literal.String
+'``' Literal.String
+' is just an alias for' Text
+'\n' Text
+
+'the statement ' Text
+'``' Literal.String
+'{% print foobar %}' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Variables are coming from the context provided by the application. Normally there' Text
+'\n' Text
+
+'should be a documentation regarding the context contents but if you want to know' Text
+'\n' Text
+
+'the content of the current context, you can add this to your template' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<' Punctuation
+'pre' Name.Tag
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'debug' Name.Variable
+'(' Operator
+')' Operator
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'pre' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+"A context isn't flat which means that each variable can has subvariables, as long" Text
+'\n' Text
+
+'as it is representable as python data structure. You can access attributes of' Text
+'\n' Text
+
+'a variable using the dot and bracket operators. The following examples show' Text
+'\n' Text
+
+'this' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.username' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' is the same as\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'[' Operator
+"'username'" Literal.String.Single
+']' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' you can also use a variable to access an attribute:\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'users' Name.Variable
+'[' Operator
+'current_user' Name.Variable
+']' Operator
+'.username' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' If you have numerical indices you have to use the [] syntax:\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'users' Name.Variable
+'[' Operator
+'0' Literal.Number
+']' Operator
+'.username' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'Filters' Generic.Heading
+'\n' Text
+
+'=======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'In the examples above you might have noticed the pipe symbols. Pipe symbols tell' Text
+'\n' Text
+
+'the engine that it has to apply a filter on the variable. Here is a small example' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'variable' Name.Variable
+'|' Operator
+'replace' Name.Function
+'(' Operator
+"'foo'" Literal.String.Single
+',' Operator
+' ' Text
+"'bar'" Literal.String.Single
+')' Operator
+'|' Operator
+'escape' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'If you want, you can also put whitespace between the filters.' Text
+'\n' Text
+
+'\n' Text
+
+'This will look for a variable ' Text
+'`variable`' Name.Variable
+', pass it to the filter ' Text
+'`replace`' Name.Variable
+'\n' Text
+
+'with the arguments ' Text
+'``' Literal.String
+"'foo'" Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+"'bar'" Literal.String
+'``' Literal.String
+', and pass the result to the filter' Text
+'\n' Text
+
+'`escape`' Name.Variable
+' that automatically XML-escapes the value. The ' Text
+'`e`' Name.Variable
+' filter is an alias for' Text
+'\n' Text
+
+'`escape`' Name.Variable
+'. Here is the complete list of supported filters' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'[' Text
+'[' Text
+'list_of_filters]]' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'admonition' Operator.Word
+'::' Punctuation
+' ' Text
+'note' Text
+'\n' Text
+
+'\n' Text
+
+' Filters have a pretty low priority. If you want to add fitered values' Text
+'\n' Text
+
+' you have to put them into parentheses. The same applies if you want to access' Text
+'\n' Text
+
+' attributes' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+' ..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'correct:\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'(' Operator
+'foo' Name.Variable
+'|' Operator
+'filter' Name.Function
+')' Operator
+' ' Text
+'+' Operator
+' ' Text
+'(' Operator
+'bar' Name.Variable
+'|' Operator
+'filter' Name.Function
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'wrong:\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'foo' Name.Variable
+'|' Operator
+'filter' Name.Function
+' ' Text
+'+' Operator
+' ' Text
+'bar' Name.Variable
+'|' Operator
+'filter' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+' ' Text
+'correct:\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'(' Operator
+'foo' Name.Variable
+'|' Operator
+'filter' Name.Function
+')' Operator
+'.attribute' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'wrong:\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'foo' Name.Variable
+'|' Operator
+'filter' Name.Function
+'.attribute' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'Tests' Generic.Heading
+'\n' Text
+
+'=====' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'You can use the ' Text
+'`is`' Name.Variable
+' operator to perform tests on a value' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'4' Literal.Number
+'2' Literal.Number
+' ' Text
+'is' Keyword
+' ' Text
+'numeric' Name.Function
+' ' Text
+'}}' Comment.Preproc
+' -> true\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'"foobar"' Literal.String.Double
+' ' Text
+'is' Keyword
+' ' Text
+'numeric' Name.Function
+' ' Text
+'}}' Comment.Preproc
+' -> false\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+"'FOO'" Literal.String.Single
+' ' Text
+'is' Keyword
+' ' Text
+'upper' Name.Function
+' ' Text
+'}}' Comment.Preproc
+' -> true\n\n' Other
+
+'These tests are especially useful when used in ' Text
+'`if`' Name.Variable
+' conditions.' Text
+'\n' Text
+
+'\n' Text
+
+'[' Text
+'[' Text
+'list_of_tests]]' Text
+'\n' Text
+
+'\n' Text
+
+'Global Functions' Generic.Heading
+'\n' Text
+
+'================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Test functions and filter functions live in their own namespace. Global' Text
+'\n' Text
+
+'functions not. They behave like normal objects in the context. Beside the' Text
+'\n' Text
+
+'functions added by the application or framewhere there are two functions' Text
+'\n' Text
+
+'available per default' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'`range`' Name.Variable
+'\n' Text
+
+' ' Text
+'\n' Text
+
+' Works like the python ' Text
+'`range function`_' Literal.String
+" just that it doesn't support" Text
+'\n' Text
+
+' ranges greater than ' Text
+'``' Literal.String
+'1000000' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'`debug`' Name.Variable
+'\n' Text
+
+'\n' Text
+
+' Function that outputs the contents of the context.' Text
+'\n' Text
+
+'\n' Text
+
+'Loops' Generic.Heading
+'\n' Text
+
+'=====' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'To iterate over a sequence, you can use the ' Text
+'`for`' Name.Variable
+' loop. It basically looks like a' Text
+'\n' Text
+
+'normal Python ' Text
+'`for`' Name.Variable
+' loop and works pretty much the same' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'Members' Text
+'<' Punctuation
+'/' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'user' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'users' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'loop' Name.Builtin
+'.index' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' / ' Text
+'{{' Comment.Preproc
+' ' Text
+'loop' Name.Builtin
+'.length' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' - ' Text
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.username' Name.Variable
+'|' Operator
+'escape' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'else' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'<' Punctuation
+'em' Name.Tag
+'>' Punctuation
+'no users found' Text
+'<' Punctuation
+'/' Punctuation
+'em' Name.Tag
+'>' Punctuation
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'*Important*' Generic.Emph
+' Contrary to Python is the optional ' Text
+'``' Literal.String
+'else' Literal.String
+'``' Literal.String
+' block only' Text
+'\n' Text
+
+'executed if there was no iteration because the sequence was empty.' Text
+'\n' Text
+
+'\n' Text
+
+'Inside of a ' Text
+'`for`' Name.Variable
+' loop block you can access some special variables' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' Variable | Description |' Text
+'\n' Text
+
+'+======================+========================================+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.index`' Name.Variable
+' | The current iteration of the loop. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.index0`' Name.Variable
+' | The current iteration of the loop, |' Text
+'\n' Text
+
+'|' Operator
+' | starting counting by 0. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.revindex`' Name.Variable
+' | The number of iterations from the end |' Text
+'\n' Text
+
+'|' Operator
+' | of the loop. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.revindex0`' Name.Variable
+' | The number of iterations from the end |' Text
+'\n' Text
+
+'|' Operator
+' | of the loop, starting counting by 0. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.first`' Name.Variable
+' | True if first iteration. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.last`' Name.Variable
+' | True if last iteration. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.even`' Name.Variable
+' | True if current iteration is even. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.odd`' Name.Variable
+' | True if current iteration is odd. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.length`' Name.Variable
+' | Total number of items in the sequence. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'|' Operator
+' ' Text
+'`loop.parent`' Name.Variable
+' | The context of the parent loop. |' Text
+'\n' Text
+
+'+----------------------+----------------------------------------+' Text
+'\n' Text
+
+'\n' Text
+
+"Loops also support recursion. Let's assume you have a sitemap where each item" Text
+'\n' Text
+
+'might have a number of child items. A template for that could look like this' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'Sitemap\n' Text
+
+' ' Text
+'<' Punctuation
+'ul' Name.Tag
+' ' Text
+'id' Name.Attribute
+'=' Operator
+'"sitemap"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'item' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'sitemap' Name.Variable
+' ' Text
+'recursive' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'<' Punctuation
+'a' Name.Tag
+' ' Text
+'href' Name.Attribute
+'=' Operator
+'"' Literal.String
+'{{' Comment.Preproc
+' ' Text
+'item' Name.Variable
+'.url' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'item' Name.Variable
+'.title' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'a' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'item' Name.Variable
+'.children' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'<' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'loop' Name.Builtin
+'(' Operator
+'item' Name.Variable
+'.children' Name.Variable
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'{%' Comment.Preproc
+' ' Text
+'endif' Keyword
+' ' Text
+'%}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'What happens here? Basically the first thing that is different to a normal' Text
+'\n' Text
+
+'loop is the additional ' Text
+'``' Literal.String
+'recursive' Literal.String
+'``' Literal.String
+' modifier in the ' Text
+'`for`' Name.Variable
+'-loop declaration.' Text
+'\n' Text
+
+'It tells the template engine that we want recursion. If recursion is enabled' Text
+'\n' Text
+
+'the special ' Text
+'`loop`' Name.Variable
+' variable is callable. If you call it with a sequence it will' Text
+'\n' Text
+
+'automatically render the loop at that position with the new sequence as argument.' Text
+'\n' Text
+
+'\n' Text
+
+'Cycling' Generic.Heading
+'\n' Text
+
+'=======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Sometimes you might want to have different text snippets for each row in a list,' Text
+'\n' Text
+
+'for example to have alternating row colors. You can easily do this by using the' Text
+'\n' Text
+
+'``' Literal.String
+'{% cycle %}' Literal.String
+'``' Literal.String
+' tag' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<' Punctuation
+'ul' Name.Tag
+' ' Text
+'id' Name.Attribute
+'=' Operator
+'"messages"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'message' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'messages' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+' ' Text
+'class' Name.Attribute
+'=' Operator
+'"' Literal.String
+'{%' Comment.Preproc
+' ' Text
+'cycle' Keyword
+' ' Text
+"'row1'" Literal.String.Single
+',' Operator
+' ' Text
+"'row2'" Literal.String.Single
+' ' Text
+'%}' Comment.Preproc
+'"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'message' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'ul' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'Each time Jinja encounters a ' Text
+'`cycle`' Name.Variable
+' tag it will cycle through the list' Text
+'\n' Text
+
+'of given items and return the next one. If you pass it one item jinja assumes' Text
+'\n' Text
+
+'that this item is a sequence from the context and uses this' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<' Punctuation
+'li' Name.Tag
+' ' Text
+'style' Name.Attribute
+'=' Operator
+'"color: ' Literal.String
+'{%' Comment.Preproc
+' ' Text
+'cycle' Keyword
+' ' Text
+'rowcolors' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'"' Literal.String
+'>' Punctuation
+'...' Text
+'<' Punctuation
+'/' Punctuation
+'li' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'Conditions' Generic.Heading
+'\n' Text
+
+'==========' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Jinja supports Python-like ' Text
+'`if`' Name.Variable
+' / ' Text
+'`elif`' Name.Variable
+' / ' Text
+'`else`' Name.Variable
+' constructs' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'user' Name.Variable
+'.active' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' user ' Other
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.name' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+' is active.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'elif' Keyword
+' ' Text
+'user' Name.Variable
+'.deleted' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' user ' Other
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.name' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+' was deleted some time ago.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'else' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+" i don't know what's wrong with " Other
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.username' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endif' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'If the user is active the first block is rendered. If not and the user was' Text
+'\n' Text
+
+'deleted the second one, in all other cases the third one.' Text
+'\n' Text
+
+'\n' Text
+
+'You can also use comparison operators' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'amount' Name.Variable
+' ' Text
+'<' Operator
+' ' Text
+'0' Literal.Number
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'span' Name.Tag
+' ' Text
+'style' Name.Attribute
+'=' Operator
+'"color: red"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'amount' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'span' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'else' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'span' Name.Tag
+' ' Text
+'style' Name.Attribute
+'=' Operator
+'"color: black"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'amount' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'span' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endif' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Text
+
+'..' Punctuation
+' ' Text
+'admonition' Operator.Word
+'::' Punctuation
+' ' Text
+'Note' Text
+'\n' Text
+
+'\n' Text
+
+' Of course you can use ' Text
+'`or`' Name.Variable
+' / ' Text
+'`and`' Name.Variable
+' and parentheses to create more complex' Text
+'\n' Text
+
+' conditions, but usually the logic is already handled in the application and' Text
+'\n' Text
+
+" you don't have to create such complex constructs in the template code. However" Text
+'\n' Text
+
+' in some situations it might be a good thing to have the abilities to create' Text
+'\n' Text
+
+' them.' Text
+'\n' Text
+
+'\n' Text
+
+'Operators' Generic.Heading
+'\n' Text
+
+'=========' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Inside ' Text
+'``' Literal.String
+'{{ variable }}' Literal.String
+'``' Literal.String
+' blocks, ' Text
+'`if`' Name.Variable
+' conditions and many other parts you can' Text
+'\n' Text
+
+'can use expressions. In expressions you can use any of the following operators' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+' ======= ===================================================================' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'+' Literal.String
+'``' Literal.String
+' add the right operand to the left one.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'{{ 1 + 2 }}' Literal.String
+'``' Literal.String
+' would return ' Text
+'``' Literal.String
+'3' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'-' Literal.String
+'``' Literal.String
+' subtract the right operand from the left one.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'{{ 1 - 1 }}' Literal.String
+'``' Literal.String
+' would return ' Text
+'``' Literal.String
+'0' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'/' Literal.String
+'``' Literal.String
+' divide the left operand by the right one.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'{{ 1 / 2 }}' Literal.String
+'``' Literal.String
+' would return ' Text
+'``' Literal.String
+'0.5' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'*' Literal.String
+'``' Literal.String
+' multiply the left operand with the right one.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'{{ 2 * 2 }}' Literal.String
+'``' Literal.String
+' would return ' Text
+'``' Literal.String
+'4' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'**' Literal.String
+'``' Literal.String
+' raise the left operand to the power of the right' Text
+'\n' Text
+
+' operand. ' Text
+'``' Literal.String
+'{{ 2**3 }}' Literal.String
+'``' Literal.String
+' would return ' Text
+'``' Literal.String
+'8' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'in' Literal.String
+'``' Literal.String
+' perform sequence membership test. ' Text
+'``' Literal.String
+'{{ 1 in [1,2,3] }}' Literal.String
+'``' Literal.String
+' would' Text
+'\n' Text
+
+' return true.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'is' Literal.String
+'``' Literal.String
+' perform a test on the value. See the section about' Text
+'\n' Text
+
+' tests for more information.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'|' Literal.String
+'``' Literal.String
+' apply a filter on the value. See the section about' Text
+'\n' Text
+
+' filters for more information.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'and' Literal.String
+'``' Literal.String
+' return true if the left and the right operand is true.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'or' Literal.String
+'``' Literal.String
+' return true if the left or the right operand is true.' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'not' Literal.String
+'``' Literal.String
+' negate a statement (see below)' Text
+'\n' Text
+
+' ' Text
+'``' Literal.String
+'()' Literal.String
+'``' Literal.String
+' call a callable' Text
+':' Text
+' ' Text
+'``' Literal.String
+'{{ user.get_username() }}' Literal.String
+'``' Literal.String
+'. Inside of the' Text
+'\n' Text
+
+' parentheses you can use variables' Text
+':' Text
+' ' Text
+'``' Literal.String
+'{{ user.get(username) }}' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+' ======= ===================================================================' Text
+'\n' Text
+
+'\n' Text
+
+'Note that there is no support for any bit operations or something similar.' Text
+'\n' Text
+
+'\n' Text
+
+'*' Literal.Number
+' special note regarding ' Text
+'`not`' Name.Variable
+':' Text
+' The ' Text
+'`is`' Name.Variable
+' and ' Text
+'`in`' Name.Variable
+' operators support negation' Text
+'\n' Text
+
+' using an infix notation too' Text
+':' Text
+' ' Text
+'``' Literal.String
+'foo is not bar' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'foo not in bar' Literal.String
+'``' Literal.String
+'\n' Text
+
+' instead of ' Text
+'``' Literal.String
+'not foo is bar' Literal.String
+'``' Literal.String
+' and ' Text
+'``' Literal.String
+'not foo in bar' Literal.String
+'``' Literal.String
+'. All other expressions' Text
+'\n' Text
+
+' require a prefix notation' Text
+':' Text
+' ' Text
+'``' Literal.String
+'not (foo and bar)' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Boolean Values' Generic.Heading
+'\n' Text
+
+'==============' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'In If-Conditions Jinja performs a boolean check. All empty values (eg' Text
+':' Text
+' empty' Text
+'\n' Text
+
+'lists ' Text
+'``' Literal.String
+'[]' Literal.String
+'``' Literal.String
+', empty dicts ' Text
+'``' Literal.String
+'{}' Literal.String
+'``' Literal.String
+' etc) evaluate to ' Text
+'`false`' Name.Variable
+'. Numbers that are' Text
+'\n' Text
+
+'equal to ' Text
+'`0`' Name.Variable
+'/' Text
+'`0.00`' Name.Variable
+' are considered ' Text
+'`false`' Name.Variable
+' too. The boolean value of other' Text
+'\n' Text
+
+'objects depends on the behavior the application developer gave it. Usually' Text
+'\n' Text
+
+'items are ' Text
+'`true`' Name.Variable
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Here some examples that should explain it' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'[' Operator
+']' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+" will always be false because it's an empty list\n\n" Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'{' Operator
+'}' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' false too.\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'[' Operator
+"'foo'" Literal.String.Single
+']' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' this is true. Because the list is not empty.\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'"foobar"' Literal.String.Double
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' this is also true because the string is not empty.\n\n' Other
+
+'Slicing' Generic.Heading
+'\n' Text
+
+'=======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Some objects support slicing operations. For example lists' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'item' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'items' Name.Variable
+'[' Operator
+':' Operator
+'5' Literal.Number
+']' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' This will only iterate over the first 5 items of the list\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'item' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'items' Name.Variable
+'[' Operator
+'5' Literal.Number
+':' Operator
+'1' Literal.Number
+'0' Literal.Number
+']' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' This will only iterate from item 5 to 10.\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'item' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'items' Name.Variable
+'[' Operator
+':' Operator
+'1' Literal.Number
+'0' Literal.Number
+':' Operator
+'2' Literal.Number
+']' Operator
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' This will only yield items from start to ten and only returing\n' Other
+
+' ' Text
+' even items.\n\n' Other
+
+'For more informations about slicing have a look at the ' Text
+'`slicing chapter`_' Literal.String
+'\n' Text
+
+'in the "Dive into Python" e-book.' Text
+'\n' Text
+
+'\n' Text
+
+'Macros' Generic.Heading
+'\n' Text
+
+'======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'If you want to use a partial template in more than one place, you might want to' Text
+'\n' Text
+
+'create a macro from it' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'macro' Keyword
+' ' Text
+'show_user' Name.Variable
+' ' Text
+'user' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.name' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'div' Name.Tag
+' ' Text
+'class' Name.Attribute
+'=' Operator
+'"test"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'user' Name.Variable
+'.description' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'div' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endmacro' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Text
+
+'Now you can use it from everywhere in the code by passing it an item' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n \n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'user' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'users' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'show_user' Name.Variable
+'(' Operator
+'user' Name.Variable
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'You can also specify more than one value' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'macro' Keyword
+' ' Text
+'show_dialog' Name.Variable
+' ' Text
+'title' Name.Variable
+',' Operator
+' ' Text
+'text' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'div' Name.Tag
+' ' Text
+'class' Name.Attribute
+'=' Operator
+'"dialog"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'title' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'div' Name.Tag
+' ' Text
+'class' Name.Attribute
+'=' Operator
+'"test"' Literal.String
+'>' Punctuation
+'{{' Comment.Preproc
+' ' Text
+'text' Name.Variable
+'|' Operator
+'e' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'<' Punctuation
+'/' Punctuation
+'div' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'div' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endmacro' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'show_dialog' Name.Variable
+'(' Operator
+"'Warning'" Literal.String.Single
+',' Operator
+' ' Text
+"'something went wrong i guess'" Literal.String.Single
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Text
+
+'Inheritance' Generic.Heading
+'\n' Text
+
+'===========' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'The most powerful part of Jinja is template inheritance. Template inheritance' Text
+'\n' Text
+
+'allows you to build a base "skeleton" template that contains all the common' Text
+'\n' Text
+
+'elements of your site and defines ' Text
+'**blocks**' Generic.Strong
+' that child templates can override.' Text
+'\n' Text
+
+'\n' Text
+
+"Sounds complicated but is very basic. It's easiest to understand it by starting" Text
+'\n' Text
+
+'with an example.' Text
+'\n' Text
+
+'\n' Text
+
+'Base Template' Generic.Heading
+'\n' Text
+
+'-------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+"This template, which we'll call " Text
+'``' Literal.String
+'base.html' Literal.String
+'``' Literal.String
+', defines a simple HTML skeleton' Text
+'\n' Text
+
+"document that you might use for a simple two-column page. It's the job of" Text
+'\n' Text
+
+'"child" templates to fill the empty blocks with content' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"\n' Comment.Preproc
+
+' ' Text
+' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'html' Name.Tag
+' ' Text
+'xmlns' Name.Attribute
+'=' Operator
+'"http://www.w3.org/1999/xhtml"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'head' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'link' Name.Tag
+' ' Text
+'rel' Name.Attribute
+'=' Operator
+'"stylesheet"' Literal.String
+' ' Text
+'href' Name.Attribute
+'=' Operator
+'"style.css"' Literal.String
+' ' Text
+'/' Punctuation
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'title' Name.Tag
+'>' Punctuation
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'title' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+' - My Webpage' Text
+'<' Punctuation
+'/' Punctuation
+'title' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'html_head' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'head' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'body' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'div' Name.Tag
+' ' Text
+'id' Name.Attribute
+'=' Operator
+'"content"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'content' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'div' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'div' Name.Tag
+' ' Text
+'id' Name.Attribute
+'=' Operator
+'"footer"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'footer' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'&copy;' Name.Entity
+' Copyright 2006 by ' Text
+'<' Punctuation
+'a' Name.Tag
+' ' Text
+'href' Name.Attribute
+'=' Operator
+'"http://mydomain.tld"' Literal.String
+'>' Punctuation
+'myself' Text
+'<' Punctuation
+'/' Punctuation
+'a' Name.Tag
+'>' Punctuation
+'.\n' Text
+
+' ' Text
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'div' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'body' Name.Tag
+'>' Punctuation
+'\n\n' Text
+
+'In this example, the ' Text
+'``' Literal.String
+'{% block %}' Literal.String
+'``' Literal.String
+' tags define four blocks that child templates' Text
+'\n' Text
+
+'can fill in. All the ' Text
+'`block`' Name.Variable
+' tag does is to tell the template engine that a' Text
+'\n' Text
+
+'child template may override those portions of the template.' Text
+'\n' Text
+
+'\n' Text
+
+'Child Template' Generic.Heading
+'\n' Text
+
+'--------------' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'A child template might look like this' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'html+jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'extends' Keyword
+' ' Text
+'"base.html"' Literal.String.Double
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'title' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'Index' Text
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'html_head' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'style' Name.Tag
+' ' Text
+'type' Name.Attribute
+'=' Operator
+'"text/css"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'.' Punctuation
+'important' Name.Class
+' ' Text
+'{' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'color' Keyword
+':' Punctuation
+' ' Text
+'#336699' Literal.Number.Hex
+';' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'}' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'style' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'block' Keyword
+' ' Text
+'content' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'Index' Text
+'<' Punctuation
+'/' Punctuation
+'h1' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'p' Name.Tag
+' ' Text
+'class' Name.Attribute
+'=' Operator
+'"important"' Literal.String
+'>' Punctuation
+'\n' Text
+
+' ' Text
+' Welcome on my awsome homepage.\n' Text
+
+' ' Text
+' ' Text
+'<' Punctuation
+'/' Punctuation
+'p' Name.Tag
+'>' Punctuation
+'\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endblock' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Text
+
+'The ' Text
+'``' Literal.String
+'{% extends %}' Literal.String
+'``' Literal.String
+' tag is the key here. It tells the template engine that' Text
+'\n' Text
+
+'this template "extends" another template. When the template system evaluates' Text
+'\n' Text
+
+'this template, first it locates the parent.' Text
+'\n' Text
+
+'\n' Text
+
+'The filename of the template depends on the template loader. For example the' Text
+'\n' Text
+
+'``' Literal.String
+'FileSystemLoader' Literal.String
+'``' Literal.String
+' allows you to access other templates by giving the' Text
+'\n' Text
+
+'filename. You can access templates in subdirectories with an slash' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'extends' Keyword
+' ' Text
+'"layout/default.html"' Literal.String.Double
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'But this behavior can depend on the application using Jinja.' Text
+'\n' Text
+
+'\n' Text
+
+"Note that since the child template didn't define the " Text
+'``' Literal.String
+'footer' Literal.String
+'``' Literal.String
+' block, the' Text
+'\n' Text
+
+'value from the parent template is used instead.' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'admonition' Operator.Word
+'::' Punctuation
+' ' Text
+'Note' Text
+'\n' Text
+
+'\n' Text
+
+" You can't define multiple " Text
+'``' Literal.String
+'{% block %}' Literal.String
+'``' Literal.String
+' tags with the same name in the' Text
+'\n' Text
+
+' same template. This limitation exists because a block tag works in "both"' Text
+'\n' Text
+
+" directions. That is, a block tag doesn't just provide a hole to fill - it" Text
+'\n' Text
+
+' also defines the content that fills the hole in the ' Text
+'*parent*' Generic.Emph
+'. If there were' Text
+'\n' Text
+
+' two similarly-named ' Text
+'``' Literal.String
+'{% block %}' Literal.String
+'``' Literal.String
+" tags in a template, that template's" Text
+'\n' Text
+
+" parent wouldn't know which one of the blocks' content to use." Text
+'\n' Text
+
+'\n' Text
+
+'Template Inclusion' Generic.Heading
+'\n' Text
+
+'==================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'You can load another template at a given position using ' Text
+'``' Literal.String
+'{% include %}' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+"Usually it's a better idea to use inheritance but if you for example want to" Text
+'\n' Text
+
+'load macros, ' Text
+'`include`' Name.Variable
+' works better than ' Text
+'`extends`' Name.Variable
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'include' Keyword
+' ' Text
+'"myhelpers.html"' Literal.String.Double
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'my_helper' Name.Variable
+'(' Operator
+'"foo"' Literal.String.Double
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'If you define a macro called ' Text
+'``' Literal.String
+'my_helper' Literal.String
+'``' Literal.String
+' in ' Text
+'``' Literal.String
+'myhelpers.html' Literal.String
+'``' Literal.String
+', you can now' Text
+'\n' Text
+
+'use it from the template as shown above.' Text
+'\n' Text
+
+'\n' Text
+
+'Filtering Blocks' Generic.Heading
+'\n' Text
+
+'================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Sometimes it could be a good idea to filter a complete block of text. For' Text
+'\n' Text
+
+'example, if you want to escape some html code' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'filter' Keyword
+' ' Text
+'escape' Name.Function
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' <html>\n' Other
+
+' ' Text
+' <code>goes here</code>\n' Other
+
+' ' Text
+' </html>\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfilter' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'Of course you can chain filters too' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'filter' Keyword
+' ' Text
+'lower' Name.Function
+'|' Operator
+'escape' Name.Function
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' <B>SOME TEXT</B>\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfilter' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'returns ' Text
+'``' Literal.String
+'"&lt;b&gt;some text&lt;/b&gt;"' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Defining Variables' Generic.Heading
+'\n' Text
+
+'==================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'You can also define variables in the namespace using the ' Text
+'``' Literal.String
+'{% set %}' Literal.String
+'``' Literal.String
+' tag' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'set' Keyword
+' ' Text
+'foo' Name.Variable
+' ' Text
+'=' Operator
+' ' Text
+"'foobar'" Literal.String.Single
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'foo' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'This should ouput ' Text
+'``' Literal.String
+'foobar' Literal.String
+'``' Literal.String
+'.' Text
+'\n' Text
+
+'\n' Text
+
+'Scopes' Generic.Heading
+'\n' Text
+
+'======' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Jinja has multiple scopes. A scope is something like a new transparent foil on' Text
+'\n' Text
+
+'a stack of foils. You can only write to the outermost foil but read all of them' Text
+'\n' Text
+
+'since you can look through them. If you remove the top foil all data on that' Text
+'\n' Text
+
+'foil disappears. Some tags in Jinja add a new layer to the stack. Currently' Text
+'\n' Text
+
+'these are ' Text
+'`block`' Name.Variable
+', ' Text
+'`for`' Name.Variable
+', ' Text
+'`macro`' Name.Variable
+' and ' Text
+'`filter`' Name.Variable
+'. This means that variables and' Text
+'\n' Text
+
+'other elements defined inside a macro, loop or some of the other tags listed' Text
+'\n' Text
+
+'above will be only available in that block. Here an example' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'macro' Keyword
+' ' Text
+'angryhello' Name.Variable
+' ' Text
+'name' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{%' Comment.Preproc
+' ' Text
+'set' Keyword
+' ' Text
+'angryname' Name.Variable
+' ' Text
+'=' Operator
+' ' Text
+'name' Name.Variable
+'|' Operator
+'upper' Name.Function
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' Hello ' Other
+'{{' Comment.Preproc
+' ' Text
+'name' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'. Hello ' Other
+'{{' Comment.Preproc
+' ' Text
+'name' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'!\n' Other
+
+' ' Text
+' HELLO ' Other
+'{{' Comment.Preproc
+' ' Text
+'angryname' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'!!!!!!111\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endmacro' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'The variable ' Text
+'``' Literal.String
+'angryname' Literal.String
+'``' Literal.String
+' just exists inside the macro, not outside it.' Text
+'\n' Text
+
+'\n' Text
+
+'Defined macros appear on the context as variables. Because of this, they are' Text
+'\n' Text
+
+'affected by the scoping too. A macro defined inside of a macro is just available' Text
+'\n' Text
+
+"in those two macros (the macro itself and the macro it's defined in). For " Text
+'`set`' Name.Variable
+'\n' Text
+
+'and ' Text
+'`macro`' Name.Variable
+' two additional rules exist' Text
+':' Text
+' If a macro is defined in an extended' Text
+'\n' Text
+
+'template but outside of a visible block (thus outside of any block) will be' Text
+'\n' Text
+
+'available in all blocks below. This allows you to use ' Text
+'`include`' Name.Variable
+' statements to' Text
+'\n' Text
+
+'load often used macros at once.' Text
+'\n' Text
+
+'\n' Text
+
+'Undefined Variables' Generic.Heading
+'\n' Text
+
+'===================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'If you have already worked with python you probably know about the fact that' Text
+'\n' Text
+
+'undefined variables raise an exception. This is different in Jinja. There is a' Text
+'\n' Text
+
+'special value called ' Text
+'`undefined`' Name.Variable
+' that represents values that do not exist.' Text
+'\n' Text
+
+'\n' Text
+
+'This special variable works complete different from any variables you maybe' Text
+'\n' Text
+
+'know. If you print it using ' Text
+'``' Literal.String
+'{{ variable }}' Literal.String
+'``' Literal.String
+" it will not appear because it's" Text
+'\n' Text
+
+'literally empty. If you try to iterate over it, it will work. But no items' Text
+'\n' Text
+
+'are returned. Comparing this value to any other value results in ' Text
+'`false`' Name.Variable
+'.' Text
+'\n' Text
+
+'Even if you compare it to itself' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'undefined' Name.Variable
+' ' Text
+'==' Operator
+' ' Text
+'undefined' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' will return false. Not even undefined is undefined :)\n' Other
+
+' ' Text
+' Use `is defined` / `is not defined`:\n\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'undefined' Name.Variable
+' ' Text
+'is' Keyword
+' ' Text
+'not' Keyword
+' ' Text
+'defined' Name.Function
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' will return true.\n\n' Other
+
+'There are also some additional rules regarding this special value. Any' Text
+'\n' Text
+
+'mathematical operators (' Text
+'``' Literal.String
+'+' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'-' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'*' Literal.String
+'``' Literal.String
+', ' Text
+'``' Literal.String
+'/' Literal.String
+'``' Literal.String
+') return the operand' Text
+'\n' Text
+
+'as result' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'undefined' Name.Variable
+' ' Text
+'+' Operator
+' ' Text
+'"foo"' Literal.String.Double
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' returns "foo"\n\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'undefined' Name.Variable
+' ' Text
+'-' Operator
+' ' Text
+'4' Literal.Number
+'2' Literal.Number
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' returns 42. Note: not -42!\n\n' Other
+
+'In any expression ' Text
+'`undefined`' Name.Variable
+' evaluates to ' Text
+'`false`' Name.Variable
+'. It has no length, all' Text
+'\n' Text
+
+'attribute calls return undefined, calling too' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'undefined' Name.Variable
+'.attribute' Name.Variable
+'(' Operator
+')' Operator
+'.attribute_too' Name.Variable
+'[' Operator
+'4' Literal.Number
+'2' Literal.Number
+']' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' still returns `undefined`.\n\n' Other
+
+'Escaping' Generic.Heading
+'\n' Text
+
+'========' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Sometimes you might want to add Jinja syntax elements into the template' Text
+'\n' Text
+
+'without executing them. In that case you have quite a few possibilities.' Text
+'\n' Text
+
+'\n' Text
+
+'For small parts this might be a good way' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'"{{ foo }} is variable syntax and {% foo %} is block syntax"' Literal.String.Double
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'When you have multiple elements you can use the ' Text
+'``' Literal.String
+'raw' Literal.String
+'``' Literal.String
+' block' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'raw' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Text
+
+' ' Text
+' Filtering blocks works like this in Jinja:\n' Text
+
+' ' Text
+' {% filter escape %}\n' Text
+
+' ' Text
+' <html>\n' Text
+
+' ' Text
+' <code>goes here</code>\n' Text
+
+' ' Text
+' </html>\n' Text
+
+' ' Text
+' {% endfilter %}\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endraw' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'Reserved Keywords' Generic.Heading
+'\n' Text
+
+'=================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'Jinja has some keywords you cannot use a variable names. This limitation' Text
+'\n' Text
+
+"exists to make look coherent. Syntax highlighters won't mess things up and" Text
+'\n' Text
+
+"you will don't have unexpected output." Text
+'\n' Text
+
+'\n' Text
+
+'The following keywords exist and cannot be used as identifiers' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+' ' Text
+'`and`' Name.Variable
+', ' Text
+'`block`' Name.Variable
+', ' Text
+'`cycle`' Name.Variable
+', ' Text
+'`elif`' Name.Variable
+', ' Text
+'`else`' Name.Variable
+', ' Text
+'`endblock`' Name.Variable
+', ' Text
+'`endfilter`' Name.Variable
+',' Text
+'\n' Text
+
+' ' Text
+'`endfor`' Name.Variable
+', ' Text
+'`endif`' Name.Variable
+', ' Text
+'`endmacro`' Name.Variable
+', ' Text
+'`endraw`' Name.Variable
+', ' Text
+'`endtrans`' Name.Variable
+', ' Text
+'`extends`' Name.Variable
+', ' Text
+'`filter`' Name.Variable
+',' Text
+'\n' Text
+
+' ' Text
+'`for`' Name.Variable
+', ' Text
+'`if`' Name.Variable
+', ' Text
+'`in`' Name.Variable
+', ' Text
+'`include`' Name.Variable
+', ' Text
+'`is`' Name.Variable
+', ' Text
+'`macro`' Name.Variable
+', ' Text
+'`not`' Name.Variable
+', ' Text
+'`or`' Name.Variable
+', ' Text
+'`pluralize`' Name.Variable
+',' Text
+'\n' Text
+
+' ' Text
+'`raw`' Name.Variable
+', ' Text
+'`recursive`' Name.Variable
+', ' Text
+'`set`' Name.Variable
+', ' Text
+'`trans`' Name.Variable
+'\n' Text
+
+'\n' Text
+
+'If you want to use such a name you have to prefix or suffix it or use' Text
+'\n' Text
+
+'alternative names' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'for' Keyword
+' ' Text
+'macro_' Name.Variable
+' ' Text
+'in' Keyword
+' ' Text
+'macros' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'macro_' Name.Variable
+'(' Operator
+"'foo'" Literal.String.Single
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endfor' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'If future Jinja releases add new keywords those will be "light" keywords which' Text
+'\n' Text
+
+"means that they won't raise an error for several releases but yield warnings" Text
+'\n' Text
+
+"on the application side. But it's very unlikely that new keywords will be" Text
+'\n' Text
+
+'added.' Text
+'\n' Text
+
+'\n' Text
+
+'Internationalization' Generic.Heading
+'\n' Text
+
+'====================' Generic.Heading
+'\n' Text
+
+'\n' Text
+
+'If the application is configured for i18n, you can define translatable blocks' Text
+'\n' Text
+
+'for translators using the ' Text
+'`trans`' Name.Variable
+' tag or the special underscore function' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'trans' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' this is a translatable block\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endtrans' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'trans' Keyword
+' ' Text
+'"This is a translatable string"' Literal.String.Double
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+' ' Text
+'{{' Comment.Preproc
+' ' Text
+'_' Keyword.Pseudo
+'(' Operator
+'"This is a translatable string"' Literal.String.Double
+')' Operator
+' ' Text
+'}}' Comment.Preproc
+'\n\n' Other
+
+'The latter one is useful if you want translatable arguments for filters etc.' Text
+'\n' Text
+
+'\n' Text
+
+'If you want to have plural forms too, use the ' Text
+'`pluralize`' Name.Variable
+' block' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'trans' Keyword
+' ' Text
+'users' Name.Variable
+'=' Operator
+'users' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' One user found.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'pluralize' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'users' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' users found.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endtrans' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'trans' Keyword
+' ' Text
+'first' Name.Variable
+'=' Operator
+'(' Operator
+'users' Name.Variable
+'|' Operator
+'first' Name.Function
+')' Operator
+'.username' Name.Variable
+'|' Operator
+'escape' Name.Function
+',' Operator
+' ' Text
+'user' Name.Variable
+'=' Operator
+'users' Name.Variable
+'|' Operator
+'length' Name.Function
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' one user ' Other
+'{{' Comment.Preproc
+' ' Text
+'first' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' found.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'pluralize' Keyword
+' ' Text
+'users' Name.Variable
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'users' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' users found, the first one is called ' Other
+'{{' Comment.Preproc
+' ' Text
+'first' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+'.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endtrans' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'If you have multiple arguments, the first one is assumed to be the indicator (the' Text
+'\n' Text
+
+'number that is used to determine the correct singular or plural form. If you' Text
+'\n' Text
+
+"don't have the indicator variable on position 1 you have to tell the " Text
+'`pluralize`' Name.Variable
+'\n' Text
+
+'tag the correct variable name.' Text
+'\n' Text
+
+'\n' Text
+
+'Inside translatable blocks you cannot use blocks or expressions (however you can' Text
+'\n' Text
+
+'still use the ' Text
+'``' Literal.String
+'raw' Literal.String
+'``' Literal.String
+' block which will work as expected). The variable' Text
+'\n' Text
+
+'print syntax (' Text
+'``' Literal.String
+'{{ variablename }}' Literal.String
+'``' Literal.String
+') is the only way to insert the variables' Text
+'\n' Text
+
+'defined in the ' Text
+'``' Literal.String
+'trans' Literal.String
+'``' Literal.String
+' header. Filters must be applied in the header.' Text
+'\n' Text
+
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'admonition' Operator.Word
+'::' Punctuation
+' ' Text
+'note' Text
+'\n' Text
+
+'\n' Text
+
+' Please make sure that you always use pluralize blocks where required.' Text
+'\n' Text
+
+' Many languages have more complex plural forms than the English language.' Text
+'\n' Text
+
+' ' Text
+'\n' Text
+
+' Never try to workaround that issue by using something like this' Text
+':' Text
+'\n' Text
+
+'\n' Text
+
+' ..' Punctuation
+' ' Text
+'sourcecode' Operator.Word
+'::' Punctuation
+' ' Text
+'jinja' Keyword
+'\n\n' Text
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'if' Keyword
+' ' Text
+'count' Name.Variable
+' ' Text
+'!=' Operator
+' ' Text
+'1' Literal.Number
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' ' Other
+'{{' Comment.Preproc
+' ' Text
+'count' Name.Variable
+' ' Text
+'}}' Comment.Preproc
+' users found.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'else' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n' Other
+
+' ' Text
+' one user found.\n' Other
+
+' ' Text
+'{%' Comment.Preproc
+' ' Text
+'endif' Keyword
+' ' Text
+'%}' Comment.Preproc
+'\n\n' Other
+
+'..' Punctuation
+' ' Text
+'_slicing chapter:' Name.Tag
+' http' Text
+':' Text
+'//diveintopython.org/native_data_types/lists.html#odbchelper.list.slice' Text
+'\n' Text
+
+'..' Punctuation
+' ' Text
+'_range function:' Name.Tag
+' http' Text
+':' Text
+'//docs.python.org/tut/node6.html#SECTION006300000000000000000' Text
+'\n' Text