Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz Functional programming in Python 1st Edition David Mertz Functional programming in Python 1st Edition David Mertz
Functional programming in Python 1st Edition David Mertz
1.
Visit https://ebookultra.com todownload the full version and explore more ebooks Functional programming in Python 1st Edition David Mertz _____ Click the link below to download _____ https://ebookultra.com/download/functional-programming- in-python-1st-edition-david-mertz/ Explore and download more ebooks at ebookultra.com
2.
Here are somesuggested products you might be interested in. Click the link to download Text processing in Python 2. print Edition Mertz https://ebookultra.com/download/text-processing-in-python-2-print- edition-mertz/ Functional Programming in C First Edition Ivan Cukic https://ebookultra.com/download/functional-programming-in-c-first- edition-ivan-cukic/ Maya Programming with Python Cookbook 1st Edition Herbez https://ebookultra.com/download/maya-programming-with-python- cookbook-1st-edition-herbez/ Parallel Programming with Python First Edition Jan Palach https://ebookultra.com/download/parallel-programming-with-python- first-edition-jan-palach/
3.
Real World FunctionalProgramming With Examples in F and C 1st Edition Tomas Petricek https://ebookultra.com/download/real-world-functional-programming- with-examples-in-f-and-c-1st-edition-tomas-petricek/ Principles of Soft Computing Using Python Programming 1st Edition Gypsy Nandi https://ebookultra.com/download/principles-of-soft-computing-using- python-programming-1st-edition-gypsy-nandi/ Python Cookbook 3rd Edition David Beazley https://ebookultra.com/download/python-cookbook-3rd-edition-david- beazley/ Introduction to Computing and Programming in Python a Multimedia Approach Mark J. Guzdial https://ebookultra.com/download/introduction-to-computing-and- programming-in-python-a-multimedia-approach-mark-j-guzdial/ Elements of Programming Interviews in Python 1st Edition Adnan Aziz & Amit Prakash & Tsung-Hsien Lee https://ebookultra.com/download/elements-of-programming-interviews-in- python-1st-edition-adnan-aziz-amit-prakash-tsung-hsien-lee/
5.
Functional programming inPython 1st Edition David Mertz Digital Instant Download Author(s): David Mertz ISBN(s): 9781491928561, 1491928565 Edition: 1 File Details: PDF, 1.56 MB Year: 2015 Language: english
Preface What Is FunctionalProgramming? We’d better start with the hardest question: “What is functional pro‐ gramming (FP), anyway?” One answer would be to say that functional programming is what you do when you program in languages like Lisp, Scheme, Clojure, Scala, Haskell, ML, OCAML, Erlang, or a few others. That is a safe answer, but not one that clarifies very much. Unfortunately, it is hard to get a consistent opinion on just what functional program‐ ming is, even from functional programmers themselves. A story about elephants and blind men seems apropos here. It is also safe to contrast functional programming with “imperative programming” (what you do in languages like C, Pascal, C++, Java, Perl, Awk, TCL, and most others, at least for the most part). Functional program‐ ming is also not object-oriented programming (OOP), although some languages are both. And it is not Logic Programming (e.g., Prolog), but again some languages are multiparadigm. Personally, I would roughly characterize functional programming as having at least several of the following characteristics. Languages that get called functional make these things easy, and make other things either hard or impossible: • Functions are first class (objects). That is, everything you can do with “data” can be done with functions themselves (such as passing a function to another function). • Recursion is used as a primary control structure. In some lan‐ guages, no other “loop” construct exists. v
13.
• There isa focus on list processing (for example, it is the source of the name Lisp). Lists are often used with recursion on sublists as a substitute for loops. • “Pure” functional languages eschew side effects. This excludes the almost ubiquitous pattern in imperative languages of assign‐ ing first one, then another value to the same variable to track the program state. • Functional programming either discourages or outright disal‐ lows statements, and instead works with the evaluation of expressions (in other words, functions plus arguments). In the pure case, one program is one expression (plus supporting defi‐ nitions). • Functional programming worries about what is to be computed rather than how it is to be computed. • Much functional programming utilizes “higher order” functions (in other words, functions that operate on functions that oper‐ ate on functions). Advocates of functional programming argue that all these character‐ istics make for more rapidly developed, shorter, and less bug-prone code. Moreover, high theorists of computer science, logic, and math find it a lot easier to prove formal properties of functional languages and programs than of imperative languages and programs. One cru‐ cial concept in functional programming is that of a “pure function”—one that always returns the same result given the same arguments—which is more closely akin to the meaning of “function” in mathematics than that in imperative programming. Python is most definitely not a “pure functional programming lan‐ guage”; side effects are widespread in most Python programs. That is, variables are frequently rebound, mutable data collections often change contents, and I/O is freely interleaved with computation. It is also not even a “functional programming language” more generally. However, Python is a multiparadigm language that makes functional programming easy to do when desired, and easy to mix with other programming styles. Beyond the Standard Library While they will not be discussed withing the limited space of this report, a large number of useful third-party Python libraries for vi | Preface
14.
functional programming areavailable. The one exception here is that I will discuss Matthew Rocklin’s multipledispatch as the best current implementation of the concept it implements. Most third-party libraries around functional programming are col‐ lections of higher-order functions, and sometimes enhancements to the tools for working lazily with iterators contained in itertools. Some notable examples include the following, but this list should not be taken as exhaustive: • pyrsistent contains a number of immutable collections. All methods on a data structure that would normally mutate it instead return a new copy of the structure containing the requested updates. The original structure is left untouched. • toolz provides a set of utility functions for iterators, functions, and dictionaries. These functions interoperate well and form the building blocks of common data analytic operations. They extend the standard libraries itertools and functools and borrow heavily from the standard libraries of contemporary functional languages. • hypothesis is a library for creating unit tests for finding edge cases in your code you wouldn’t have thought to look for. It works by generating random data matching your specification and checking that your guarantee still holds in that case. This is often called property-based testing, and was popularized by the Haskell library QuickCheck. • more_itertools tries to collect useful compositions of iterators that neither itertools nor the recipes included in its docs address. These compositions are deceptively tricky to get right and this well-crafted library helps users avoid pitfalls of rolling them themselves. Resources There are a large number of other papers, articles, and books written about functional programming, in Python and otherwise. The Python standard documentation itself contains an excellent intro‐ duction called “Functional Programming HOWTO,” by Andrew Kuchling, that discusses some of the motivation for functional pro‐ gramming styles, as well as particular capabilities in Python. Preface | vii
15.
Mentioned in Kuchling’sintroduction are several very old public domain articles this author wrote in the 2000s, on which portions of this report are based. These include: • The first chapter of my book Text Processing in Python, which discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Pro‐ cessing.” I also wrote several articles, mentioned by Kuchling, for IBM’s devel‐ operWorks site that discussed using functional programming in an early version of Python 2.x: • Charming Python: Functional programming in Python, Part 1: Making more out of your favorite scripting language • Charming Python: Functional programming in Python, Part 2: Wading into functional programming? • Charming Python: Functional programming in Python, Part 3: Currying and other higher-order functions Not mentioned by Kuchling, and also for an older version of Python, I discussed multiple dispatch in another article for the same column. The implementation I created there has no advantages over the more recent multipledispatch library, but it provides a longer conceptual explanation than this report can: • Charming Python: Multiple dispatch: Generalizing polymor‐ phism with multimethods A Stylistic Note As in most programming texts, a fixed font will be used both for inline and block samples of code, including simple command or function names. Within code blocks, a notional segment of pseudo- code is indicated with a word surrounded by angle brackets (i.e., not valid Python), such as <code-block>. In other cases, syntactically valid but undefined functions are used with descriptive names, such as get_the_data(). viii | Preface
16.
(Avoiding) Flow Control Intypical imperative Python programs—including those that make use of classes and methods to hold their imperative code—a block of code generally consists of some outside loops (for or while), assign‐ ment of state variables within those loops, modification of data structures like dicts, lists, and sets (or various other structures, either from the standard library or from third-party packages), and some branch statements (if/elif/else or try/except/finally). All of this is both natural and seems at first easy to reason about. The problems often arise, however, precisely with those side effects that come with state variables and mutable data structures; they often model our concepts from the physical world of containers fairly well, but it is also difficult to reason accurately about what state data is in at a given point in a program. One solution is to focus not on constructing a data collection but rather on describing “what” that data collection consists of. When one simply thinks, “Here’s some data, what do I need to do with it?” rather than the mechanism of constructing the data, more direct reasoning is often possible. The imperative flow control described in the last paragraph is much more about the “how” than the “what” and we can often shift the question. Encapsulation One obvious way of focusing more on “what” than “how” is simply to refactor code, and to put the data construction in a more isolated place—i.e., in a function or method. For example, consider an exist‐ ing snippet of imperative code that looks like this: 1
17.
# configure thedata to start with collection = get_initial_state() state_var = None for datum in data_set: if condition(state_var): state_var = calculate_from(datum) new = modify(datum, state_var) collection.add_to(new) else: new = modify_differently(datum) collection.add_to(new) # Now actually work with the data for thing in collection: process(thing) We might simply remove the “how” of the data construction from the current scope, and tuck it away in a function that we can think about in isolation (or not think about at all once it is sufficiently abstracted). For example: # tuck away construction of data def make_collection(data_set): collection = get_initial_state() state_var = None for datum in data_set: if condition(state_var): state_var = calculate_from(datum, state_var) new = modify(datum, state_var) collection.add_to(new) else: new = modify_differently(datum) collection.add_to(new) return collection # Now actually work with the data for thing in make_collection(data_set): process(thing) We haven’t changed the programming logic, nor even the lines of code, at all, but we have still shifted the focus from “How do we con‐ struct collection?” to “What does make_collection() create?” Comprehensions Using comprehensions is often a way both to make code more com‐ pact and to shift our focus from the “how” to the “what.” A compre‐ hension is an expression that uses the same keywords as loop and conditional blocks, but inverts their order to focus on the data 2 | (Avoiding) Flow Control
18.
rather than onthe procedure. Simply changing the form of expres‐ sion can often make a surprisingly large difference in how we reason about code and how easy it is to understand. The ternary operator also performs a similar restructuring of our focus, using the same keywords in a different order. For example, if our original code was: collection = list() for datum in data_set: if condition(datum): collection.append(datum) else: new = modify(datum) collection.append(new) Somewhat more compactly we could write this as: collection = [d if condition(d) else modify(d) for d in data_set] Far more important than simply saving a few characters and lines is the mental shift enacted by thinking of what collection is, and by avoiding needing to think about or debug “What is the state of col lection at this point in the loop?” List comprehensions have been in Python the longest, and are in some ways the simplest. We now also have generator comprehen‐ sions, set comprehensions, and dict comprehensions available in Python syntax. As a caveat though, while you can nest comprehen‐ sions to arbitrary depth, past a fairly simple level they tend to stop clarifying and start obscuring. For genuinely complex construction of a data collection, refactoring into functions remains more reada‐ ble. Generators Generator comprehensions have the same syntax as list comprehen‐ sions—other than that there are no square brackets around them (but parentheses are needed syntactically in some contexts, in place of brackets)—but they are also lazy. That is to say that they are merely a description of “how to get the data” that is not realized until one explicitly asks for it, either by calling .next() on the object, or by looping over it. This often saves memory for large sequences and defers computation until it is actually needed. For example: log_lines = (line for line in read_line(huge_log_file) if complex_condition(line)) Comprehensions | 3
19.
For typical uses,the behavior is the same as if you had constructed a list, but runtime behavior is nicer. Obviously, this generator compre‐ hension also has imperative versions, for example: def get_log_lines(log_file): line = read_line(log_file) while True: try: if complex_condition(line): yield line line = read_line(log_file) except StopIteration: raise log_lines = get_log_lines(huge_log_file) Yes, the imperative version could be simplified too, but the version shown is meant to illustrate the behind-the-scenes “how” of a for loop over an iteratable—more details we also want to abstract from in our thinking. In fact, even using yield is somewhat of an abstrac‐ tion from the underlying “iterator protocol.” We could do this with a class that had .__next__() and .__iter__() methods. For example: class GetLogLines(object): def __init__(self, log_file): self.log_file = log_file self.line = None def __iter__(self): return self def __next__(self): if self.line is None: self.line = read_line(log_file) while not complex_condition(self.line): self.line = read_line(self.log_file) return self.line log_lines = GetLogLines(huge_log_file) Aside from the digression into the iterator protocol and laziness more generally, the reader should see that the comprehension focu‐ ses attention much better on the “what,” whereas the imperative ver‐ sion—although successful as refactorings perhaps—retains the focus on the “how.” Dicts and Sets In the same fashion that lists can be created in comprehensions rather than by creating an empty list, looping, and repeatedly call‐ 4 | (Avoiding) Flow Control
20.
ing .append(), dictionariesand sets can be created “all at once” rather than by repeatedly calling .update() or .add() in a loop. For example: >>> {i:chr(65+i) for i in range(6)} {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'} >>> {chr(65+i) for i in range(6)} {'A', 'B', 'C', 'D', 'E', 'F'} The imperative versions of these comprehensions would look very similar to the examples shown earlier for other built-in datatypes. Recursion Functional programmers often put weight in expressing flow con‐ trol through recursion rather than through loops. Done this way, we can avoid altering the state of any variables or data structures within an algorithm, and more importantly get more at the “what” than the “how” of a computation. However, in considering using recursive styles we should distinguish between the cases where recursion is just “iteration by another name” and those where a problem can readily be partitioned into smaller problems, each approached in a similar way. There are two reasons why we should make the distinction men‐ tioned. On the one hand, using recursion effectively as a way of marching through a sequence of elements is, while possible, really not “Pythonic.” It matches the style of other languages like Lisp, def‐ initely, but it often feels contrived in Python. On the other hand, Python is simply comparatively slow at recursion, and has a limited stack depth limit. Yes, you can change this with sys.setrecursion limit() to more than the default 1000; but if you find yourself doing so it is probably a mistake. Python lacks an internal feature called tail call elimination that makes deep recursion computation‐ ally efficient in some languages. Let us find a trivial example where recursion is really just a kind of iteration: def running_sum(numbers, start=0): if len(numbers) == 0: print() return total = numbers[0] + start print(total, end=" ") running_sum(numbers[1:], total) Recursion | 5
21.
There is littleto recommend this approach, however; an iteration that simply repeatedly modified the total state variable would be more readable, and moreover this function is perfectly reasonable to want to call against sequences of much larger length than 1000. However, in other cases, recursive style, even over sequential opera‐ tions, still expresses algorithms more intuitively and in a way that is easier to reason about. A slightly less trivial example, factorial in recursive and iterative style: def factorialR(N): "Recursive factorial function" assert isinstance(N, int) and N >= 1 return 1 if N <= 1 else N * factorialR(N-1) def factorialI(N): "Iterative factorial function" assert isinstance(N, int) and N >= 1 product = 1 while N >= 1: product *= N N -= 1 return product Although this algorithm can also be expressed easily enough with a running product variable, the recursive expression still comes closer to the “what” than the “how” of the algorithm. The details of repeat‐ edly changing the values of product and N in the iterative version feels like it’s just bookkeeping, not the nature of the computation itself (but the iterative version is probably faster, and it is easy to reach the recursion limit if it is not adjusted). As a footnote, the fastest version I know of for factorial() in Python is in a functional programming style, and also expresses the “what” of the algorithm well once some higher-order functions are familiar: from functools import reduce from operator import mul def factorialHOF(n): return reduce(mul, range(1, n+1), 1) Where recursion is compelling, and sometimes even the only really obvious way to express a solution, is when a problem offers itself to a “divide and conquer” approach. That is, if we can do a similar computation on two halves (or anyway, several similarly sized chunks) of a larger collection. In that case, the recursion depth is only O(log N) of the size of the collection, which is unlikely to be 6 | (Avoiding) Flow Control
22.
overly deep. Forexample, the quicksort algorithm is very elegantly expressed without any state variables or loops, but wholly through recursion: def quicksort(lst): "Quicksort over a list-like sequence" if len(lst) == 0: return lst pivot = lst[0] pivots = [x for x in lst if x == pivot] small = quicksort([x for x in lst if x < pivot]) large = quicksort([x for x in lst if x > pivot]) return small + pivots + large Some names are used in the function body to hold convenient val‐ ues, but they are never mutated. It would not be as readable, but the definition could be written as a single expression if we wanted to do so. In fact, it is somewhat difficult, and certainly less intuitive, to transform this into a stateful iterative version. As general advice, it is good practice to look for possibilities of recursive expression—and especially for versions that avoid the need for state variables or mutable data collections—whenever a problem looks partitionable into smaller problems. It is not a good idea in Python—most of the time—to use recursion merely for “iter‐ ation by other means.” Eliminating Loops Just for fun, let us take a quick look at how we could take out all loops from any Python program. Most of the time this is a bad idea, both for readability and performance, but it is worth looking at how simple it is to do in a systematic fashion as background to contem‐ plate those cases where it is actually a good idea. If we simply call a function inside a for loop, the built-in higher- order function map() comes to our aid: for e in it: # statement-based loop func(e) The following code is entirely equivalent to the functional version, except there is no repeated rebinding of the variable e involved, and hence no state: map(func, it) # map()-based "loop" Eliminating Loops | 7
23.
A similar techniqueis available for a functional approach to sequen‐ tial program flow. Most imperative programming consists of state‐ ments that amount to “do this, then do that, then do the other thing.” If those individual actions are wrapped in functions, map() lets us do just this: # let f1, f2, f3 (etc) be functions that perform actions # an execution utility function do_it = lambda f, *args: f(*args) # map()-based action sequence map(do_it, [f1, f2, f3]) We can combine the sequencing of function calls with passing argu‐ ments from iterables: >>> hello = lambda first, last: print("Hello", first, last) >>> bye = lambda first, last: print("Bye", first, last) >>> _ = list(map(do_it, [hello, bye], >>> ['David','Jane'], ['Mertz','Doe'])) Hello David Mertz Bye Jane Doe Of course, looking at the example, one suspects the result one really wants is actually to pass all the arguments to each of the functions rather than one argument from each list to each function. Express‐ ing that is difficult without using a list comprehension, but easy enough using one: >>> do_all_funcs = lambda fns, *args: [ list(map(fn, *args)) for fn in fns] >>> _ = do_all_funcs([hello, bye], ['David','Jane'], ['Mertz','Doe']) Hello David Mertz Hello Jane Doe Bye David Mertz Bye Jane Doe In general, the whole of our main program could, in principle, be a map() expression with an iterable of functions to execute to com‐ plete the program. Translating while is slightly more complicated, but is possible to do directly using recursion: # statement-based while loop while <cond>: <pre-suite> if <break_condition>: break else: 8 | (Avoiding) Flow Control
24.
<suite> # FP-style recursivewhile loop def while_block(): <pre-suite> if <break_condition>: return 1 else: <suite> return 0 while_FP = lambda: (<cond> and while_block()) or while_FP() while_FP() Our translation of while still requires a while_block() function that may itself contain statements rather than just expressions. We could go further in turning suites into function sequences, using map() as above. If we did this, we could, moreover, also return a sin‐ gle ternary expression. The details of this further purely functional refactoring is left to readers as an exercise (hint: it will be ugly; fun to play with, but not good production code). It is hard for <cond> to be useful with the usual tests, such as while myvar==7, since the loop body (by design) cannot change any vari‐ able values. One way to add a more useful condition is to let while_block() return a more interesting value, and compare that return value for a termination condition. Here is a concrete example of eliminating statements: # imperative version of "echo()" def echo_IMP(): while 1: x = input("IMP -- ") if x == 'quit': break else: print(x) echo_IMP() Now let’s remove the while loop for the functional version: # FP version of "echo()" def identity_print(x): # "identity with side-effect" print(x) return x echo_FP = lambda: identity_print(input("FP -- "))=='quit' or echo_FP() echo_FP() Eliminating Loops | 9
25.
What we haveaccomplished is that we have managed to express a little program that involves I/O, looping, and conditional statements as a pure expression with recursion (in fact, as a function object that can be passed elsewhere if desired). We do still utilize the utility function identity_print(), but this function is completely general, and can be reused in every functional program expression we might create later (it’s a one-time cost). Notice that any expression contain‐ ing identity_print(x) evaluates to the same thing as if it had sim‐ ply contained x; it is only called for its I/O side effect. Eliminating Recursion As with the simple factorial example given above, sometimes we can perform “recursion without recursion” by using func tools.reduce() or other folding operations (other “folds” are not in the Python standard library, but can easily be constructed and/or occur in third-party libraries). A recursion is often simply a way of combining something simpler with an accumulated intermediate result, and that is exactly what reduce() does at heart. A slightly longer discussion of functools.reduce() occurs in the chapter on higher-order functions. 10 | (Avoiding) Flow Control
26.
Callables The emphasis infunctional programming is, somewhat tautolo‐ gously, on calling functions. Python actually gives us several differ‐ ent ways to create functions, or at least something very function-like (i.e., that can be called). They are: • Regular functions created with def and given a name at defini‐ tion time • Anonymous functions created with lambda • Instances of classes that define a __call()__ method • Closures returned by function factories • Static methods of instances, either via the @staticmethod deco‐ rator or via the class __dict__ • Generator functions This list is probably not exhaustive, but it gives a sense of the numerous slightly different ways one can create something callable. Of course, a plain method of a class instance is also a callable, but one generally uses those where the emphasis is on accessing and modifying mutable state. Python is a multiple paradigm language, but it has an emphasis on object-oriented styles. When one defines a class, it is generally to generate instances meant as containers for data that change as one calls methods of the class. This style is in some ways opposite to a functional programming approach, which emphasizes immutability and pure functions. 11
27.
Any method thataccesses the state of an instance (in any degree) to determine what result to return is not a pure function. Of course, all the other types of callables we discuss also allow reliance on state in various ways. The author of this report has long pondered whether he could use some dark magic within Python explicitly to declare a function as pure—say by decorating it with a hypothetical @purefunction decorator that would raise an exception if the func‐ tion can have side effects—but consensus seems to be that it would be impossible to guard against every edge case in Python’s internal machinery. The advantage of a pure function and side-effect-free code is that it is generally easier to debug and test. Callables that freely intersperse statefulness with their returned results cannot be examined inde‐ pendently of their running context to see how they behave, at least not entirely so. For example, a unit test (using doctest or unittest, or some third-party testing framework such as py.test or nose) might succeed in one context but fail when identical calls are made within a running, stateful program. Of course, at the very least, any program that does anything must have some kind of output (whether to console, a file, a database, over the network, or what‐ ever) in it to do anything useful, so side effects cannot be entirely eliminated, only isolated to a degree when thinking in functional programming terms. Named Functions and Lambdas The most obvious ways to create callables in Python are, in definite order of obviousness, named functions and lambdas. The only in- principle difference between them is simply whether they have a .__qualname__ attribute, since both can very well be bound to one or more names. In most cases, lambda expressions are used within Python only for callbacks and other uses where a simple action is inlined into a function call. But as we have shown in this report, flow control in general can be incorporated into single-expression lamb‐ das if we really want. Let’s define a simple example to illustrate: >>> def hello1(name): ..... print("Hello", name) ..... >>> hello2 = lambda name: print("Hello", name) >>> hello1('David') Hello David 12 | Callables
28.
>>> hello2('David') Hello David >>>hello1.__qualname__ 'hello1' >>> hello2.__qualname__ '<lambda>' >>> hello3 = hello2 # can bind func to other names >>> hello3.__qualname__ '<lambda>' >>> hello3.__qualname__ = 'hello3' >>> hello3.__qualname__ 'hello3' One of the reasons that functions are useful is that they isolate state lexically, and avoid contamination of enclosing namespaces. This is a limited form of nonmutability in that (by default) nothing you do within a function will bind state variables outside the function. Of course, this guarantee is very limited in that both the global and nonlocal statements explicitly allow state to “leak out” of a function. Moreover, many data types are themselves mutable, so if they are passed into a function that function might change their contents. Furthermore, doing I/O can also change the “state of the world” and hence alter results of functions (e.g., by changing the contents of a file or a database that is itself read elsewhere). Notwithstanding all the caveats and limits mentioned above, a pro‐ grammer who wants to focus on a functional programming style can intentionally decide to write many functions as pure functions to allow mathematical and formal reasoning about them. In most cases, one only leaks state intentionally, and creating a certain subset of all your functionality as pure functions allows for cleaner code. They might perhaps be broken up by “pure” modules, or annotated in the function names or docstrings. Closures and Callable Instances There is a saying in computer science that a class is “data with opera‐ tions attached” while a closure is “operations with data attached.” In some sense they accomplish much the same thing of putting logic and data in the same object. But there is definitely a philosophical difference in the approaches, with classes emphasizing mutable or rebindable state, and closures emphasizing immutability and pure functions. Neither side of this divide is absolute—at least in Python —but different attitudes motivate the use of each. Closures and Callable Instances | 13
29.
Let us constructa toy example that shows this, something just past a “hello world” of the different styles: # A class that creates callable adder instances class Adder(object): def __init__(self, n): self.n = n def __call__(self, m): return self.n + m add5_i = Adder(5) # "instance" or "imperative" We have constructed something callable that adds five to an argu‐ ment passed in. Seems simple and mathematical enough. Let us also try it as a closure: def make_adder(n): def adder(m): return m + n return adder add5_f = make_adder(5) # "functional" So far these seem to amount to pretty much the same thing, but the mutable state in the instance provides a attractive nuisance: >>> add5_i(10) 15 >>> add5_f(10) # only argument affects result 15 >>> add5_i.n = 10 # state is readily changeable >>> add5_i(10) # result is dependent on prior flow 20 The behavior of an “adder” created by either Adder() or make_adder() is, of course, not determined until runtime in general. But once the object exists, the closure behaves in a pure functional way, while the class instance remains state dependent. One might simply settle for “don’t change that state”—and indeed that is possi‐ ble (if no one else with poorer understanding imports and uses your code)—but one is accustomed to changing the state of instances, and a style that prevents abuse programmatically encourages better habits. There is a little “gotcha” about how Python binds variables in clo‐ sures. It does so by name rather than value, and that can cause con‐ fusion, but also has an easy solution. For example, what if we want to manufacture several related closures encapsulating different data: 14 | Callables
30.
# almost surelynot the behavior we intended! >>> adders = [] >>> for n in range(5): adders.append(lambda m: m+n) >>> [adder(10) for adder in adders] [14, 14, 14, 14, 14] >>> n = 10 >>> [adder(10) for adder in adders] [20, 20, 20, 20, 20] Fortunately, a small change brings behavior that probably better meets our goal: >>> adders = [] >>> for n in range(5): .... adders.append(lambda m, n=n: m+n) .... >>> [adder(10) for adder in adders] [10, 11, 12, 13, 14] >>> n = 10 >>> [adder(10) for adder in adders] [10, 11, 12, 13, 14] >>> add4 = adders[4] >>> add4(10, 100) # Can override the bound value 110 Notice that using the keyword argument scope-binding trick allows you to change the closed-over value; but this poses much less of a danger for confusion than in the class instance. The overriding value for the named variable must be passed explictly in the call itself, not rebound somewhere remote in the program flow. Yes, the name add4 is no longer accurately descriptive for “add any two numbers,” but at least the change in result is syntactically local. Methods of Classes All methods of classes are callables. For the most part, however, call‐ ing a method of an instance goes against the grain of functional pro‐ gramming styles. Usually we use methods because we want to refer‐ ence mutable data that is bundled in the attributes of the instance, and hence each call to a method may produce a different result that varies independently of the arguments passed to it. Accessors and Operators Even accessors, whether created with the @property decorator or otherwise, are technically callables, albeit accessors are callables with Methods of Classes | 15
31.
a limited use(from a functional programming perspective) in that they take no arguments as getters, and return no value as setters: class Car(object): def __init__(self): self._speed = 100 @property def speed(self): print("Speed is", self._speed) return self._speed @speed.setter def speed(self, value): print("Setting to", value) self._speed = value # >> car = Car() # >>> car.speed = 80 # Odd syntax to pass one argument # Setting to 80 # >>> x = car.speed # Speed is 80 In an accessor, we co-opt the Python syntax of assignment to pass an argument instead. That in itself is fairly easy for much Python syn‐ tax though, for example: >>> class TalkativeInt(int): def __lshift__(self, other): print("Shift", self, "by", other) return int.__lshift__(self, other) .... >>> t = TalkativeInt(8) >>> t << 3 Shift 8 by 3 64 Every operator in Python is basically a method call “under the hood.” But while occasionally producing a more readable “domain specific language” (DSL), defining special callable meanings for operators adds no improvement to the underlying capabilities of function calls. Static Methods of Instances One use of classes and their methods that is more closely aligned with a functional style of programming is to use them simply as namespaces to hold a variety of related functions: 16 | Callables
32.
import math class RightTriangle(object): "Classused solely as namespace for related functions" @staticmethod def hypotenuse(a, b): return math.sqrt(a**2 + b**2) @staticmethod def sin(a, b): return a / RightTriangle.hypotenuse(a, b) @staticmethod def cos(a, b): return b / RightTriangle.hypotenuse(a, b) Keeping this functionality in a class avoids polluting the global (or module, etc.) namespace, and lets us name either the class or an instance of it when we make calls to pure functions. For example: >>> RightTriangle.hypotenuse(3,4) 5.0 >>> rt = RightTriangle() >>> rt.sin(3,4) 0.6 >>> rt.cos(3,4) 0.8 By far the most straightforward way to define static methods is with the decorator named in the obvious way. However, in Python 3.x, you can pull out functions that have not been so decorated too—i.e., the concept of an “unbound method” is no longer needed in modern Python versions: >>> import functools, operator >>> class Math(object): ... def product(*nums): ... return functools.reduce(operator.mul, nums) ... def power_chain(*nums): ... return functools.reduce(operator.pow, nums) ... >>> Math.product(3,4,5) 60 >>> Math.power_chain(3,4,5) 3486784401 Without @staticmethod, however, this will not work on the instan‐ ces since they still expect to be passed self: >>> m = Math() >>> m.product(3,4,5) ----------------------------------------------------------------- Methods of Classes | 17
33.
TypeError Traceback (most recentcall last) <ipython-input-5-e1de62cf88af> in <module>() ----> 1 m.product(3,4,5) <ipython-input-2-535194f57a64> in product(*nums) 2 class Math(object): 3 def product(*nums): ----> 4 return functools.reduce(operator.mul, nums) 5 def power_chain(*nums): 6 return functools.reduce(operator.pow, nums) TypeError: unsupported operand type(s) for *: 'Math' and 'int' If your namespace is entirely a bag for pure functions, there is no reason not to call via the class rather than the instance. But if you wish to mix some pure functions with some other stateful methods that rely on instance mutable state, you should use the @staticme thod decorator. Generator Functions A special sort of function in Python is one that contains a yield statement, which turns it into a generator. What is returned from calling such a function is not a regular value, but rather an iterator that produces a sequence of values as you call the next() function on it or loop over it. This is discussed in more detail in the chapter entitled “Lazy Evaluation.” While like any Python object, there are many ways to introduce statefulness into a generator, in principle a generator can be “pure” in the sense of a pure function. It is merely a pure function that pro‐ duces a (potentially infinite) sequence of values rather than a single value, but still based only on the arguments passed into it. Notice, however, that generator functions typically have a great deal of inter‐ nal state; it is at the boundaries of call signature and return value that they act like a side-effect-free “black box.” A simple example: >>> def get_primes(): ... "Simple lazy Sieve of Eratosthenes" ... candidate = 2 ... found = [] ... while True: ... if all(candidate % prime != 0 for prime in found): ... yield candidate ... found.append(candidate) ... candidate += 1 18 | Callables
34.
... >>> primes =get_primes() >>> next(primes), next(primes), next(primes) (2, 3, 5) >>> for _, prime in zip(range(10), primes): ... print(prime, end=" ") .... 7 11 13 17 19 23 29 31 37 41 Every time you create a new object with get_primes() the iterator is the same infinite lazy sequence—another example might pass in some initializing values that affected the result—but the object itself is stateful as it is consumed incrementally. Multiple Dispatch A very interesting approach to programming multiple paths of exe‐ cution is a technique called “multiple dispatch” or sometimes “mul‐ timethods.” The idea here is to declare multiple signatures for a sin‐ gle function and call the actual computation that matches the types or properties of the calling arguments. This technique often allows one to avoid or reduce the use of explicitly conditional branching, and instead substitute the use of more intuitive pattern descriptions of arguments. A long time ago, this author wrote a module called multimethods that was quite flexible in its options for resolving “dispatch lineariza‐ tion” but is also so old as only to work with Python 2.x, and was even written before Python had decorators for more elegant expres‐ sion of the concept. Matthew Rocklin’s more recent multipledis patch is a modern approach for recent Python versions, albeit it lacks some of the theoretical arcana I explored in my ancient mod‐ ule. Ideally, in this author’s opinion, a future Python version would include a standardized syntax or API for multiple dispatch (but more likely the task will always be the domain of third-party libra‐ ries). To explain how multiple dispatch can make more readable and less bug-prone code, let us implement the game of rock/paper/scissors in three styles. Let us create the classes to play the game for all the ver‐ sions: class Thing(object): pass class Rock(Thing): pass Multiple Dispatch | 19
35.
class Paper(Thing): pass classScissors(Thing): pass Many Branches First a purely imperative version. This is going to have a lot of repet‐ itive, nested, conditional blocks that are easy to get wrong: def beats(x, y): if isinstance(x, Rock): if isinstance(y, Rock): return None # No winner elif isinstance(y, Paper): return y elif isinstance(y, Scissors): return x else: raise TypeError("Unknown second thing") elif isinstance(x, Paper): if isinstance(y, Rock): return x elif isinstance(y, Paper): return None # No winner elif isinstance(y, Scissors): return y else: raise TypeError("Unknown second thing") elif isinstance(x, Scissors): if isinstance(y, Rock): return y elif isinstance(y, Paper): return x elif isinstance(y, Scissors): return None # No winner else: raise TypeError("Unknown second thing") else: raise TypeError("Unknown first thing") rock, paper, scissors = Rock(), Paper(), Scissors() # >>> beats(paper, rock) # <__main__.Paper at 0x103b96b00> # >>> beats(paper, 3) # TypeError: Unknown second thing Delegating to the Object As a second try we might try to eliminate some of the fragile repiti‐ tion with Python’s “duck typing”—that is, maybe we can have differ‐ ent things share a common method that is called as needed: 20 | Callables
36.
class DuckRock(Rock): def beats(self,other): if isinstance(other, Rock): return None # No winner elif isinstance(other, Paper): return other elif isinstance(other, Scissors): return self else: raise TypeError("Unknown second thing") class DuckPaper(Paper): def beats(self, other): if isinstance(other, Rock): return self elif isinstance(other, Paper): return None # No winner elif isinstance(other, Scissors): return other else: raise TypeError("Unknown second thing") class DuckScissors(Scissors): def beats(self, other): if isinstance(other, Rock): return other elif isinstance(other, Paper): return self elif isinstance(other, Scissors): return None # No winner else: raise TypeError("Unknown second thing") def beats2(x, y): if hasattr(x, 'beats'): return x.beats(y) else: raise TypeError("Unknown first thing") rock, paper, scissors = DuckRock(), DuckPaper(), DuckScissors() # >>> beats2(rock, paper) # <__main__.DuckPaper at 0x103b894a8> # >>> beats2(3, rock) # TypeError: Unknown first thing We haven’t actually reduced the amount of code, but this version somewhat reduces the complexity within each individual callable, and reduces the level of nested conditionals by one. Most of the logic is pushed into separate classes rather than deep branching. In Multiple Dispatch | 21
37.
object-oriented programming wecan “delgate dispatch to the object” (but only to the one controlling object). Pattern Matching As a final try, we can express all the logic more directly using multi‐ ple dispatch. This should be more readable, albeit there are still a number of cases to define: from multipledispatch import dispatch @dispatch(Rock, Rock) def beats3(x, y): return None @dispatch(Rock, Paper) def beats3(x, y): return y @dispatch(Rock, Scissors) def beats3(x, y): return x @dispatch(Paper, Rock) def beats3(x, y): return x @dispatch(Paper, Paper) def beats3(x, y): return None @dispatch(Paper, Scissors) def beats3(x, y): return x @dispatch(Scissors, Rock) def beats3(x, y): return y @dispatch(Scissors, Paper) def beats3(x, y): return x @dispatch(Scissors, Scissors) def beats3(x, y): return None @dispatch(object, object) def beats3(x, y): if not isinstance(x, (Rock, Paper, Scissors)): raise TypeError("Unknown first thing") else: raise TypeError("Unknown second thing") # >>> beats3(rock, paper) # <__main__.DuckPaper at 0x103b894a8> # >>> beats3(rock, 3) # TypeError: Unknown second thing 22 | Callables
38.
Predicate-Based Dispatch A reallyexotic approach to expressing conditionals as dispatch deci‐ sions is to include predicates directly within the function signatures (or perhaps within decorators on them, as with multipledispatch). I do not know of any well-maintained Python library that does this, but let us simply stipulate a hypothetical library briefly to illustrate the concept. This imaginary library might be aptly named predicative_dispatch: from predicative_dispatch import predicate @predicate(lambda x: x < 0, lambda y: True) def sign(x, y): print("x is negative; y is", y) @predicate(lambda x: x == 0, lambda y: True) def sign(x, y): print("x is zero; y is", y) @predicate(lambda x: x > 0, lambda y: True) def sign(x, y): print("x is positive; y is", y) While this small example is obviously not a full specification, the reader can see how we might move much or all of the conditional branching into the function call signatures themselves, and this might result in smaller, more easily understood and debugged func‐ tions. Multiple Dispatch | 23
40.
Lazy Evaluation A powerfulfeature of Python is its iterator protocol (which we will get to shortly). This capability is only loosely connected to func‐ tional programming per se, since Python does not quite offer lazy data structures in the sense of a language like Haskell. However, use of the iterator protocol—and Python’s many built-in or standard library iteratables—accomplish much the same effect as an actual lazy data structure. Let us explain the contrast here in slightly more detail. In a language like Haskell, which is inherently lazily evaluated, we might define a list of all the prime numbers in a manner like the following: -- Define a list of ALL the prime numbers primes = sieve [2 ..] where sieve (p:xs) = p : sieve [x | x <- xs, (x `rem` p)/=0] This report is not the place to try to teach Haskell, but you can see a comprehension in there, which is in fact the model that Python used in introducing its own comprehensions. There is also deep recursion involved, which is not going to work in Python. Apart from syntactic differences, or even the ability to recurse to indefinite depth, the significant difference here is that the Haskell version of primes is an actual (infinite) sequence, not just an object capable of sequentially producing elements (as was the primes object we demonstrated in the chapter entitled “Callables”). In par‐ ticular, you can index into an arbitrary element of the infinite list of primes in Haskell, and the intermediate values will be produced internally as needed based on the syntactic construction of the list itself. 25
41.
Mind you, onecan replicate this in Python too, it just isn’t in the inherent syntax of the language and takes more manual construc‐ tion. Given the get_primes() generator function discussed earlier, we might write our own container to simulate the same thing, for example: from collections.abc import Sequence class ExpandingSequence(Sequence): def __init__(self, it): self.it = it self._cache = [] def __getitem__(self, index): while len(self._cache) <= index: self._cache.append(next(self.it)) return self._cache[index] def __len__(self): return len(self._cache) This new container can be both lazy and also indexible: >>> primes = ExpandingSequence(get_primes()) >>> for _, p in zip(range(10), primes): .... print(p, end=" ") .... 2 3 5 7 11 13 17 19 23 29 >>> primes[10] 31 >>> primes[5] 13 >>> len(primes) 11 >>> primes[100] 547 >>> len(primes) 101 Of course, there are other custom capabilities we might want to engineer in, since lazy data structures are not inherently intertwined into Python. Maybe we’d like to be able to slice this special sequence. Maybe we’d like a prettier representation of the object when printed. Maybe we should report the length as inf if we somehow signaled it was meant to be infinite. All of this is possible, but it takes a little bit of code to add each behavior rather than simply being the default assumption of Python data structures. 26 | Lazy Evaluation
42.
The Iterator Protocol Theeasiest way to create an iterator—that is to say, a lazy sequence —in Python is to define a generator function, as was discussed in the chapter entitled “Callables.” Simply use the yield statement within the body of a function to define the places (usually in a loop) where values are produced. Or, technically, the easiest way is to use one of the many iterable objects already produced by built-ins or the standard library rather than programming a custom one at all. Generator functions are syn‐ tax sugar for defining a function that returns an iterator. Many objects have a method named .__iter__(), which will return an iterator when it is called, generally via the iter() built-in func‐ tion, or even more often simply by looping over the object (e.g., for item in collection: ...). What an iterator is is the object returned by a call to iter(some thing), which itself has a method named .__iter__() that simply returns the object itself, and another method named .__next__(). The reason the iterable itself still has an .__iter__() method is to make iter() idempotent. That is, this identity should always hold (or raise TypeError("object is not iterable")): iter_seq = iter(sequence) iter(iter_seq) == iter_seq The above remarks are a bit abstract, so let us look at a few concrete examples: >>> lazy = open('06-laziness.md') # iterate over lines of file >>> '__iter__' in dir(lazy) and '__next__' in dir(lazy) True >>> plus1 = map(lambda x: x+1, range(10)) >>> plus1 # iterate over deferred computations <map at 0x103b002b0> >>> '__iter__' in dir(plus1) and '__next__' in dir(plus1) True >>> def to10(): ... for i in range(10): ... yield i ... >>> '__iter__' in dir(to10) False >>> '__iter__' in dir(to10()) and '__next__' in dir(to10()) True The Iterator Protocol | 27
43.
>>> l =[1,2,3] >>> '__iter__' in dir(l) True >>> '__next__' in dir(l) False >>> li = iter(l) # iterate over concrete collection >>> li <list_iterator at 0x103b11278> >>> li == iter(li) True In a functional programming style—or even just generally for read‐ ability—writing custom iterators as generator functions is most nat‐ ural. However, we can also create custom classes that obey the pro‐ tocol; often these will have other behaviors (i.e., methods) as well, but most such behaviors necessarily rely on statefulness and side effects to be meaningful. For example: from collections.abc import Iterable class Fibonacci(Iterable): def __init__(self): self.a, self.b = 0, 1 self.total = 0 def __iter__(self): return self def __next__(self): self.a, self.b = self.b, self.a + self.b self.total += self.a return self.a def running_sum(self): return self.total # >>> fib = Fibonacci() # >>> fib.running_sum() # 0 # >>> for _, i in zip(range(10), fib): # ... print(i, end=" ") # ... # 1 1 2 3 5 8 13 21 34 55 # >>> fib.running_sum() # 143 # >>> next(fib) # 89 This example is trivial, of course, but it shows a class that both implements the iterator protocol and also provides an additional method to return something stateful about its instance. Since state‐ fulness is for object-oriented programmers, in a functional pro‐ gramming style we will generally avoid classes like this. 28 | Lazy Evaluation
44.
Module: itertools The moduleitertools is a collection of very powerful—and care‐ fully designed—functions for performing iterator algebra. That is, these allow you to combine iterators in sophisticated ways without having to concretely instantiate anything more than is currently required. As well as the basic functions in the module itself, the module documentation provides a number of short, but easy to get subtly wrong, recipes for additional functions that each utilize two or three of the basic functions in combination. The third-party module more_itertools mentioned in the Preface provides addi‐ tional functions that are likewise designed to avoid common pitfalls and edge cases. The basic goal of using the building blocks inside itertools is to avoid performing computations before they are required, to avoid the memory requirements of a large instantiated collection, to avoid potentially slow I/O until it is stricly required, and so on. Iterators are lazy sequences rather than realized collections, and when com‐ bined with functions or recipes in itertools they retain this prop‐ erty. Here is a quick example of combining a few things. Rather than the stateful Fibonacci class to let us keep a running sum, we might sim‐ ply create a single lazy iterator to generate both the current number and this sum: >>> def fibonacci(): ... a, b = 1, 1 ... while True: ... yield a ... a, b = b, a+b ... >>> from itertools import tee, accumulate >>> s, t = tee(fibonacci()) >>> pairs = zip(t, accumulate(s)) >>> for _, (fib, total) in zip(range(7), pairs): ... print(fib, total) ... 1 1 1 2 2 4 3 7 5 12 8 20 13 33 Module: itertools | 29
45.
Figuring out exactlyhow to use functions in itertools correctly and optimally often requires careful thought, but once combined, remarkable power is obtained for dealing with large, or even infin‐ ite, iterators that could not be done with concrete collections. The documentation for the itertools module contain details on its combinatorial functions as well as a number of short recipes for combining them. This paper does not have space to repeat those descriptions, so just exhibiting a few of them above will suffice. Note that for practical purposes, zip(), map(), filter(), and range() (which is, in a sense, just a terminating itertools.count()) could well live in itertools if they were not built-ins. That is, all of those functions lazily generate sequential items (mostly based on existing iterables) without creating a concrete sequence. Built-ins like all(), any(), sum(), min(), max(), and functools.reduce() also act on iterables, but all of them, in the general case, need to exhaust the iterator rather than remain lazy. The function itertools.prod uct() might be out of place in its module since it also creates con‐ crete cached sequences, and cannot operate on infinite iterators. Chaining Iterables The itertools.chain() and itertools.chain.from_iterable() functions combine multiple iterables. Built-in zip() and iter tools.zip_longest() also do this, of course, but in manners that allow incremental advancement through the iterables. A conse‐ quence of this is that while chaining infinite iterables is valid syntac‐ tically and semantically, no actual program will exhaust the earlier iterable. For example: from itertools import chain, count thrice_to_inf = chain(count(), count(), count()) Conceptually, thrice_to_inf will count to infinity three times, but in practice once would always be enough. However, for merely large iterables—not for infinite ones—chaining can be very useful and parsimonious: def from_logs(fnames): yield from (open(file) for file in fnames) lines = chain.from_iterable(from_logs( ['huge.log', 'gigantic.log'])) 30 | Lazy Evaluation
46.
Notice that inthe example given, we didn’t even need to pass in a concrete list of files—that sequence of filenames itself could be a lazy iterable per the API given. Besides the chaining with itertools, we should mention collec tions.ChainMap() in the same breath. Dictionaries (or generally any collections.abc.Mapping) are iterable (over their keys). Just as we might want to chain multiple sequence-like iterables, we some‐ times want to chain together multiple mappings without needing to create a single larger concrete one. ChainMap() is handy, and does not alter the underlying mappings used to construct it. Module: itertools | 31
48.
Higher-Order Functions In thelast chapter we saw an iterator algebra that builds on the iter tools module. In some ways, higher-order functions (often abbrevi‐ ated as “HOFs”) provide similar building blocks to express complex concepts by combining simpler functions into new functions. In general, a higher-order function is simply a function that takes one or more functions as arguments and/or produces a function as a result. Many interesting abstractions are available here. They allow chain‐ ing and combining higher-order functions in a manner analogous to how we can combine functions in itertools to produce new itera‐ bles. A few useful higher-order functions are contained in the functools module, and a few others are built-ins. It is common the think of map(), filter(), and functools.reduce() as the most basic build‐ ing blocks of higher-order functions, and most functional program‐ ming languages use these functions as their primitives (occasionally under other names). Almost as basic as map/filter/reduce as a build‐ ing block is currying. In Python, currying is spelled as partial(), and is contained in the functools module—this is a function that will take another function, along with zero or more arguments to pre-fill, and return a function of fewer arguments that operates as the input function would when those arguments are passed to it. The built-in functions map() and filter() are equivalent to com‐ prehensions—especially now that generator comprehensions are available—and most Python programmers find the comprehension versions more readable. For example, here are some (almost) equiv‐ alent pairs: 33
49.
# Classic "FP-style" transformed= map(tranformation, iterator) # Comprehension transformed = (transformation(x) for x in iterator) # Classic "FP-style" filtered = filter(predicate, iterator) # Comprehension filtered = (x for x in iterator if predicate(x)) The function functools.reduce() is very general, very powerful, and very subtle to use to its full power. It takes successive items of an iterable, and combines them in some way. The most common use case for reduce() is probably covered by the built-in sum(), which is a more compact spelling of: from functools import reduce total = reduce(operator.add, it, 0) # total = sum(it) It may or may not be obvious that map() and filter() are also a special cases of reduce(). That is: >>> add5 = lambda n: n+5 >>> reduce(lambda l, x: l+[add5(x)], range(10), []) [5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> # simpler: map(add5, range(10)) >>> isOdd = lambda n: n%2 >>> reduce(lambda l, x: l+[x] if isOdd(x) else l, range(10), []) [1, 3, 5, 7, 9] >>> # simpler: filter(isOdd, range(10)) These reduce() expressions are awkward, but they also illustrate how powerful the function is in its generality: anything that can be computed from a sequence of successive elements can (if awk‐ wardly) be expressed as a reduction. There are a few common higher-order functions that are not among the “batteries included” with Python, but that are very easy to create as utilities (and are included with many third-party collections of functional programming tools). Different libraries—and other pro‐ gramming languages—may use different names for the utility func‐ tions I describe, but analogous capabilities are widespread (as are the names I choose). 34 | Higher-Order Functions
50.
Utility Higher-Order Functions Ahandy utility is compose(). This is a function that takes a sequence of functions and returns a function that represents the application of each of these argument functions to a data argument: def compose(*funcs): """Return a new function s.t. compose(f,g,...)(x) == f(g(...(x)))""" def inner(data, funcs=funcs): result = data for f in reversed(funcs): result = f(result) return result return inner # >>> times2 = lambda x: x*2 # >>> minus3 = lambda x: x-3 # >>> mod6 = lambda x: x%6 # >>> f = compose(mod6, times2, minus3) # >>> all(f(i)==((i-3)*2)%6 for i in range(1000000)) # True For these one-line math operations (times2, minus3, etc.), we could have simply written the underlying math expression at least as easily; but if the composite calculations each involved branching, flow control, complex logic, etc., this would not be true. The built-in functions all() and any() are useful for asking whether a predicate holds of elements of an iterable. But it is also nice to be able to ask whether any/all of a collection of predicates hold for a particular data item in a composable way. We might implement these as: all_pred = lambda item, *tests: all(p(item) for p in tests) any_pred = lambda item, *tests: any(p(item) for p in tests) To show the use, let us make a few predicates: >>> is_lt100 = partial(operator.ge, 100) # less than 100? >>> is_gt10 = partial(operator.le, 10) # greater than 10? >>> from nums import is_prime # implemented elsewhere >>> all_pred(71, is_lt100, is_gt10, is_prime) True >>> predicates = (is_lt100, is_gt10, is_prime) >>> all_pred(107, *predicates) False The library toolz has what might be a more general version of this called juxt() that creates a function that calls several functions with Utility Higher-Order Functions | 35
wines, wool, andother products are numerous, but unimportant. The iron ore mines (red and brown hematite) in the Somorrostro range and district are largely in the hands of English capitalists. These mines, which began to attract the attention of British iron masters about 1870, occur chiefly in the mountain limestone, and are worked in open quarries. Short railways and tramways have been made to San Nicolas on the Nervion; and a wire tramway has been constructed by the Galdames Mining Company, who possess a cliff of iron ore about a mile long and 280 feet high. The tramway carries the ore through a tunnel, 600 feet long, to the quay. The Landore Siamese Steel Company have important hematite mines connected with the river by a wire tramway, carrying baskets for loading. BILBAO—THE ORCONERO IRON ORE COMPANY’S WHARF IN LUCHANA. Bilbao is largely modern and wholly commercial, and its public buildings are not notable. But its thoroughfares are full of movement, and the shady arenal, in the old town—the focus of the life of the whole city—contains the principal hotels, the chief cafes, and the New Theatre. The land which this beautiful promenade now occupies was at one time very boggy, and swept by the tides. Now the two principal avenues are asphalted. The Church of San Nicolás de Bari, which faces it, is one of the city parish churches. It was built towards the end of the fifteenth century on the ruins of the sailors’ and fishermen’s little church. This church has suffered greatly on account of floods, especially during the year 1553. It was closed in 1740 as ruin threatened it. When it fell, the present one was begun in 1743. During the last war it was used as a provisioning station; and, after repairs, was opened for worship on the 21st of January, 1881.
53.
A GALICIAN. T In NorthernSpain. HE great bulk of the Spanish people know as little of Galicia and the neighbouring Principality of the Asturias as the average Englishman knows of the Hebrides. Nor can they judge of the inhabitants of these provinces from the few individual Galicians who emigrate to Madrid any more than we in England can form an idea of Italians from the specimens who perambulate the London streets with a piano organ and a monkey. The Madrileño comes across a few Galicians in the capital engaged in menial services, and speaking a harsh, strange patois, which he finds some difficulty in understanding; but the Gallegan in exile is a very different person from the man you meet in his own land of rain and mist, where the scenery is exquisite, the hotels are famously bad, and devotion is the chief recreation of the community. At home these people are poor, but hardy; possessing little intelligence, but great capacity for work; knowing little comfort, but nursing a passionate attachment for the country of their birth. Many of the young women are remarkably handsome, but drudgery and hardship early tell their tale, and very few of them retain their good looks beyond the age of twenty. The country, for the most part, is poor to barrenness; the peasantry work day and night for mere subsistance; the cottages, which do duty for bedroom and nursery, stable, kitchen, rabbit hutch, pigsty and parlour, are damp and dirty, and destitute of beds or chimneys. The climate is rainy, the surface is mountainous, and the roads are generally bad. Small wonder is it that muleteers and commercial travellers constitute the principal visitors to Galicia—for those who have a soul above scenery, and an ambition beyond fishing, the country is practically without attraction. The single province of Oviedo, which constitutes the principality of the Asturias, harbours a people who have remained unconquered alike by Roman and Moor. There is protection, if not complete safety, in a country of mountain and valley, of damp and cold; and the Asturians have ever been able to spread themselves over the land and farm their straggling holdings in comparative security. They have cultivated maize for their staple food,
54.
A GALICIAN. AGALICIAN. poached the hills and rivers for game and fish, cultivated the art of dancing, and lived in terror of the evil eye from the most ancient times; and despite damp, hard fare, and harder toil, they have learnt REDONDELA (PROVINCE OF PONTEVEDRA)—GENERAL VIEW. the secret of longevity and the charm of a gracious civility of manner. Minerals in abundance are common to both Asturias and Galicia; and while the former is the richer in coal and iron, the latter has been worked for gold, silver, and tin from the time of the Roman occupation. It is on their mineral resources that these provinces will have to depend for their future prosperity.
55.
IN GALICIA. IN GALICIA. Afterthe cities of the South— Barcelona, Toledo, Granada, or even modern Madrid—the Northern towns are small, shabby, and unimportant. Coruña, the chief seaport of Galicia, though interesting to Englishmen as being the landing place in Spain of John of Gaunt, and the harbour from which the invincible Armada sailed to conquer and Romanise Great Britain, is a place of only secondary importance. The city was founded by the Phœnicians; its name is probably derived from Columna, the Phœnician Pharos, or lighthouse; and its famous lighthouse, the Tower of Hercules, has had its counterpart from the earliest days. The Phœnicians, who made gain rather than discovery the aim of all their expeditions, were attracted to Galicia and to the province of Orense particularly by reason of its rich deposits of tin. Coruña in ancient days was the principal port of the North-west Coast, and the most westerly town in Europe. It is still the chief military station in Northern Spain, and ranks as a commercial city of the first importance. CORUÑA—GENERAL VIEW TAKEN FROM THE OLD TOWN. The hill-girt city of Santiago, though knowing nothing of commercial prestige, and having no part in the military system of the country, is to the traveller of far more interest than the capital of the province. For dead as it
56.
now appears tobe, with the hand of death on its crooked, branching streets, and its crazy, deformed squares, which echo the pilgrims’ footfalls to the deaf ears of the dead, it was at one time the most celebrated religious centre in Spain—the goal of fanatics from every corner of Europe, the Mecca of countless thousands of theologians, and the tomb of one of the personal companions of Christ. Although the ancient glory of Santiago has departed, although PONTEVEDRA—GENERAL VIEW. its broad-flagged pavements are no longer thronged by the feet of the devout, and it has been much shorn of its former civil and religious dignities, the city is still the See of an Archbishop with a cathedral, two allegiate churches, and fifteen parishes. The cathedral is erected on the site of the chapel which was erected by Alonso II. to mark the spot where Theodomer, Bishop of Iria Flavia, is said to have discovered the body of St. James the Apostle; and the city, which sprang up around the memorial, bears the Spanish name for St. James the Elder. The original cathedral, which was finished in 879, consecrated in 899, and destroyed by the Moors in 997, was replaced by the present edifice in 1078. Whether one believes or not the tradition of the foundation of the cathedral—which, by the way, is no mere
57.
tradition in themind of the Galician—one cannot but regard this mighty pile of stone with awe, and recognise in it the expression of an influence which was once felt throughout the Christian world. Even to-day it is one of the most frequented pilgrim-resorts in Europe. One passes through Pontevedra, a picturesque granite town, with arcaded streets and ancient houses bearing armorial shields, on the journey to Vigo. Here, as everywhere on the Galician coast line, the parish priest goes down to the shore one day in every year and blesses the sea; here also the oysters are excellent and abundant, and here the watchman’s night chant is heard in the streets. The call of the sereno, or watchman, who dates from the building of the ancient walls of Pontevedra, and the chapel of Alonso II. of Santiago, seems to catch the imagination of the traveller, and hurl him back into the mediæval ages, when life was a state that men fought to retain, and religion was a power for which they laid it down. The sereno, with his theatrical cloak wrapped about him, his axe-headed staff, his lantern, his majestic stalking walk, and his thrilling chant, “Ave Maria Purissima. Son las diez y sereno,” seemed to me impressive, unreal, almost fantastic. At ten o’clock he passed me in the deserted square, at eleven he was offering up his quavering invocation beneath my window. Galicia has little in common with the towns of the South—it retires to rest early in order to be up betimes. At Vigo a small fragment of the ancient sea walls yet remain, but the ruins that Lord Cobham made of the town in 1719 have been obliterated, and in place of the fortified port, which Drake visited in 1585 and 1589, we have a thriving, modernised town. Vigo is an important place of call for Mediterranean steamers, it is one of the chief centres of the cattle trade export to London, and the port of the mineral provinces of Pontevedra and Orense. The town of Orense, the capital of its province, is reached by the magnificent old bridge that spans the river Miño. Though now deprived of three of its arches, which were removed to give the road more width, and also of the ancient castle which defended the entrance, it continues to attract the attention of the traveller on account of its elegant and bold construction, its ample proportions and majestic appearance. Tradition says it is Roman, but many learned writers find nothing to confirm this assertion. It is quite likely that a bridge existed there previously; but the present one, it would appear, was built by order of Bishop Lorenzo during the first half of the thirteenth century, and has since undergone many alterations, including those
58.
to the largestarch, which is more than forty-three metres in width, and the reconstruction of which was completed about the middle of the fifteenth century. In the Roman days Orense was celebrated for its warm baths. These three springs, which are still in existence, flow copiously from fountains one above another, but the waters have lost their medicinal virtues—it is VIGO—VIEW FROM THE CASTLE. only a supposition that they ever possessed any—and are now used for domestic purposes. The present cathedral, which is an obvious imitation of the cathedral at Santiago, was raised in 1220. The cathedral, the warm springs, and the bridge over the Miño, comprise the three marvels of the city.
59.
GIJON—THE WHARF. Equally ancient,but in many ways more interesting, is the capital town of Lugo. It boasts a cathedral which shares with San Isidoro of León the immemorial right to have the consecrated Host always exposed; Roman walls in an excellent state of preservation that entirely surround the city, and an establishment of baths. The bath-house contains 200 beds; and the springs, which contain nitre and antimony, are good for cutaneous diseases and rheumatism. The river Miño, which is the glory not only of Lugo but of Galicia, rises in the mountains, some nineteen miles from the city. As the centre of a beautiful and variegated country, which affords good sport for the angler, and scenery of enchanting loveliness to attract the artist, Oriedo, the capital of the Astionas, has its charms; but the seaport of Gijon, with its tobacco manufactory, its railway workshops, its iron foundry, and glass and pottery works, is a much more thriving and important town. Gijon, like Santander, is a flourishing port; and both have gained immensely in importance of late years. While the latter, with its handsome modern houses, makes a more splendid show, its drainage and sanitary arrangements leave much to be desired, and the harbour at low water is sometimes most offensive. Both towns are of Roman origin, but Gijon is the most pleasantly situated on a projecting headland beneath the shelter of the hill of Santa Catalina, and the harbour is the safest on the North Coast. It exports apples and nuts in enormous quantities, coal, and iron, and jet; while its shores are much frequented by bathers during the summer months.
60.
SANTANDER—THE PORT. SANTANDER—GENERAL VIEW. Itis currently believed, and I have no reason to doubt the accuracy of the statement, that if a visitor in any town in England stops the first native he meets and inquires as to the objects of interest that the place possesses, he will be referred immediately to the principal hostelry of the town. If you wander in London, and ask your way about, you will be directed right across the city by references to public-houses, which are the only landmarks that the Cockney ever dreams of studying. In Spain, cathedrals are as ubiquitous as inns are in England. You may be sure of finding comfortable accommodation for man and beast in most English towns, and in the Peninsula you can be quite as confident of “bringing up” against a cathedral —if nothing else. In León, the capital of the province of the same name, and in Salamanca, the second city in the province, we find the same state of things existing—the cathedral first and the rest nowhere. Yet these two cities boast of a noble history of ancient splendour and old-time greatness, and with this—and their cathedrals—they appear to be content. León, in the time
61.
LEÓN—THE CATHEDRAL. LEÓN—CLOISTER IN CATHEDRAL. ofAugustus, was the headquarters of the legion that defended the plains from the Asturian marauders; and when the Romans withdrew, it continued as an independent city to withstand the continued attacks of the Goths until 586. The city yielded to the Moor, was rescued by Ordoño I., and retaken by the Arabs with every accompaniment of inhuman atrocity. Its defences were rebuilt by Alonso V. nearly 400 years later, its houses were repeopled, and it continued to be the capital of the Kings of León until the court was removed to Seville by Don Pedro. Its present miserable condition is a lamentable appendix to such a history. Its streets are mean, its shops are miserable, and its inns are worse. Nothing is left to it but its cathedral. This temple is truly an architectural wonder, combining the delicacy of the purest Gothic style with a solidity which has stood for centuries; the manner in which the problem of stability was solved is wonderful, the immense weights seeming to have no solid bases. The finest and most beautiful chiselled work is visible everywhere, and careful study is necessary in order to understand how the weight and strain of the arches were made to rest on their elegant buttresses. The origin of this magnificent temple is not quite clear, but many archæologists believe that it was founded in the time of King Ordoño II. It is of irregular form, but the cathedral or nave, transept, and presbytery are in the form of a perfect Latin cross.
62.
LEÓN—THE CATHEDRAL CHOIRSTALLS. The windows are of colossal dimensions, and the ratablos and sculptures are notable. Among its many famous works the cloister must not be forgotten. It is an example of the transition style from ogive to renaissance, with large galleries, interesting groups of sculpture, and a beautiful door leading into the temple. LEÓN—VIEW TAKEN FROM THE CEMETERY. Among all the choral stalls treasured in Spanish churches those in the cathedral at León stand out prominently. Unfortunately, the names of the master who designed them, and of the artists who assisted him to carry that marvel of ogive art into effect, are not known; but it must have been executed during the last thirty years of the fifteenth century, for it is known that in 1468 the necessary bulls were obtained from his holiness through Archbishop Antonio de Veneris in order to arrange means for meeting the cost of the stalls, and in 1481 the work was still proceeding.
63.
SALAMANCA—GENERAL VIEW. Salamanca hasa great name, a florid Gothic cathedral, and a square of handsome proportions and pleasant prospects. In other respects, it is quite without attractions. The streets are badly paved and dull, the climate is shrewd, and fuel, I was told, is scarce and expensive. Even the cathedral, though grand, is bare; and when one has visited the cathedral and lingered awhile in the pleasant garden of the Plaza Mayor—one of the largest and handsomest squares in Spain—and tested the accommodation of “La Comercio,” one can find little else to entrance one in the disappointing old city which was once a world-famed seat of learning. In the fifteenth century, when its university gave precedence to Oxford alone, it boasted of 10,000 students. In the following century its scholars had declined to one half that number, and to-day only some few hundred students are on its books. The sun of Salamanca commenced to set at a period of the world’s history that to all the rest of Europe was one of awakening and advancement. Decline and decay are writ large on the face of the city. From a distance its noble situation and fine buildings, built of beautiful creamy stone, gives the place an imposing and picturesque appearance. But though the shell of Salamanca remains, its spirit has departed. The ravages of the Romans, the Goths, the Moors, the Spaniards, and the ruin which the neighbourly French inflicted less than a hundred years ago, have left their cruel marks upon its historic walls. Salamanca is but a broken hulk spent by the storms that, from time to time, have devastated her. Her narrow, tortuous, ill-paved streets, which skirt its multitude of grandiose buildings, her squalor and poverty, her inferior art work, but even more the uncorrupted art of the grand old cathedral, all remind us of what Salamanca was, and turn our eyes backwards from what it is.
64.
SALAMANCA—VIEW OF THECOLLEGE FROM THE IRLANDESES. ZARAGOZA—“INDEPENDENCIA” PROMENADE.
65.
ZARAGOZA—PILAR CHURCH. One mustapproach Zaragoza with one’s mind full of memories of heroes, queens, poets, and bandits that have been associated with this once mighty city, and one’s heart filled with sympathy and respect for the old, proud Aragon that flourished, and was illustrious in history while the Englanders still decorated themselves with blue paint, and were domiciled in caves. For Zaragoza is not altogether a gay or an exhilarating city. Many of the streets have a gloomy aspect, and the old houses are high, dark, and repellant. But the city is not only important as the seat of a university, an Audiencia, an archbishop, the captain-general of Aragón, and other officials; it is also the junction of four railways, and its commercial progress has been steadily increasing of recent years. For Zaragoza is in reality two cities—the old part with ancient fortified houses, converted now into stables and wood stores, and the new part traversed by broad, well-paved, and excellently-lighted streets, and lined with modern buildings. Until the railway connected the city with Madrid and Barcelona, Zaragoza was as dead as Salamanca, and as dilapidated as León. But it has always held the advantage of those places in having two cathedrals to their one. The principal cathedral, that of La Seo, is a venerable Gothic pile occupying the site of a Moorish mosque, and its high arches have echoed many councils, and looked down on the solemn coronations of the kings of Aragon. More modern is the Cathedral El Pilar, so called from the identical pillar on which the Virgin descended from heaven. It was commenced on St. James’s Day, 1686, the work being designed and carried out by the famous Don Francisco Herrera, the architect. In the year 1753 King Ferdinand VI. instructed Ventura Rodriguex, the architect, to design and build a new church, as luxurious as possible, in which to instal the image without taking it out of its temple. This was done by erecting a small Corinthian temple under the magnificent cupola, which was ornamented with the richest marble and jasper that could be procured. On one of the altars of this temple, which is crowned with a magnificent silver canopy, reposes the venerated effigy, the jewels on which are of incalculable value.
66.
A FLEMISH DANCE. ATNUEVALOS. The Stone Monastery at Nuevalos, on the right bank of the river from which it takes its name, is one of the places most worthy of a visit in the province of Zaragoza, not only on account of the building itself, which is of great historical interest, having been built in 1195, but for the delicious picturesqueness of the place. Surrounded by rocks, winding amidst thick woods and dashing into deep abysses, this river runs its erratic course, imparting life to a landscape which is, according to the noted poet, Don Ramon Campoamor, “an improved dream of Virgil.” Among its many picturesque waterfalls, the one called “La Caprichosa” is perhaps the most beautiful. The dress of the Aragonese peasantry is peculiar and picturesque. The men, as a rule, wear no hats, but have instead a coloured handkerchief wound round the head, leaving the top bare. Their knee-breeches are slashed down the sides and tied by strings below the knee. The waistcoats are worn open. Round the waist they wind a wide sash, in the folds of which pipes, tobacco, money, and provisions are carried as safely as in a pocket. Their feet are shod with sandals, and they universally carry a blanket, which is thrown in a graceful manner over their shoulders.
67.
A Bull-fighting. BULL-FIGHT is underlinedfor an early visit in the note-book of every visitor to Spain. He goes prepared to be disgusted, and he comes away to denounce it as a revolting and demoralising exhibition. He even plumes himself upon his moral and human superiority over the Spaniard, because the spectacle proves too strong for his untutored stomach. The inference is as gratuitous as it is illogical. In point of fact, the effect of the spectacle upon the spectator is not so much a matter of sensibility as custom. The Spaniard grows up to the sport as our Elizabethan ancestors grew to bull-baiting—even as the present generation of Englishman grows to pugilism. To the Spaniard, the cruelty of the craft of tauromachy does not appeal; the spectacle inflames his blood, and stirs not a chord of compassion in his nature. Yet he can be intensely sympathetic, gentle, and tender- hearted; but these softer qualities of character are not touched by the sight of animal suffering. In the first place, the bull is his enemy by heredited tendency. He cannot forbear to hurl insulting epithets at him when he chances to pass him on a journey. He witnesses his end with the thrill of satisfaction which a soldier feels in the death of a treacherous and implacable foe. The Englishman cannot share, or even realise this sentiment —it would be strange if he could. His leading feeling is curiosity, and a nervous apprehensive tension which only magnifies the horror and repulsion of the sport. With the Spaniard it is entirely different. Long habit has familiarised him with the bloody details, and his experienced eyes follow each trick and turn of the contest with the enthusiasm of an athlete watching an athletic display. Every detail of skill and dexterity and nerve exhibited by the fighters, and every clever move made by the bull is greeted with critical applause. Cruelty there must be, but courage in a high degree is a factor in the contest—danger gives to the contest a dignity which is absent from pheasant shooting, and which formed no excuse for the vogue to which bear- baiting and cock-fighting once attained in this country.
68.
THE PROCESSION. It maybe thought that I am trying to champion an institution which is regarded with aversion by all classes of English people, but such is not my intention. My object is to look at it from the Spanish point of view, and endeavour to see if there is not some plausible explanation of its popularity as a national amusement. But when all is said and done, there still exist two objections to the sport which cannot be explained away. The first is the almost inexplicable indifference which a Spanish audience shows for the torture that is inflicted upon the horses that take part in the corrida: the other is the attendance of the gentler sex. It must, however, be noted that a large proportion—certainly the majority of Spanish ladies—are opposed to the sport, and with the rest it is the manly courage and address of the performers that fascinates them. But the fact remains that women are seen in large numbers in the amphitheatre, as 300 years ago good Queen Bess was not ashamed to be a spectator at many an exhibition of bear-baiting. English sentiments in matters of sport have undergone a great change since the Elizabethan era, but Spain is notoriously the most conservative country in Europe. However, enough has been said of the theoretical side of bull-fighting; let us accompany the seething populace to the Plaza de Toros, and witness the sport for ourselves. The streets of Madrid are crowded with people who are all moving in the same direction. April to October is the regular bull-fighting season, but the Spaniard finds the lightest excuse a sufficient one for indulgence in his favourite pastime during the “close” season. And so, although it is February when I am in Madrid, I am not to forego an experience of a promising corrida.
69.
Although I haveseen bull-fights in some of the best rings in Spain, including those of San Sebastian, Valencia, Barcelona, and Madrid, it is more particularly of my experiences at the latter place that I shall write. During the fashionable months, a boletin de Sombra, or “ticket for the shade,” is a luxury to be prized; but in February, in Madrid, we need all the warmth and glare that the sun can give us. The present Bull Ring, which was built at a cost of £80,000, and opened in 1874, seats 15,000 persons. It stands on a gentle elevation in a broad stretch of bare yellow land, where it raises its brick-coloured walls—the only land-mark in the barren, treeless, desolate expanse between the city and the solemn distant mountains. Around the various entrances countless human beings cluster like bees, and the Plaza is alive with men and horses, mules with tinkling bells, soldiers, police, picadors, and fruit-sellers. What strikes one most curiously about this concourse of human beings, both outside the bull-ring and within the huge amphitheatre, which rises tier above tier from the brown sand till it is almost lost in the vast expanse of blue above, is its single-mindedness, its patience, and the entire absence of horseplay. To a Spaniard this is not curious, but to the English spectator some familiar characteristic of a crowd appears to be absent. ENTRANCE OF THE BULL. Punctuality is not a strong trait in the Spanish character, but punctuality will be observed to-day. At the hour and the minute appointed, the President enters his palco, the signal is given, and the proceedings commence. The procession, headed by two caballeros, habited in black velvet, moves slowly across the ring to the front of the President’s seat. The two espadas in yellow and violet, and gold and green costumes respectively, follow the caballeros. After them come half-a-dozen stoutly-protected picadores, then eight
70.
banderilleros, gay witha profusion of silk sashes, short breeches, and variously-coloured hose, and the rear is brought up by a posse of attendants, leading the mules, all bedecked in plumes and rich trappings, which are to drag off the carcases from the arena. The entrance of the glittering cavalcade is announced by a trumpet sound, and the President tosses the key of the toril into the ring. To the “new chum,” all this preliminary detail, commonplace and “circusy” as it is, is sufficient to strain the nerves, and expectancy changes to apprehension. The creak emitted by the opening of the heavy door of the toril intensifies the feeling. The clutch of curiosity with which the entire concourse awaits the entrance of the first bull is contagious. Instinctively one strains forward and catches one’s breath. Toro does not keep us long in suspense. There is a momentary lull, and then the bull dashes from his dark cell into the glint of the Spring sunshine. The novelty of the environment staggers him for a moment. He hesitates in the centre of the ring, and looks wildly around him. The arena is empty, with the exception of three picadores, who sit rigidly in a row on their sorry hacks, waiting for the bull to recognise their presence. Our first victim is a doughty warrior. He is as ignorant as the blindfold knackers—that would be dear at a pound a leg—of the fate in store for him. He may make a brave fight, kill horses, upset men, and leap the barriers with a heroic rush, but in twenty minutes his corpse will be coupled up to the mules, and fresh sand will be strewn on the red trail that will mark his last passage across the arena. The inevitableness of the outcome of the encounter, so far as the principal actor is concerned, is the least pleasing feature of the sport. The fox and the stag are
71.
ANTONI O FUENTE S. LUIS MAZZANTINI AND CUADRILLA. U E R R I T A . B a n d i l l e r o . givena gambling chance, the grouse is not without hope, and the gladiator of the cock-pit may live to fight another day, but the bull is a doomed animal. Happily he is not capable of calculating the uselessness of his efforts. The horses stand but little better chance, and the picadores, despite their iron and leather greaves and spears, are paid to take risks. The art of the picador is displayed in the skill with which he avoids the charge of the bull, and turns him on to the next picador, who, in turn, will pass him on to the third. In this instance the manœuvre does not come off. The bull’s rush is met by the first picador with the point, but the horse he strides is too ancient to obey with sufficient celerity the rider’s injunction to swerve, and horse and man are rolled over with the force of the impact. The
72.
wretched equine islacerated on his opposing flank, but the spearman appears to be uninjured, and before the bull has completed his circuit of the ring, the horse is on his feet again, and the picador is waiting for the next attack. The toreros, with their red capa, are immediately on the spot to draw the bull from his victim, but the bull is too eager to waste time on a fallen foe. The second and third horseman avoid his rush; and the bull, smarting from spear thrusts, and confused by the cheers, is inclined, in racing parlance, to “turn it up.” The first horse who crosses the line of sight is caught on the brute’s horns, and is so deeply impaled that the bull has to swerve at right angles to rid himself of his enemy. The second horse is impaled before the combatant can plant his spear in the bull’s neck. Steed and rider are lurched in the air, and fall heavily to the ground, and the momentary victor lowers his head again to the prostrate man, and rolls him over and over. Toreros hasten to the spot to get him away, the people rise in their places, ladies lift their fans and avert their faces, while the air is filled with the usual murmur of lamentation which accompanies an accident. Both the other picadores are unhorsed before the President gives the signal for them to retire. Act one of this most realistic of sporting melodramas is over. The banderilleros now come forward. They are costumed like Figaro, in the opera of “Il Barbiere de Sevilla,” and their hair is tied into a knot behind. To the English spectator, this part of the performance is the most fascinating and least abhorrent of the entire piece. The banderillero inflicts no more pain on the bull than the humane angler deals out to the wily trout, and the agility and daring with which he addresses himself to his task is superb. His aim is to plant small barbed darts, or banderillas, on each side of the neck of the bull. The chulos, or apprentices, here open the ball by tantalising the animal, and working him up to a proper pitch of fury. Then the banderilleros circle round him, and one, standing full in his line of flight, “defies” him with the arms raised high over his head. If the bull stops, as he is doing now, the man walks composedly towards him. Then the bull lowers his head and makes his rush, and the athlete, swerving nimbly to one side, pins in his banderillas simultaneously. Again and again the maddened animal, frantic more from impotence than pain, makes his rushes from one tormentor to another. At each rush he receives further instalments of his hated decorations. Then one man bungles. He loses his nerve, or, failing to time the animal’s charge, shirks the onslaught. A howl of execration greets the exhibition, and the unfortunate baiter is tempted to more rash efforts. He seats himself in a
73.
chair, and waitswith suicidal calmness the rush of the bull. Just as the animal’s horns are thrust beneath him he jumps lightly up, manipulating his darts with miraculous precision, while the chair is tossed high in the air. Thunders of applause greet this venturesome feat, and the other banderilleros, warmed to their work by the plaudits of the public, vie with one another in deeds of coolness and “derring do.” One waits, alert but motionless, for the attacks of the charging bull, and as the galloping brute lowers his head to toss him, places his foot between the terrible horns, and is lifted clear over his onrushing enemy. Another, seizing hold of the lashing tail, swings himself along the bull’s side, and plants himself for one thrilling moment right between the horns. THE PICADOR. I once saw a banderillero, in response to the jeers of the crowd, take the darts, which are about two feet long, break them across his knee, and plant the stumpy weapons, with unerring precision, on each side of the neck of the bull. These feats appear to be fraught with infinite danger, and the agility with which the performers acquit themselves cannot be witnessed without a tremour of amazement and admiration. Several times the venturesome chulos escape death as by a miracle: they sometimes seem so close to their end when they vault over the barriers to avoid the pursuing bull, that they appear to be helped over the fence by the bull’s horns. One bull exhibits at this stage of the proceedings an emphatic disinclination to continue the fight. He paws the ground when the darts are driven home, but makes no show of retaliation, and the hoots and opprobrious epithets that are hurled at him by the populace fail to inspire him to renewed efforts. Then the banderillas de
74.
fuego are calledfor. These are arrows, provided with fire crackers, which explode the moment they are affixed in the neck. In a moment the spectacle, which had worked me up to a high pitch of excitement, becomes intensely distasteful. The tortured animal, driven mad with fright and pain, bounds across the ring in a series of leaps like a kid. The people scream with delight, and I mentally wonder what kind of “steadier” the Spaniard resorts to when his stomachic nerve is affected by a detail of the exhibition. The firework display had not lasted long when the last trumpet sounded, and the espada walks forward to a storm of rapturous applause. The finale of the spectacle is approaching. The executioner comes alone: the bull, who has hitherto been tormented by a crowd of enemies, is now able to concentrate his whole attention on one object. Toro has become exhausted with his previous exertions, and he moves without his old dash. The espada studies his foe carefully, to judge the temper of the animal with which he has to deal. With his left hand he waves the muleta—the red cloak —to lure the beast into a few characteristic rushes and disclose his disposition. If he is a dull, heavy bull, he will be despatched with the beautiful half-volley; but if he proves himself a sly, dangerous customer, that is cunning enough to run at the man, instead of at the muleta, a less picturesque, but safer thrust must be employed. But our bull is neither sly nor leaden. He has recovered from his fright, and is quick to seize his opportunity to make a final effort before the stinging banderilleros return to distract him. Once or twice he thrusts his horns into the unresisting cloak, then gathers himself together for a final rush. The swordsman raises the point of his glimmering Toledo blade; while every nerve of his sinuous, graceful body quivers with the absolute constraint and concentrated effort that hold him. The duellists are both of the same mind. The espada has summed up his antagonist—he is levantados, the bold bull, a fit subject for la suerte de frente. The bull’s next rush is his last. The fencer receives the charge on his sword, which enters just between the left shoulder and the blade. The bull staggers, lurches heavily on to his knees, and rolls over, at the feet of his conqueror, vomiting blood. The assembled multitude rend the air with their cheers, the men yell applause, and every face is distorted with excitement and enthusiasm. The only indifferent person in the building is the espada. With a graceful and unassertive turn of his wrist, he waves the sword over his fallen foe, wipes the hot blood from the blade, and turning on his heel, approaches the
75.
President’s box, andbows with admirable sang-froid. The team of jingling mules enter, and the dead bull is carried off at a rapid gallop. The espada walks composedly away, without another glance at the result of his handiwork. The superb imperturbability of these espadas always fills me with admiration. They accept the plaudits of the spectators with the same unconcern with which they hear the execrations that fill the air if they do not at the first attempt inflict the coup de grace. During the first corrida I attended, an espada failed to aim at the precise spot, and the bull tore up the sand in agony. The populace insulted the swordsman with jeers and howlings, but he remained perfectly cool and collected, and nerved himself with as much composure to his second and successful thrust as if he had been practising with a sack of potatoes in an empty arena. When I had been witness to the death of two bulls, I remarked to my Spanish friend that I had seen as much as I desired, and was quite ready to quit the spot. But my companion was a friend of long standing: he could be firm without seeming discourteous. “No! no!” he said, “you kept me in the theatre last night until ‘Don Juan’ was played to the bitter end: you shall remain to-day to reward me for my exemplary patience and respect for your wishes.” I saw five other bulls done to death during the afternoon. AT CLOSE QUARTERS. Although not to be compared with an ordinary corrida as a display of skill, and capacity, and artistic finish, a Royal bull-fight, such as Madrid saw on the occasion of the coronation of King Alfonso XIII., is more interesting as being a revival of the sport as it was originally practised. Bull-fighting to- day is a purely professional business, but in the knightly days of ancient Spain it was employed as a means to teach the chivalrous youth the use of
76.
arms. In thosedays, mounted caballeros encountered the bulls in the ring with lances alone—a more dangerous pastime than is bull-fighting in its modern sufficiently hazardous form. Then the combatants were mounted on good horses, and their business was to save them and turn the bull, to kill the bull if possible, but, at the risk of their own lives, to protect their steeds from injury. It is recorded that in one Fiesta de Toros at the beginning of the sixteenth century, no less than ten young knights lost their lives. The corrida, Real con Caballeros en plaza—a Royal bull-fight with gentlemen in the arena—on the olden lines, that was held on May 21st, 1902, in Madrid, was fought by young officers and scions of noble families, who were attired in the gorgeous costumes of Spanish knights of the reign of Philip IV., and attended by their pages and grooms wearing the dress of the same period, and displaying the colours of the noble house which they served. On that occasion, the Paseo de las Cuadrillas, or preliminary procession of the bull- fighters across the arena to the strains of military music, was a most imposing sight. The Padrinos, the grandees who acted as supporters or godfathers of the knights, accompanied the fighters, followed by their mediævally-clad retinues, to the foot of the Royal box, and presented them to the King. The spectacle was strikingly brilliant, but the display was not to be compared with a professional bout. The horses of the cavaliers had evidently not been sufficiently trained for their work, and the best riding in the world could not bring them off scathless. Let me condense an account of the scene to convey an impression of what the present-day bull-fight has been derived from. When the procession had withdrawn, leaving only the chulos and the gallant caballeros in the arena, the door of the toril swung on its heavy hinges, and a splendid specimen of a bull, dungeoned for several hours previously in utter darkness, darted into the light of day, tearing up the ground with its hoofs, and ploughing the air with its horns. Suddenly, a horseman and his prancing steed vaulted into the centre of the ring—the charger, with flowing mane, full-veined ears and shapely head slanted forward—to meet the onrush of the goaded bull. The second picador seeing the bull worried and dazed by the tantalising assistants, scudded past on a swift, white racer, sitting gracefully in his saddle, and then turning deftly as he passed the great brute, plunged his lance into his neck, and whirled aside to avoid possible pursuit. But by sheer accident, the bleeding steer dashed
77.
off in thesame direction, caught the horse in the hindquarters, raising it on its forelegs and endangering the equilibrium of the rider. Before the scampering bull had time to recover from the compact, the second caballero, dashing up, had planted his lance deep into its neck. The white horse, stung with pain, made a wild rush, but was brought to hand by splendid horsemanship, and his rider urged him along, to inflict another wound in the animal’s head. Then two toreros advanced, beguiling and wearying the bull. By the time the bull had received the fifth lance in his neck, and the white steed had been twice wounded, the edge was taken off the keen thirst for violent emotions, and another torero unfolded his red capa, waved it to and fro until the bull swooped down upon him, and a moment later he was sprawling in the sand seemingly gored by the infuriated animal. The next minute the wounded steer tottered, dropped on its forelegs, and turned over on the sand, and a knife put a speedy end to its sufferings. The second bull, a black massive creature, appeared listless and faint, and made little effort to defend itself. It made one successful attack on the white charger; and, then, at the signal from the King, an amateur espada stepped forward. The attempt was a miserable failure. The young swordsman dedicated, in a few well-chosen words, the death of the bull to his sovereign, and after a dozen passes with the red capa, plunged the gleaming blade of Toledo steel into the animal’s neck, but so ineffectually that a storm of hisses resounded through the ring. The second attempt was still more awkward, the sword entering but a few inches. The sword was pulled out, and another effort, made amid groans and hisses, proved equally unsuccessful. A TURN WITH HIS BACK TO THE BULL. Although the madness had died out of the expiring brute’s eyes, and his forelegs were bending under him, the inexperienced torero seemed unable to
78.
put him outof pain. However, he grasped the short, sharp knife, and unsteadily taking aim, plunged it into the neck. Another failure. Yells, groans, shrieks, whistling, and hissing marked the anger of the crowd. The espada may be a paid professional, or the greatest noble in Spain, but in the ring he is judged by the rules of the ring, and his bungling is recognised with the most poignant scorn to which failure could be subjected. He again grasped the sword; and, spurred by the vitriolic exclamations of the public, sheathed it in the bull’s neck. The animal stood still and tottered, his forelegs bent, his head sank upon the moist, red sand, his hind feet quivered, and a flourish of trumpets announced that life was extinct. It is curious to find, in talking with learned enthusiasts on the relative merits of the bull-fighters, what diversity of opinion exists; but all parties are agreed upon the unrivalled skill and daring of the mighty Frascuelo. In his day, for death’s whistle summoned him from the arena in the height of his fame, Frascuelo was regarded as the greatest matador that Spain had ever seen; and Spaniards, in debating the subject of the bull-ring, never indulge the hope that his equal will ever arise to shed a new glory on the National sport. Frascuelo is dead, and his famous rival, Guerra, or Guerrita—to give him his professional name—has long since cut off his coleta, and lives in well-earned retirement at Córdova. But the school of fighters, who claim Frascuelo as their master—the fearless, dare-devil toreros, who scorn to concede a yard of ground to the bull, and do all their fighting at close quarters—is widely popular; and if their terribly dangerous methods are attended by frequent casualties, the intoxicating applause that rewards the accomplishment of a brilliant coup is, apparently, ample compensation for the risks that it entails. But the wildest appreciation of a successful feat does not exempt the most popular performer from the furious condemnation of the multitude when his scheme miscarries. The allowances made by a Spanish audience at the ring-side are of the most grudging nature. I once travelled from Barcelona to Madrid in the company of Bombita-Chico—the boy Bombita—who, although he was barely recovered from an unfortunate encounter with a tricky bull eight days before, was on his way to take part in a grand corrida that was to be held in the capital. He was—as his name denotes—no more than a lad, with large, strong hands that sparkled with jewels, while a formidable anchor about five inches long, set with magnificent diamonds, dangled from his watch-chain. I saw him again in the arena a few days later. He seemed nervous, and was, it appeared to me, a
79.
little perturbed bythe demonstration that welcomed his reappearance in the ring after his accident. Ill fortune allotted him a troublesome animal, and his kill, while creditable enough to untutored eyes, lacked the grace and finish that the critical spectator requires. Bombita was their own Boy of Madrid, and because of his recent misfortune they forgave him, but they did not cheer him; and the lad walked out of the arena amid a silence that could be felt. FIXING THE BANDERILLAS. Mazantini, now grown old and heavy, was in his day an undoubtedly fine matador. There are some that still regard him as the head of his profession. But the majority, remembering what he was, regret that he has not gone into honourable retirement. But Mazantini cannot tear himself away from the fascination of the arena, although his appearances grow less frequent every year. Conejito, who was wounded in Barcelona in the spring of 1903, is generally regarded as the most accomplished matador now before the public; but Fuentes is, par excellence, the best all-round man. For, with the exception of the picador business, Fuentes plays every part in the piece. Other espadas have their assistants, who play the bull with their capas, and stand by while the banderilleros ply their infuriating darts. It is only when the bull has been prepared for the slaughter by the other performers that the matador comes forward to put the finishing touch to the grim tragedy. Fuentes, on the other hand, on special occasions—of which the corrida which I attended in Madrid was one—keeps his assistants entirely in the background; he takes the stage when the picadores leave it, and keeps it to the end. So close does he keep to the bull, that during the corrida in Madrid, of which I am writing, he seldom allowed the animal to be a dart’s length away from him. On one occasion his capa got caught so tightly on the bull’s
80.
horns that hetore it in jerking it away; and at another time the bull stopped dead, with his forefeet on the hated sash. As a banderillero, Fuentes is without equal in Spain. He frequently works with darts that have previously been broken short, and he uses them sparingly. Yet the encounter between the banderillero and the bull when Fuentes is on the scene is the most thrilling part of the whole performance. It is a contest between human intellect and brute intelligence—a duel between mind and matter. Fuentes does not avoid the bull, but by exerting some magnetic power he repulses the animal and compels it to halt. When the bull charges, in response to his “defiance,” he waits with the banderillas suspended above his head until the animal is within a few yards of him. Then he deliberately, but without haste, lowers one arm until the arrow is on a level with the brute’s eyes. The bull wavers in his onslaught, slows up, and stops dead within a foot or two of the point. Sometimes Fuentes walks backwards, while the bull glares at him with stupefied impotence, until he escapes the eyes that THE MATADOR. hold him, and gallops away. Again and again the banderillero taunts his enemy to attack him, only to arrest his charge and force him to turn from his deadly purpose by the irresistible power of his superior mentality. The crowd follows this superb exhibition with breathless interest, and in a silence that is more eloquent of admiration than the wildest cheers would be. But the end is nearly reached. Fuentes grasps his stumpy darts and advances against his bewildered antagonist, who waits his approach with sulky indifference. The man’s arms are flung up with a gesture of exasperating defiance, and when the bull makes his final rush, his opponent, instead of stopping him, steps lithely on one side, and the brute thunders past him with the two galling arrows firmly implanted in his huge neck. Fuentes has already moved to the
81.
side of thering. The bull turns and charges back at him. The banderillero glides gracefully over the sand, but his pace is not equal to that of his infuriated pursuer. The distance between them decreases rapidly; in half-a- dozen yards he will be upon him. Fuentes glances over his shoulder and, without changing his pace, doffs his cap and flings it in the bull’s face. This stratagem only arrests the rush of the brute for a moment, but it gives the man time to reach the barrier, where he receives his muleta and sword from an attendant and returns to complete his task. All the kings of the bull-ring have their own particular feats or strokes, which the Spaniards appreciate as Englishmen revel in Ranjitsinhji’s acrobatic hitting, or Morny Cannon’s inimitable “finishes.” Bombita-Chico’s speciality in playing his bull is to kneel in the arena and allow the animal to charge through the capa which is held within three feet of the ground. The nerve required for this feat fires the audience with enthusiastic approval. The tale is told of a torero, whose name I have forgotten, who gained distinction by his exceptional skill in facing the bull with the long vaulting pole, known as the salto de la garrocha. With this instrument he would goad the bull on to the attack. When the brute was in full gallop he would, timing his movements to the instant, run a few yards to meet him, and swing himself high into the air at the end of his pole. The oncoming bull would charge the pole, the grounded end would be tossed upwards, and the torero would drop lightly to the ground and make good his escape. On one occasion the man performed his risky “turn” at a moment when the attention of a royal lady was attracted from the arena, and she sent an attendant to the expert to command him to repeat it. In vain the poor fellow protested that it was impossible for him to accomplish the same feat again with the same bull. The lady’s desire had been expressed. “But it is more than my life is worth,” argued the athlete. “It is the lady’s wish,” responded the attendant. The torero bowed, and “I dedicate my life to Her Royal Highness,” he said. The attempt fell out as he foretold. The bull charged and stopped dead. The man vaulted aloft, his body described a half circle, and fell—on the horns of the bull. He was dead before the attendants could entice the animal from his victim.
82.
THE FINAL STROKE. Lagartijo,Lagartijillo, Mazantini, and Montes all have their distinguishing methods of attacking and despatching the bull, but none of these are capable of the feat by which Guerrita was wont to throw the bull- ring into transports of deafening enthusiasm. In the ordinary way, the espada having taken the measure of his adversary, receives him standing sideways, and having thrust his sword at arm’s length between the left shoulder and the blade, leaps aside as the bull blunders forward on to his knees and falls to the earth. But Guerrita advanced his left arm across his body and waved his muleta under his right uplifted arm. When the bull lowered his head at the charge he passed the sword over the animal’s horns and plunged the blade into the vital spot behind the shoulder. In other words, he stopped the brute and killed him while his head was under his arm; and so closely were the duellists locked in that last embrace, that Guerrita’s side was frequently scratched by the bull’s horns. One may lecture, write, and preach against the barbarity of bull-fighting; but so long as Spain can breed men of such amazing nerve, and skill, and dexterity that they can successfully defy death and mutilation to provide their countrymen with such lurid sport, so long will bull-fighting continue to flourish in Spain.
83.
Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com