Text
stringlengths
1
9.41k
Such a utility function could call itself recursively to navigate arbitrarily shaped import dependency chains.
Module __dict__ attributes were introduced earlier in, the section “Modules Are Objects: Metaprograms” on page 591, and the ``` type call was presented in Chapter 9; we just need to combine the two tools. ``` **|** ----- For example, the module reloadall.py listed next has a reload_all function that automatically r...
It uses a dictionary to keep track of already reloaded modules, recursion to walk the import chains, and the standard library’s ``` types module, which simply predefines type results for built-in types.
The visited ``` dictionary technique works to avoid cycles here when imports are recursive or redundant, because module objects can be dictionary keys (as we learned in Chapter 5, a set would offer similar functionality if we use visited.add(module) to insert): ``` """ reloadall.py: transitively reload nested modu...
When the file runs standalone, its self-test code will test itself—it has to import itself because its own name is not defined in the file without an import (this code works in both 3.0 and 2.6 and prints identical output, because we’ve used + instead of a comma in the print): ``` C:\misc> c:\Python30\python reloadal...
Notice how os is imported by tkinter, but tkinter reaches sys before os can (if you want to test this on Python 2.6, substitute Tkinter for tkinter): **|** ----- ``` >>> from reloadall import reload_all >>> import os, tkinter >>> reload_all(os) reloading os reloading copyreg reloading ntpath reloading...
All of this will become clearer when you start writing bigger Python systems, but here are a few general ideas to keep in mind: - You’re always in a module in Python.
There’s no way to write code that doesn’t live in some module.
In fact, code typed at the interactive prompt really goes in a built-in module called `__main__; the only unique things about the interactive` prompt are that code runs and is discarded immediately, and expression results are printed automatically. - Minimize module coupling: global variables.
Like functions, modules work best if they’re written to be closed boxes.
As a rule of thumb, they should be as independent of global variables used within other modules as possible, except for functions and classes imported from them. - Maximize module cohesion: unified purpose.
You can minimize a module’s couplings by maximizing its cohesion; if all the components of a module share a general purpose, you’re less likely to depend on external names. - Modules should rarely change other modules’ variables.
We illustrated this with code in Chapter 17, but it’s worth repeating here: it’s perfectly OK to use globals defined in another module (that’s how clients import services, after all), but changing globals in another module is often a symptom of a design problem. There are exceptions, of course, but you should try to co...
Modules contain variables, functions, classes, and other modules (if imported).
Functions have local variables of their own, as do classes—i.e., objects that live within modules, which we’ll meet next in Chapter 25. **|** ----- _Figure 24-1. Module execution environment.
Modules are imported, but modules also import and use_ _other modules, which may be coded in Python or another language such as C.
Modules in turn contain_ _variables, functions, and classes to do their work, and their functions and classes may contain variables_ _and other items of their own.
At the top, though, programs are just sets of modules._ ###### Module Gotchas In this section, we’ll take a look at the usual collection of boundary cases that make life interesting for Python beginners.
Some are so obscure that it was hard to come up with examples, but most illustrate something important about the language. ###### Statement Order Matters in Top-Level Code When a module is first imported (or reloaded), Python executes its statements one by one, from the top of the file to the bottom.
This has a few subtle implications regarding forward references that are worth underscoring here: - Code at the top level of a module file (not nested in a function) runs as soon as Python reaches it during an import; because of that, it can’t reference names assigned lower in the file. - Code inside a function bod...
Here’s an example that illustrates forward reference: **|** ----- ``` func1() # Error: "func1" not yet assigned def func1(): print(func2()) # Okay: "func2" looked up later func1() # Error: "func2" not yet assigned def func2(): return "Hello" func1() # ...
The first call to func1 fails because the func1 def hasn’t run yet.
The call to func2 inside func1 works as long as func2’s def has been reached by the time func1 is called (it hasn’t when the second top-level func1 call is run).
The last call to `func1 at the bottom of the file works because` `func1 and` `func2 have both been` assigned. Mixing defs with top-level code is not only hard to read, it’s dependent on statement ordering.
As a rule of thumb, if you need to mix immediate code with defs, put your ``` defs at the top of the file and your top-level code at the bottom.
That way, your functions ``` are guaranteed to be defined and assigned by the time code that uses them runs. ###### from Copies Names but Doesn’t Link Although it’s commonly used, the from statement is the source of a variety of potential gotchas in Python.
The from statement is really an assignment to names in the importer’s scope—a name-copy operation, not a name aliasing.
The implications of this are the same as for all assignments in Python, but they’re subtle, especially given that the code that shares the objects lives in different files.
For instance, suppose we define the following module, nested1.py: _# nested1.py_ ``` X = 99 def printer(): print(X) ``` If we import its two names using from in another module, nested2.py, we get copies of those names, not links to them.
Changing a name in the importer resets only the binding of the local version of that name, not the name in nested1.py: _# nested2.py_ ``` from nested1 import X, printer # Copy names out X = 88 # Changes my "X" only! printer() # nested1's X is still 99 % python nested2.py 99 ``` **|...
Qualification directs Python to a name in the module object, rather than a name in the importer, nested3.py: _# nested3.py_ ``` import nested1 # Get module as a whole nested1.X = 88 # OK: change nested1's X nested1.printer() % python nested3.py 88 ###### from * Can Obscure the Meaning of V...
Because you don’t list the variables you want when using the from module import * statement form, it can accidentally overwrite names you’re already using in your scope.
Worse, it can make it difficult to determine where a variable comes from.
This is especially true if the from * form is used on more than one imported file. For example, if you use from * on three modules, you’ll have no way of knowing what a raw function call really means, short of searching all three external module files (all of which may be in other directories): `>>> from module1 impo...
.
. ``` `>>> func()` _# Huh???_ The solution again is not to do this: try to explicitly list the attributes you want in your ``` from statements, and restrict the from * form to at most one imported module per file. ``` That way, any undefined names must by deduction be in the module named in the single from *.
You can avoid the issue altogether if you always use import instead of ``` from, but that advice is too harsh; like much else in programming, from is a convenient ``` tool if used wisely.
Even this example isn’t an absolute evil—it’s OK for a program to use this technique to collect names in a single space for convenience, as long as it’s well known. ###### reload May Not Impact from Imports Here’s another from-related gotcha: as discussed previously, because from copies (assigns) names when run, ther...
Names imported with from simply become references to objects, which happen to have been referenced by the same names in the importee when the from ran. **|** ----- Because of this behavior, reloading the importee has no effect on clients that import its names using from.
That is, the client’s names will still reference the original objects fetched with from, even if the names in the original module are later reset: ``` from module import X # X may not reflect any module reloads! .
.
. from imp import reload reload(module) # Changes module, but not my names X # Still references old object ``` To make reloads more effective, use `import and name qualification instead of` `from.` Because qualifications always go back to the module, they will find the new bindings of module...
.
. from imp import reload reload(module) # Changes module in-place module.X # Get current X: reflects module reloads ###### reload, from, and Interactive Testing ``` In fact, the prior gotcha is even more subtle than it appears.
Chapter 3 warned that it’s usually better not to launch programs with imports and reloads because of the complexities involved. Things get even worse when from is brought into the mix.
Python beginners often stumble onto its issues in scenarios like the one outlined next.
Say that after opening a module file in a text edit window, you launch an interactive session to load and test your module with from: ``` from module import function function(1, 2, 3) ``` Finding a bug, you jump back to the edit window, make a change, and try to reload the module this way: ``` from imp import re...
To refer to the module in a reload, you have to first load it with an import ``` statement at least once: ``` from imp import reload import module reload(module) function(1, 2, 3) ``` However, this doesn’t quite work either—reload updates the module object, but as discussed in the preceding section, names lik...
To really get the new function, you must refer to it as module.function after the reload, or rerun the from: **|** ----- ``` from imp import reload import module reload(module) from module import function # Or give up and use module.function() function(1, 2, 3) ``` Now, the new version of the function...
This is complex enough to trip up even an expert once ``` in a while.
(In fact, the situation has gotten even worse in Python 3.0, because you must also remember to import reload itself!) The short story is that you should not expect reload and from to play together nicely. The best policy is not to combine them at all—use reload with import, or launch your programs other ways, as sugge...
Because imports execute a file’s statements from top to bottom, you need to be careful when using modules that import each other (known as recursive imports).
Because the statements in a module may not all have been run when it imports another module, some of its names may not yet exist. If you use `import to fetch the module as a whole, this may or may not matter; the` module’s names won’t be accessed until you later use qualification to fetch their values. But if you use ...
recur1 assigns a name X, and then imports recur2 before assigning the name Y.
At this point, recur2 can fetch ``` recur1 as a whole with an import (it already exists in Python’s internal modules table), ``` but if it uses from, it will be able to see only the name X; the name Y, which is assigned below the import in recur1, doesn’t yet exist, so you get an error: _# recur1.py_ ``` X = 1 im...
Don’t use from in recursive imports (no, really!).
Python won’t get stuck in a cycle if you do, but your programs will once again be dependent on the order of the statements in the modules. There are two ways out of this gotcha: - You can usually eliminate import cycles like this by careful design—maximizing cohesion and minimizing coupling are good first steps. -...
We studied data hiding techniques, enabling new language features with the __future__ module, the ``` __name__ usage mode variable, transitive reloads, importing by name strings, and more. ``` We also explored and summarized module design issues and looked at common mistakes related to modules to help you avoid them i...
Much of what we’ve covered in the last few chapters will apply there, too—classes live in modules and are namespaces as well, but they add an extra component to attribute lookup called inheritance search.
As this is the last chapter in this part of the book, however, before we dive into that topic, be sure to work through this part’s set of lab exercises.
And before that, here is this chapter’s quiz to review the topics covered here. ###### Test Your Knowledge: Quiz 1.
What is significant about variables at the top level of a module whose names begin with a single underscore? 2.
What does it mean when a module’s __name__ variable is the string "__main__"? **|** ----- 3. If the user interactively types the name of a module to test, how can you import it? 4.
How is changing sys.path different from setting PYTHONPATH to modify the module search path? 5.
If the module __future__ allows us to import from the future, can we also import from the past? ###### Test Your Knowledge: Answers 1.
Variables at the top level of a module whose names begin with a single underscore are not copied out to the importing scope when the from * statement form is used. They can still be accessed by an import or the normal from statement form, though. 2.
If a module’s __name__ variable is the string "__main__", it means that the file is being executed as a top-level script instead of being imported from another file in the program.
That is, the file is being used as a program, not a library. 3.
User input usually comes into a script as a string; to import the referenced module given its string name, you can build and run an import statement with exec, or pass the string name in a call to the __import__ function. 4.
Changing `sys.path only affects one running program, and is temporary—the` change goes away when the program ends.
PYTHONPATH settings live in the operating system—they are picked up globally by all programs on a machine, and changes to these settings endure after programs exit. 5.
No, we can’t import from the past in Python.
We can install (or stubbornly use) an older version of the language, but the latest Python is generally the best Python. ###### Test Your Knowledge: Part V Exercises See “Part V, Modules” on page 1119 in Appendix B for the solutions. 1.
Import basics. Write a program that counts the lines and characters in a file (similar in spirit to _wc on Unix).
With your text editor, code a Python module called_ _mymod.py that exports three top-level names:_ - A countLines(name) function that reads an input file and counts the number of lines in it (hint: file.readlines does most of the work for you, and len does the rest). - A countChars(name) function that reads an in...
Such a filename generally might be passed in, hardcoded, input with the input built-in function, or pulled from a command line via the sys.argv list shown in this chapter’s _formats.py example; for now, you can assume it’s a_ passed-in function argument. **|** ----- All three mymod functions should expect a filenam...
If you type more than two or three lines per function, you’re working much too hard— use the hints I just gave! Next, test your module interactively, using import and attribute references to fetch your exports.
Does your PYTHONPATH need to include the directory where you created _mymod.py? Try running your module on itself: e.g., test("mymod.py").
Note that_ ``` test opens the file twice; if you’re feeling ambitious, you may be able to improve ``` this by passing an open file object into the two count functions (hint: ``` file.seek(0) is a file rewind). ``` 2.
from/from *. Test your mymod module from exercise 1 interactively by using from to load the exports directly, first by name, then using the `from * variant to fetch` everything. 3. __main__.
Add a line in your mymod module that calls the test function automatically only when the module is run as a script, not when it is imported.
The line you add will probably test the value of __name__ for the string "__main__", as shown in this chapter.
Try running your module from the system command line; then, import the module and test its functions interactively. Does it still work in both modes? 4. Nested imports.
Write a second module, myclient.py, that imports mymod and tests its functions; then run myclient from the system command line.
If myclient uses ``` from to fetch from mymod, will mymod’s functions be accessible from the top level of myclient? What if it imports with import instead?
Try coding both variations in myclient and test interactively by importing myclient and inspecting its __dict__ ``` attribute. 5. Package imports. Import your file from a package.
Create a subdirectory called _mypkg nested in a directory on your module import search path, move the_ _mymod.py module file you created in exercise 1 or 3 into the new directory, and_ try to import it with a package import of the form import mypkg.mymod. You’ll need to add an __init__.py file in the directory your mod...
The package directory you create can be simply a subdirectory of the one you’re working in; if it is, it will be found via the home directory component of the search path, and you won’t have to configure your path.
Add some code to your __init__.py, and see if it runs on each import. 6. Reloads.
Experiment with module reloads: perform the tests in Chapter 22’s _changer.py example, changing the called function’s message and/or behavior re-_ peatedly, without stopping the Python interpreter.
Depending on your system, you might be able to edit changer in another window, or suspend the Python interpreter and edit in the same window (on Unix, a Ctrl-Z key combination usually suspends the current process, and an fg command later resumes it). **|** ----- 7.
Circular imports.[‡] In the section on recursive import gotchas, importing `recur1` raised an error.
But if you restart Python and import recur2 interactively, the error doesn’t occur—test this and see for yourself. Why do you think it works to import ``` recur2, but not recur1?
(Hint: Python stores new modules in the built-in sys.modules table—a dictionary—before running their code; later imports fetch ``` the module from this table first, whether the module is “complete” yet or not.) Now, try running recur1 as a top-level script file: python recur1.py.
Do you get the same error that occurs when recur1 is imported interactively? Why?
(Hint: when modules are run as programs, they aren’t imported, so this case has the same effect as importing recur2 interactively; recur2 is the first module imported.) What happens when you run recur2 as a script? ‡ Note that circular imports are extremely rare in practice.
On the other hand, if you can understand why they are a potential problem, you know a lot about Python’s import semantics. **|** ----- ----- ##### PART VI ## Classes and OOP ----- ----- ###### CHAPTER 25 ### OOP: The Big Picture So far in this book, we’ve been using the term “object” generically.
Really, the code written up to this point has been object-based—we’ve passed objects around our scripts, used them in expressions, called their methods, and so on.
For our code to qualify as being truly object-oriented (OO), though, our objects will generally need to also participate in something called an inheritance hierarchy. This chapter begins our exploration of the Python class—a device used to implement new kinds of objects in Python that support inheritance.
Classes are Python’s main object-oriented programming (OOP) tool, so we’ll also look at OOP basics along the way in this part of the book.