Oct 9, 2008

Learning python 读书笔记 PART 5

PART 5: MODULES
Chapter 15. Modules: The Big Picture
a.code reuse b.System namespace partitioning c.Implementing shared services or data
Python Program Architecture
import and from statements execute and load another file at runtime
How Imports Work
Find it --> Compile it(Maybe) --> Run it
Find it
The module search path:

a. home directory of the top-level file
b. PYTHONPATH directories (if set)
c. Standard library directories
d. The contents of any .pth files (if present)
current working directory
sys.path: the actual search path, is configured by Python at program startup
Compile it
.py & .pyc
Run it
import operation executes the byte code of the module
def: run at import time to create functions

Chapter 16. Module Coding Basics
Module Creation
module --import--> variables (name)
they should follow the normal variable name rules
<directory>m.<extension>
import a --> a.b
from a import b --> b
from a import * --> b
imports happen only once
Later imoort operations simply fetch an already loaded module object.
def, import, from are executable statements
import and from are assignments!
from small import x,y
x = 42 #change my x only
import small
small.x = 42 #change x in other module
equivalence from module import name
is euqal to
import module
name = module.name
del module
Module Namespace
attributes --namespace--> module ojbect
Module statements run on the first imoort: create an empty module object and execute the statements inside the module
Top-level assignments create module attributes
Module namespace: attribute__dict__, or dir(M) --> a directory object
Attribute Name Qualification
Import Versus Scope: function <--> module
Namespace Nesting
Reloading Modules
reload currently only works on modules written in Python; C extension modules cannot.
Reload Basics:
Reloads impact all clients that use import to fetch modules
Reloads impact future from clients only

Chapter 17. Module Package
Package import Basics
import dir1.dir2.mod --> dir0/dir1/dir2/mod
__init__.py
package initialization: run automatically
module namespace initialization
from* statement behavior
from Versus import with packages
import dir1.dir2.mod as mod #short name
from dir1.dir2 import mod

Chapter 18. Advanced Module Topics
_X: prevent being copied out in from* statement, but still not import statement
__all__: from* will only copy out those names listed in the __all__ list
can be used in __init__.py
__all__ = ["b","c"]
from __future__ import featurename
__name__ and __main__
run at top level: __name__ <-- "__main__"
if __name__ == '__main__'
tester()
from module import longname as name
Module Design Concept
you're always in a module in python
Minimize module coupling: global variables
Maximize module cohesion: unified purpose
Module should raraly change other module's variables

0 comments: