12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

As one consequence, because top-level code in a module file is usually executed onlyonce, you can use it to initialize variables. Consider the file simple.py, for example:print 'hello'spam = 1# Initialize variableIn this example, the print and = statements run the first time the module isimported, and the variable spam is initialized at import time:% python>>> import simple # First import: loads and runs file's codehello>>> simple.spam # Assignment makes an attribute1Second and later imports don’t rerun the module’s code; they just fetch the alreadycreated module object from <strong>Python</strong>’s internal modules table. Thus, the variable spamis not reinitialized:>>> simple.spam = 2 # Change attribute in module>>> import simple # Just fetches already loaded module>>> simple.spam # Code wasn't rerun: attribute unchanged2Of course, sometimes you really want a module’s code to be rerun on a subsequentimport. We’ll see how to do this with the reload built-in function later in this chapter.import and from Are AssignmentsJust like def, import and from are executable statements, not compile-time declarations.They may be nested in if tests, appear in function defs, and so on, and theyare not resolved or run until <strong>Python</strong> reaches them while executing your program. Inother words, imported modules and names are not available until their associatedimport or from statements run. Also, like def, import and from are implicit assignments:• import assigns an entire module object to a single name.• from assigns one or more names to objects of the same names in another module.All the things we’ve already discussed about assignment apply to module access, too.For instance, names copied with a from become references to shared objects; as withfunction arguments, reassigning a fetched name has no effect on the module fromwhich it was copied, but changing a fetched mutable object can change it in the modulefrom which it was imported. To illustrate, consider the following file, small.py:x = 1y = [1, 2]% python>>> from small import x, y # Copy two names out>>> x = 42 # Changes local x only>>> y[0] = 42 # Changes shared mutable in-placeModule Usage | 401

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

Saved successfully!

Ooh no, something went wrong!