Text stringlengths 1 9.41k |
|---|
When you start using functions in earnest, you’re faced
with choices about how to glue components together—for instance, how to decompose
a task into purposeful functions (known as cohesion), how your functions should communicate (called coupling), and so on. |
You also need to take into account concepts such
as the size of your functions, because they directly impact code usability. |
Some of this
falls into the category of structured analysis and design, but it applies to Python code
as to any other.
We introduced some ideas related to function and module coupling in the Chapter 17 when studying scopes, but here is a review of a few general guidelines for function
beginners:
- Coupling: use argu... |
Generally, you**
should strive to make a function independent of things outside of it. |
Arguments
and return statements are often the best ways to isolate external dependencies to
a small number of well-known places in your code.
-----
- Coupling: use global variables only when truly necessary. |
Global variables
(i.e., names in the enclosing module) are usually a poor way for functions to communicate. |
They can create dependencies and timing issues that make programs
difficult to debug and change.
- Coupling: don’t change mutable arguments unless the caller expects it.
Functions can change parts of passed-in mutable objects, but (as with global
variables) this creates lots of coupling between the caller and callee,... |
When designed well, each of your functions should do one thing—something you can summarize in a simple declarative sentence. |
If that sentence is very broad (e.g., “this
function implements my whole program”), or contains lots of conjunctions (e.g.,
“this function gives employee raises and submits a pizza order”), you might want
to think about splitting it into separate and simpler functions. |
Otherwise, there is
no way to reuse the code behind the steps mixed together in the function.
- Size: each function should be relatively small. |
This naturally follows from the
preceding goal, but if your functions start spanning multiple pages on your display,
it’s probably time to split them. |
Especially given that Python code is so concise to
begin with, a long or deeply nested function is often a symptom of design problems.
Keep it simple, and keep it short.
- Coupling: avoid changing variables in another module file directly. |
We introduced this concept in Chapter 17, and we’ll revisit it in the next part of the book
when we focus on modules. |
For reference, though, remember that changing variables across file boundaries sets up a coupling between modules similar to how
global variables couple functions—the modules become difficult to understand
and reuse. |
Use accessor functions whenever possible, instead of direct assignment
statements.
Figure 19-1 summarizes the ways functions can talk to the outside world; inputs may
come from items on the left side, and results may be sent out in any of the forms on the
right. |
Good function designers prefer to use only arguments for inputs and `return`
statements for outputs, whenever possible.
Of course, there are plenty of exceptions to the preceding design rules, including some
related to Python’s OOP support. |
As you’ll see in Part VI, Python classes depend on
changing a passed-in mutable object—class functions set attributes of an automatically
passed-in argument called `self to change per-object state information (e.g.,`
```
self.name='bob'). |
Moreover, if classes are not used, global variables are often the most
```
straightforward way for functions in modules to retain state between calls. |
Side effects
are dangerous only if they’re unexpected.
In general though, you should strive to minimize external dependencies in functions
and other program components. |
The more self-contained a function is, the easier it will
be to understand, reuse, and modify.
**|**
-----
_Figure 19-1. Function execution environment. |
Functions may obtain input and produce output in a_
_variety of ways, though functions are usually easier to understand and maintain if you use arguments_
_for input and return statements and anticipated mutable argument changes for output. |
In Python 3,_
_outputs may also take the form of declared nonlocal names that exist in an enclosing function scope._
###### Recursive Functions
While discussing scope rules near the start of Chapter 17, we briefly noted that Python
supports recursive functions—functions that call themselves either directly or indirec... |
Recursion is a somewhat advanced topic, and it’s relatively rare to see
in Python. |
Still, it’s a useful technique to know about, as it allows programs to traverse
structures that have arbitrary and unpredictable shapes. |
Recursion is even an alternative
for simple loops and iterations, though not necessarily the simplest or most efficient
one.
###### Summation with Recursion
Let’s look at some examples. |
To sum a list (or other sequence) of numbers, we can
either use the built-in sum function or write a more custom version of our own. |
Here’s
what a custom summing function might look like when coded with recursion:
```
>>> def mysum(L):
... if not L:
... return 0
... else:
```
`... |
return L[0] + mysum(L[1:])` _# Call myself_
```
>>> mysum([1, 2, 3, 4, 5])
15
```
At each level, this function calls itself recursively to compute the sum of the rest of the
list, which is later added to the item at the front. |
The recursive loop ends and zero is
returned when the list becomes empty. |
When using recursion like this, each open level
**|**
-----
of call to the function has its own copy of the function’s local scope on the runtime call
stack—here, that means L is different in each level.
If this is difficult to understand (and it often is for new programmers), try adding a
```
print of L to the fu... |
print(L)` _# Trace recursive levels_
`... if not L:` _# L shorter at each level_
```
... return 0
... else:
... |
return L[0] + mysum(L[1:])
...
>>> mysum([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]
[2, 3, 4, 5]
[3, 4, 5]
[4, 5]
[5]
[]
15
```
As you can see, the list to be summed grows smaller at each recursive level, until it
becomes empty—the termination of the recursive loop. |
The sum is computed as the
recursive calls unwind.
###### Coding Alternatives
Interestingly, we can also use Python’s if/else ternary expression (described in Chapter 12) to save some code real-estate here. |
We can also generalize for any summable
type (which is easier if we assume at least one item in the input, as we did in Chapter 18’s minimum value example) and use Python 3.0’s extended sequence assignment
to make the first/rest unpacking simpler (as covered in Chapter 11):
```
def mysum(L):
return 0 if not L els... |
The
net effect is the same, though there are two function calls at each level instead of one:
```
>>> def mysum(L):
... if not L: return 0
```
`... |
return nonempty(L)` _# Call a function that calls me_
```
...
>>> def nonempty(L):
```
`... |
return L[0] + mysum(L[1:])` _# Indirectly recursive_
```
...
>>> mysum([1.1, 2.2, 3.3, 4.4])
11.0
###### Loop Statements Versus Recursion
```
Though recursion works for summing in the prior sections’ examples, it’s probably
overkill in this context. |
In fact, recursion is not used nearly as often in Python as in
more esoteric languages like Prolog or Lisp, because Python emphasizes simpler procedural statements like loops, which are usually more natural. |
The while, for example,
often makes things a bit more concrete, and it doesn’t require that a function be defined
to allow recursive calls:
```
>>> L = [1, 2, 3, 4, 5]
>>> sum = 0
>>> while L:
... |
sum += L[0]
... |
L = L[1:]
...
>>> sum
15
```
Better yet, for loops iterate for us automatically, making recursion largely extraneous
in most cases (and, in all likelihood, less efficient in terms of memory space and execution time):
```
>>> L = [1, 2, 3, 4, 5]
>>> sum = 0
>>> for x in L: sum += x
...
>>> sum
15
```... |
As a simple
example of recursion’s role in this context, consider the task of computing the sum of
all the numbers in a nested sublists structure like this:
```
[1, [2, [3, 4], 5], 6, [7, 8]] # Arbitrarily nested sublists
```
Simple looping statements won’t work here because this not a linear iteration. |
Nested
looping statements do not suffice either, because the sublists may be nested to arbitrary
depth and in an arbitrary shape. |
Instead, the following code accommodates such general nesting by using recursion to visit sublists along the way:
```
def sumtree(L):
tot = 0
for x in L: # For each item at this level
if not isinstance(x, list):
tot += x # Add numbers directly
else:
to... |
Although this example is artificial, it is representative of a larger class
of programs; inheritance trees and module import chains, for example, can exhibit
similarly general structures. |
In fact, we will use recursion again in such roles in more
realistic examples later in this book:
- In Chapter 24’s reloadall.py, to traverse import chains
- In Chapter 28’s classtree.py, to traverse class inheritance trees
- In Chapter 30’s lister.py, to traverse class inheritance trees again
**|**
-----
Alt... |
As you’ll also see later in the book, some operator overloading methods
in classes such as __setattr__ and __getattribute__ have the potential to recursively
loop if used incorrectly. |
Recursion is a powerful tool, but it tends to be best when
expected!
###### Function Objects: Attributes and Annotations
Python functions are more flexible than you might think. |
As we’ve seen in this part of
the book, functions in Python are much more than code-generation specifications for
a compiler—Python functions are full-blown objects, stored in pieces of memory all
their own. |
As such, they can be freely passed around a program and called indirectly.
They also support operations that have little to do with calls at all—attribute storage
and annotation.
###### Indirect Function Calls
Because Python functions are objects, you can write programs that process them generically. |
Function objects may be assigned to other names, passed to other functions,
embedded in data structures, returned from one function to another, and more, as if
they were simple numbers or strings. |
Function objects also happen to support a special
operation: they can be called by listing arguments in parentheses after a function expression. |
Still, functions belong to the same general category as other objects.
We’ve seen some of these generic use cases for functions in earlier examples, but a quick
review helps to underscore the object model. |
For example, there’s really nothing special
about the name used in a def statement: it’s just a variable assigned in the current scope,
as if it had appeared on the left of an = sign. |
After a def runs, the function name is simply
a reference to an object—you can reassign that object to other names freely and call it
through any reference:
`>>> def echo(message):` _# Name echo assigned to function object_
```
... |
print(message)
...
```
`>>> echo('Direct call')` _# Call object through original name_
```
Direct call
```
`>>> x = echo` _# Now x references the function too_
`>>> x('Indirect call!')` _# Call object through name by adding ()_
```
Indirect call!
```
**|**
-----
Because arguments are passed by assigning obj... |
The callee may then call the passed-in function just by
adding arguments in parentheses:
```
>>> def indirect(func, arg):
```
`... |
func(arg)` _# Call the passed-in object by adding ()_
```
...
```
`>>> indirect(echo, 'Argument call!')` _# Pass the function to another function_
```
Argument call!
```
You can even stuff function objects into data structures, as though they were integers
or strings. |
The following, for example, embeds the function twice in a list of tuples, as
a sort of actions table. |
Because Python compound types like these can contain any sort
of object, there’s no special case here, either:
```
>>> schedule = [ (echo, 'Spam!'), (echo, 'Ham!') ]
>>> for (func, arg) in schedule:
```
`... |
func(arg)` _# Call functions embedded in containers_
```
...
Spam!
Ham!
```
This code simply steps through the schedule list, calling the echo function with one
argument each time through (notice the tuple-unpacking assignment in the for loop
header, introduced in Chapter 13). |
As we saw in Chapter 17’s examples, functions can
also be created and returned for use elsewhere:
`>>> def make(label):` _# Make a function but don't call it_
```
... def echo(message):
... |
print(label + ':' + message)
... |
return echo
...
```
`>>> F = make('Spam')` _# Label in enclosing scope is retained_
`>>> F('Ham!')` _# Call the function that make returned_
```
Spam:Ham!
>>> F('Eggs!')
Spam:Eggs!
```
Python’s universal object model and lack of type declarations make for an incredibly
flexible programming language.
###### F... |
In
fact, functions are more flexible than you might expect. For instance, once we make a
function, we can call it as usual:
```
>>> def func(a):
... b = 'spam'
... |
return b * a
...
>>> func(8)
'spamspamspamspamspamspamspamspam'
```
**|**
-----
But the call expression is just one operation defined to work on function objects. |
We
can also inspect their attributes generically (the following is run in Python 3.0, but 2.6
results are similar):
```
>>> func.__name__
'func'
>>> dir(func)
['__annotations__', '__call__', '__class__', '__closure__', '__code__',
...more omitted...
'__repr__', '__setattr__', '__sizeof__', '__str__', '__sub... |
As we learned in Chapter 17, it’s possible to attach arbitrary userdefined attributes to them as well:
```
>>> func
<function func at 0x0257C738>
>>> func.count = 0
>>> func.count += 1
>>> func.count
1
>>> func.handles = 'Button-Press'
>>> func.handles
'Button-Press'
>>> dir(func)
['__annotations_... |
Unlike nonlocals, such attributes are accessible anywhere the function itself
is. |
In a sense, this is also a way to emulate “static locals” in other languages—variables
whose names are local to a function, but whose values are retained after a function
exits. |
Attributes are related to objects instead of scopes, but the net effect is similar.
###### Function Annotations in 3.0
In Python 3.0 (but not 2.6), it’s also possible to attach _annotation information—_
arbitrary user-defined data about a function’s arguments and result—to a function
object. |
Python provides special syntax for specifying annotations, but it doesn’t do
anything with them itself; annotations are completely optional, and when present are
simply attached to the function object’s `__annotations__ attribute for use by other`
tools.
We met Python 3.0’s keyword-only arguments in the prior chapter;... |
Consider the following nonannotated function,
which is coded with three arguments and returns a result:
```
>>> def func(a, b, c):
... |
return a + b + c
...
>>> func(1, 2, 3)
6
```
Syntactically, function annotations are coded in def header lines, as arbitrary expressions associated with arguments and return values. |
For arguments, they appear after a
colon immediately following the argument’s name; for return values, they are written
after a -> following the arguments list. |
This code, for example, annotates all three of
the prior function’s arguments, as well as its return value:
```
>>> def func(a: 'spam', b: (1, 10), c: float) -> int:
... |
return a + b + c
...
>>> func(1, 2, 3)
6
```
Calls to an annotated function work as usual, but when annotations are present Python
collects them in a _dictionary and attaches it to the function object itself. |
Argument_
names become keys, the return value annotation is stored under key “return” if coded,
and the values of annotation keys are assigned to the results of the annotation
expressions:
```
>>> func.__annotations__
{'a': 'spam', 'c': <class 'float'>, 'b': (1, 10), 'return': <class 'int'>}
```
Because they are j... |
The following annotates just two of three arguments and
steps through the attached annotations generically:
**|**
-----
```
>>> def func(a: 'spam', b, c: 99):
... |
return a + b + c
...
>>> func(1, 2, 3)
6
>>> func.__annotations__
{'a': 'spam', 'c': 99}
>>> for arg in func.__annotations__:
... |
print(arg, '=>', func.__annotations__[arg])
...
a => spam
c => 99
```
There are two fine points to note here. |
First, you can still use defaults for arguments if
you code annotations—the annotation (and its : character) appear before the default
(and its = character). |
In the following, for example, a: 'spam' = 4 means that argument
```
a defaults to 4 and is annotated with the string 'spam':
>>> def func(a: 'spam' = 4, b: (1, 10) = 5, c: float = 6) -> int:
... |
return a + b + c
...
>>> func(1, 2, 3)
6
```
`>>> func()` _# 4 + 5 + 6 (all defaults)_
```
15
```
`>>> func(1, c=10)` _# 1 + 5 + 10 (keywords work normally)_
```
16
>>> func.__annotations__
{'a': 'spam', 'c': <class 'float'>, 'b': (1, 10), 'return': <class 'int'>}
```
Second, note that the blank space... |
return a + b + c
...
```
`>>> func(1, 2)` _# 1 + 2 + 6_
```
9
>>> func.__annotations__
{'a': 'spam', 'c': <class 'float'>, 'b': (1, 10), 'return': <class 'int'>}
```
Annotations are a new feature in 3.0, and some of their potential uses remain to be
uncovered. |
It’s easy to imagine annotations being used to specify constraints for argument types or values, though, and larger APIs might use this feature as a way to register
function interface information. |
In fact, we’ll see a potential application in Chapter 38, where we’ll look at annotations as an alternative to function decorator argu_ments (a more general concept in which information is coded outside the function_
header and so is not limited to a single role). |
Like Python itself, annotation is a tool
whose roles are shaped by your imagination.
**|**
-----
Finally, note that annotations work only in `def statements, not` `lambda expressions,`
because lambda’s syntax already limits the utility of the functions it defines. |
Coincidentally, this brings us to our next topic.
###### Anonymous Functions: lambda
Besides the `def statement, Python also provides an expression form that generates`
function objects. |
Because of its similarity to a tool in the Lisp language, it’s called
```
lambda.[*] Like def, this expression creates a function to be called later, but it returns the
```
function instead of assigning it to a name. |
This is why lambdas are sometimes known
as anonymous (i.e., unnamed) functions. |
In practice, they are often used as a way to
inline a function definition, or to defer execution of a piece of code.
###### lambda Basics
The lambda’s general form is the keyword lambda, followed by one or more arguments
(exactly like the arguments list you enclose in parentheses in a def header), followed
by an expr... |
argumentN :expression using arguments
```
Function objects returned by running `lambda expressions work exactly the same as`
those created and assigned by defs, but there are a few differences that make lambdas
useful in specialized roles:
- lambda **is an expression, not a statement. |
Because of this, a lambda can appear in**
places a def is not allowed by Python’s syntax—inside a list literal or a function
call’s arguments, for example. |
As an expression, `lambda returns a value (a new`
function) that can optionally be assigned a name. |
In contrast, the def statement
always assigns the new function to the name in the header, instead of returning it
as a result.
- lambda’s body is a single expression, not a block of statements. |
The lambda’s
body is similar to what you’d put in a def body’s return statement; you simply type
the result as a naked expression, instead of explicitly returning it. |
Because it is
limited to an expression, a lambda is less general than a def—you can only squeeze
so much logic into a lambda body without using statements such as if. |
This is by
design, to limit program nesting: lambda is designed for coding simple functions,
and def handles larger tasks.
- The `lambda tends to intimidate people more than it should. |
This reaction seems to stem from the name`
“lambda” itself—a name that comes from the Lisp language, which got it from lambda calculus, which is a
form of symbolic logic. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.