Absoluterelative imports since [PEP

• Feature must be enabled by: from__future__import absolute_import: will probably be adopted in 2.7.

• Imports are normally relative: modules are searched first in the current directory/package, and then in the builtin modules, resulting in possible ambiguities (e.g. masking a builtin symbol).

• When the new feature is enabled:

o import x will look up for module X in sys.path first (absolute import).

o import .x (with a dot) will still search for X in the current package first, then in builtins (relative import). o import . .x will search for X in the package containing the current one, etc...

Packages (>1.5): a package is a name space which maps to a directory including module(s) and the special initialization module_init_.py (possibly empty).

Packages/directories can be nested. You address a module's symbol via [package. [package...] .module.symbol. [1.51: On Mac & Windows, the case of module file names must now match the case as used in the import statement]

Name space statements



import module1 [as name1] [, module2]*

Imports modules. Members of module must be referred to by qualifying with [package.]module name, e.g.:

import sys; print sys.argv import package1.subpackage.module package!.subpackage.module.foo()

modulei renamed as namei, if supplied.

from module import namei [as othernamei][, name2]*

Imports names from module module in current namespace.

from sys import argv; print argv from packagei import module; module.foo()

from packagei.module import foo; foo()

namei renamed as othernamei, if supplied.

[2.4] You can now put parentheses around the list of names in a from module import names statement (PEP 328).

from module import *

Imports all names in module, except those starting with "_". Use sparsely, beware of name clashes!

from sys import *; print argv from package.module import *; print x

Only legal at the top level of a module.

If module defines an_all__attribute, only names listed in_all__will be imported.

NB: "from package import *" only imports the symbols defined in the package's_init_.py file, not those in the package's modules !

global namei [, name2]

Names are from global scope (usually meaning from module) rather than local (usually meaning only in function).

E.g. in function without global statements, assuming "x" is name that hasn't been used in function or module so far:

- Try to write to "x" -> creates "x" local to function

If "x" not defined in fct, but is in module, then: - Try to read from "x", gets value from module

- Try to write to "x", creates "x" local to fct

But note "x[0] = 3" starts with search for "x", will use to global "x" if no local "x".

Was this article helpful?

0 0

Post a comment