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.

Probably the best real-world advice here is to generally prefer import to from for simplemodules, to explicitly list the variables you want in most from statements, and tolimit the from * form to just one import per file. That way, any undefined names canbe assumed to live in the module referenced with the from *. Some care is requiredwhen using the from statement, but armed with a little knowledge, most programmersfind it to be a convenient way to access modules.When import is requiredThe only time you really must use import instead of from is when you must use thesame name defined in two different modules. For example, if two files define thesame name differently:# M.pydef func( ):...do something...# N.pydef func( ):...do something else...and you must use both versions of the name in your program, the from statement willfail—you can only have one assignment to the name in your scope:# O.pyfrom M import funcfrom N import funcfunc( )# This overwites the one we got from M# Calls N.func onlyAn import will work here, though, because including the name of the enclosing modulemakes the two names unique:# O.pyimport M, NM.func( )N.func( )# Get the whole modules, not their names# We can call both names now# The module names make them uniqueThis case is unusual enough that you’re unlikely to encounter it very often in practice.Module NamespacesModules are probably best understood as simply packages of names—i.e., places todefine names you want to make visible to the rest of a system. Technically, modulesusually correspond to files, and <strong>Python</strong> creates a module object to contain all thenames assigned in a module file. But, in simple terms, modules are just namespaces(places where names are created), and the names that live in a module are called itsattributes. We’ll explore how all this works in this section.404 | Chapter 19: Module Coding Basics

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

Saved successfully!

Ooh no, something went wrong!