Text
stringlengths
1
9.41k
As mentioned previously, arguments are passed by assignment, so in this case the name x in the function header is assigned the value 2, y is assigned the value 4, and the function’s body is run.
For this function, the body is just a return statement that sends back the result as the value of the call expression.
The returned object was printed here interactively (as in most languages, ``` 2 * 4 is 8 in Python), but if we needed to use it later we could instead assign it to a ``` variable.
For example: `>>> x = times(3.14, 4)` _# Save the result object_ ``` >>> x 12.56 ``` Now, watch what happens when the function is called a third time, with very different kinds of objects passed in: `>>> times('Ni', 4)` _# Functions are "typeless"_ ``` 'NiNiNiNi' ``` **|** ----- This time, our function mea...
In this third call, a string and an integer are passed to x and y, instead of two numbers.
Recall that * works on both numbers and sequences; because we never declare the types of variables, arguments, or return values in Python, we can use ``` times to either multiply numbers or repeat sequences. ``` In other words, what our times function means and does depends on what we pass into it.
This is a core idea in Python (and perhaps the key to using the language well), which we’ll explore in the next section. ###### Polymorphism in Python As we just saw, the very meaning of the expression x * y in our simple times function depends completely upon the kinds of objects that x and y are—thus, the same func...
Python leaves it up to the objects to do something reasonable for the syntax.
Really, * is just a dispatch mechanism that routes control to the objects being processed. This sort of type-dependent behavior is known as polymorphism, a term we first met in Chapter 4 that essentially means that the meaning of an operation depends on the objects being operated upon.
Because it’s a dynamically typed language, polymorphism runs rampant in Python.
In fact, every operation is a polymorphic operation in Python: printing, indexing, the * operator, and much more. This is deliberate, and it accounts for much of the language’s conciseness and flexibility. A single function, for instance, can generally be applied to a whole category of object types automatically.
As long as those objects support the expected interface (a.k.a. protocol), the function can process them.
That is, if the objects passed into a function have the expected methods and expression operators, they are plug-and-play compatible with the function’s logic. Even in our simple times function, this means that any two objects that support a * will work, no matter what they may be, and no matter when they are coded.
This function will work on two numbers (performing multiplication), or a string and a number (performing repetition), or any other combination of objects supporting the expected interface—even class-based objects we have not even coded yet. Moreover, if the objects passed in do not support this expected interface, Pyt...
It’s therefore pointless to code error checking ourselves.
In fact, doing so would limit our function’s utility, as it would be restricted to work only on objects whose types we test for. This turns out to be a crucial philosophical difference between Python and statically typed languages like C++ and Java: in Python, your code is not supposed to care about specific data type...
If it does, it will be limited to working on just the types you anticipated when you wrote it, and it will not support other compatible object types that **f** **|** ----- may be coded in the future.
Although it is possible to test for types with tools like the ``` type built-in function, doing so breaks your code’s flexibility.
By and large, we code to ``` object interfaces in Python, not data types. Of course, this polymorphic model of programming means we have to test our code to detect errors, rather than providing type declarations a compiler can use to detect some types of errors for us ahead of time.
In exchange for an initial bit of testing, though, we radically reduce the amount of code we have to write and radically increase our code’s flexibility.
As you’ll learn, it’s a net win in practice. ###### A Second Example: Intersecting Sequences Let’s look at a second function example that does something a bit more useful than multiplying arguments and further illustrates function basics. In Chapter 13, we coded a for loop that collected items held in common in two ...
Of course, we could copy the code and paste it into each place where it needs to be run, but this solution is neither good nor general—we’d still have to edit each copy to support different sequence names, and changing the algorithm would then require changing multiple copies. ###### Definition By now, you can probab...
Doing so offers a number of advantages: ``` - Putting the code in a function makes it a tool that you can run as many times as you like. - Because callers can pass in arbitrary arguments, functions are general enough to work on any two sequences (or other iterables) you wish to intersect. - When the logic is pack...
Because this function computes a result, we’ve also added a return statement to send a result object back to the caller. ###### Calls Before you can call a function, you have to make it.
To do this, run its def statement, either by typing it interactively or by coding it in a module file and importing the file. Once you’ve run the def, you can call the function by passing any two sequence objects in parentheses: ``` >>> s1 = "SPAM" >>> s2 = "SCAM" ``` `>>> intersect(s1, s2)` _# Strings_ ``` ['S'...
The algorithm the function uses is simple: “for every item in the first argument, if that item is also in the second argument, append the item to the result.” It’s a little shorter to say that in Python than in English, but it works out the same. To be fair, our intersect function is fairly slow (it executes nested lo...
That is, it works on arbitrary types, as long as they support the expected object interface: `>>> x = intersect([1, 2, 3], (1, 4))` _# Mixed types_ `>>> x` _# Saved result object_ ``` [1] ``` This time, we passed in different types of objects to our function—a list and a tuple (mixed types)—and it still picked out ...
Because you don’t have to specify the types of arguments ahead of time, the intersect function happily iterates through any kind of sequence objects you send it, as long as they support the expected interfaces. For intersect, this means that the first argument has to support the for loop, and the second has to support...
Any two such objects will work, regardless of their specific types—that includes physically stored sequences like strings **|** ----- and lists; all the iterable objects we met in Chapter 14, including files and dictionaries; and even any class-based objects we code that apply operator overloading techniques (we’ll...
By not coding type tests and allowing Python to detect the mismatches for us, we both reduce the amount of code we need to write and increase our code’s flexibility. ###### Local Variables Probably the most interesting part of this example is its names.
It turns out that the variable res inside intersect is what in Python is called a local variable—a name that is visible only to code inside the function def and that exists only while the function runs.
In fact, because all names assigned in any way inside a function are classified as local variables by default, nearly all the names in intersect are local variables: - res is obviously assigned, so it is a local variable. - Arguments are passed by assignment, so seq1 and seq2 are, too. - The for loop assigns item...
To fully explore the notion of locals, though, we` need to move on to Chapter 17. ###### Chapter Summary This chapter introduced the core ideas behind function definition—the syntax and operation of the def and return statements, the behavior of function call expressions, and the notion and benefits of polymorphism i...
As we saw, a def statement is executable code that creates a function object at runtime; when the function is later called, objects are passed into it by assignment (recall that assignment means object reference in Python, which, as we learned in Chapter 6, really means pointer internally), and computed values are sent...
We also began` - This code will always work if we intersect files’ contents obtained with file.readlines().
It may not work to intersect lines in open input files directly, though, depending on the file object’s implementation of the ``` in operator or general iteration.
Files must generally be rewound (e.g., with a file.seek(0) or another ``` `open) after they have been read to end-of-file once.
As we’ll see in` Chapter 29 when we study operator overloading, classes implement the in operator either by providing the specific __contains__ method or by supporting the general iteration protocol with the __iter__ or older __getitem__ methods; if coded, classes can define what iteration means for their data. **|** ...
First, though, a quick quiz. ###### Test Your Knowledge: Quiz 1. What is the point of coding functions? 2. At what time does Python create a function? 3.
What does a function return if it has no return statement in it? 4. When does the code nested inside the function definition statement run? 5.
What’s wrong with checking the types of objects passed into a function? ###### Test Your Knowledge: Answers 1.
Functions are the most basic way of avoiding code redundancy in Python—factoring code into functions means that we have only one copy of an operation’s code to update in the future.
Functions are also the basic unit of code reuse in Python— wrapping code in functions makes it a reusable tool, callable in a variety of programs.
Finally, functions allow us to divide a complex system into manageable parts, each of which may be developed individually. 2.
A function is created when Python reaches and runs the def statement; this statement creates a function object and assigns it the function’s name.
This normally happens when the enclosing module file is imported by another module (recall that imports run the code in a file from top to bottom, including any defs), but it can also occur when a def is typed interactively or nested in other statements, such as ``` ifs. ``` 3.
A function returns the None object by default if the control flow falls off the end of the function body without running into a `return statement.
Such functions are` usually called with expression statements, as assigning their None results to variables is generally pointless. 4.
The function body (the code nested inside the function definition statement) is run when the function is later called with a call expression. The body runs anew each time the function is called. 5.
Checking the types of objects passed into a function effectively breaks the function’s flexibility, constraining the function to work on specific types only.
Without such checks, the function would likely be able to process an entire range of object types—any objects that support the interface expected by the function will work. (The term interface means the set of methods and expression operators the function’s code runs.) **|** ----- ----- ###### CHAPTER 17 ### Scope...
As we saw, Python’s basic function model is simple to use, but even simple function examples quickly led us to questions about the meaning of variables in our code.
This chapter moves on to present the details behind Python’s scopes—the places where variables are defined and looked up.
As we’ll see, the place where a name is assigned in our code is crucial to determining what the name means.
We’ll also find that scope usage can have a major impact on program maintenance effort; overuse of globals, for example, is a generally bad thing. ###### Python Scope Basics Now that you’re ready to start writing your own functions, we need to get more formal about what names mean in Python.
When you use a name in a program, Python creates, changes, or looks up the name in what is known as a namespace—a place where names live.
When we talk about the search for a name’s value in relation to code, the term _scope refers to a namespace: that is, the location of a name’s assignment in your code_ determines the scope of the name’s visibility to your code. Just about everything related to names, including scope classification, happens at assignme...
As we’ve seen, names in Python spring into existence when they are first assigned values, and they must be assigned before they are used.
Because names are not declared ahead of time, Python uses the location of the assignment of a name to associate it with (i.e., bind it to) a particular namespace.
In other words, the place where you assign a name in your source code determines the namespace it will live in, and hence its scope of visibility. Besides packaging code, functions add an extra namespace layer to your programs— by default, all names assigned inside a function are associated with that function’s namesp...
This means that: - Names defined inside a def can only be seen by the code within that def.
You cannot even refer to such names from outside the function. ----- - Names defined inside a def do not clash with variables outside the def, even if the same names are used elsewhere.
A name X assigned outside a given def (i.e., in a different def or at the top level of a module file) is a completely different variable from a name X assigned inside that def. In all cases, the scope of a variable (where it can be used) is always determined by where it is assigned in your source code and has nothing ...
The net effect is that function scopes help to avoid name clashes in your programs and help to make functions more self-contained program units. ###### Scope Rules Before we started writing functions, all the code we wrote was at the top level of a module (i.e., not nested in a def), so the names we used either lived...
Functions provide nested namespaces (scopes) that localize the names they use, such that names inside a function won’t clash with those outside it (in a module or another function).
Again, functions define a local scope, and modules define a global scope. The two scopes are related as follows: - The enclosing module is a global scope.
Each module is a global scope—that is, a namespace in which variables created (assigned) at the top level of the module file live.
Global variables become attributes of a module object to the outside world but can be used as simple variables within a module file. - The global scope spans a single file only.
Don’t be fooled by the word “global” here—names at the top level of a file are only global to code within that single file. There is really no notion of a single, all-encompassing global file-based scope in **|** ----- Python.
Instead, names are partitioned into modules, and you must always import a module explicitly if you want to be able to use the names its file defines.
When you hear “global” in Python, think “module.” - Each call to a function creates a new local scope.
Every time you call a function, you create a new local scope—that is, a namespace in which the names created inside that function will usually live.
You can think of each `def statement (and` ``` lambda expression) as defining a new local scope, but because Python allows func ``` tions to call themselves to loop (an advanced technique known as recursion), the local scope in fact technically corresponds to a function call—in other words, each call creates a new lo...
Recursion is useful when processing structures whose shapes can’t be predicted ahead of time. - Assigned names are local unless declared global or nonlocal.
By default, all the names assigned inside a function definition are put in the local scope (the namespace associated with the function call).
If you need to assign a name that lives at the top level of the module enclosing the function, you can do so by declaring it in a global statement inside the function.
If you need to assign a name that lives in an enclosing def, as of Python 3.0 you can do so by declaring it in a ``` nonlocal statement. ``` - All other names are enclosing function locals, globals, or built-ins.
Names not assigned a value in the function definition are assumed to be enclosing scope locals (in an enclosing def), globals (in the enclosing module’s namespace), or builtins (in the predefined __builtin__ module Python provides). There are a few subtleties to note here.
First, keep in mind that code typed at the _interactive command prompt follows these same rules.
You may not know it yet, but_ code run interactively is really entered into a built-in module called `__main__; this` module works just like a module file, but results are echoed as you go.
Because of this, interactively created names live in a module, too, and thus follow the normal scope rules: they are global to the interactive session.
You’ll learn more about modules in the next part of this book. Also note that any type of assignment within a function classifies a name as local.
This includes = statements, module names in import, function names in def, function argument names, and so on.
If you assign a name in any way within a def, it will become a local to that function. Conversely, in-place changes to objects do not classify names as locals; only actual name assignments do.
For instance, if the name L is assigned to a list at the top level of a module, a statement L = X within a function will classify L as a local, but L.append(X) will not.
In the latter case, we are changing the list object that L references, not L itself— ``` L is found in the global scope as usual, and Python happily modifies it without requiring ``` a global (or nonlocal) declaration.
As usual, it helps to keep the distinction between names and objects clear: changing an object is not an assignment to a name. **|** ----- ###### Name Resolution: The LEGB Rule If the prior section sounds confusing, it really boils down to three simple rules.
With a ``` def statement: ``` - Name references search at most four scopes: local, then enclosing functions (if any), then global, then built-in. - Name assignments create or change local names by default. - global and nonlocal declarations map assigned names to enclosing module and function scopes. In other wor...
Functions can freely use names assigned in syntactically enclosing functions and the global scope, but they must declare such nonlocals and globals in order to change them. Python’s name-resolution scheme is sometimes called the LEGB rule, after the scope names: - When you use an unqualified name inside a function, ...
If the name is not found during this search, Python reports an error.
As we learned in Chapter 6, names must be assigned before they can be used. - When you assign a name in a function (instead of just referring to it in an expression), Python always creates or changes the name in the local scope, unless it’s declared to be global or nonlocal in that function. - When you assign a nam...
Note that the second scope lookup layer, _E—the scopes of enclosing defs or lambdas—can technically correspond to more than_ one lookup layer.
This case only comes into play when you nest functions within functions, and it is addressed by the nonlocal statement.[*] Also keep in mind that these rules apply only to simple variable names (e.g., spam).
In Parts V and VI, we’ll see that qualified attribute names (e.g., object.spam) live in particular objects and follow a completely different set of lookup rules than those - The scope lookup rule was called the “LGB rule” in the first edition of this book.
The enclosing def “E” layer was added later in Python to obviate the task of passing in enclosing scope names explicitly with default arguments—a topic usually of marginal interest to Python beginners that we’ll defer until later in this chapter. Since this scope is addressed by the nonlocal statement in Python 3.0, I ...
The LEGB scope lookup rule.
When a variable is referenced, Python searches for it in_ _this order: in the local scope, in any enclosing functions’ local scopes, in the global scope, and finally_ _in the built-in scope.
The first occurrence wins. The place in your code where a variable is assigned_ _usually determines its scope.
In Python 3, nonlocal declarations can also force names to be mapped_ _to enclosing function scopes, whether assigned or not._ covered here.
References to attribute names following periods (.) search one or more _objects, not scopes, and may invoke something called “inheritance”; more on this in_ Part VI of this book. ###### Scope Example Let’s look at a larger example that demonstrates scope ideas.