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.

For example, presently, a statement of the form:from .spam import namemeans “from a module named spam located in the same package that this statement iscontained in, import the variable name.” A similar statement without the leading dotwill still default to the current relative-then-absolute search path order, unless astatement of the following form is included in the importing file:from _ _future_ _ import absolute_import # Required until 2.7?If present, this statement enables the future absolute default path change. It causesall imports without extra dots to skip the relative components of the module importsearch path, and look instead in the absolute directories that sys.path contains. Forinstance, when absolute imports are thus enabled, a statement of the following formwill always find the standard library’s string module, instead of a module of thesame name in the package:import string# Always finds standard lib's versionWithout the from _ _future_ _ statement, if there’s a string module in the package, itwill be imported instead. To get the same behavior when the future absolute importchange is enabled, run a statement of the following form (which also works in<strong>Python</strong> today) to force a relative import:from . import string# Searches this package firstNote that leading dots can only be used with the from statement, not the importstatement. The import modname statement form still performs relative imports today,but these will become absolute in <strong>Python</strong> 2.7.Other dot-based relative reference patterns are possible, too. Given a package namedmypkg, the following alternative import forms used by code within the package workas described:from .string import name1, name2from . import stringfrom .. import string# Imports names from mypkg.string# Imports mypkg.string# Imports string from parent directoryTo understand these latter forms better, we need to understand the rationale behindthis change.Why Relative Imports?This feature is designed to allow scripts to resolve ambiguities that can arise when asame-named file appears in multiple places on the module search path. Consider thefollowing package directory:mypkg\_ _init_ _.pymain.pystring.py432 | Chapter 21: Advanced Module Topics

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

Saved successfully!

Ooh no, something went wrong!