12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Files Generate NamespacesSo, how do files morph into namespaces? The short story is that every name that isassigned a value at the top level of a module file (i.e., not nested in a function or classbody) becomes an attribute of that module.For instance, given an assignment statement such as X=1at the top level of a modulefile M.py, the name X becomes an attribute of M, which we can refer to fromoutside the module as M.X. The name X also becomes a global variable to other codeinside M.py, but we need to explain the notion of module loading and scopes a bitmore formally to understand why:• Module statements run on the first import. The first time a module is importedanywhere in a system, <strong>Python</strong> creates an empty module object, and executes thestatements in the module file one after another, from the top of the file to thebottom.• Top-level assignments create module attributes. During an import, statementsat the top level of the file not nested in a def or class that assign names (e.g., =,def) create attributes of the module object; assigned names are stored in themodule’s namespace.• Module namespaces can be accessed via the attribute _ _dict_ _ or dir(M). Modulenamespaces created by imports are dictionaries; they may be accessed throughthe built-in _ _dict_ _ attribute associated with module objects and may beinspected with the dir function. The dir function is roughly equivalent to thesorted keys list of an object’s _ _dict_ _ attribute, but it includes inherited namesfor classes, may not be complete, and is prone to changing from release to release.• Modules are a single scope (local is global). As we saw in Chapter 16, names atthe top level of a module follow the same reference/assignment rules as names ina function, but the local and global scopes are the same (more formally, they followthe LEGB scope rule we met in Chapter 16, but without the L and E lookuplayers). But, in modules, the module scope becomes an attribute dictionary of amodule object after the module has been loaded. Unlike with functions (wherethe local namespace exists only while the function runs), a module file’s scopebecomes a module object’s attribute namespace and lives on after the import.Here’s a demonstration of these ideas. Suppose we create the following module filein a text editor and call it module2.py:print 'starting to load...'import sysname = 42def func( ): passclass klass: passprint 'done loading.'Module Namespaces | 405

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!