rest25/tutorial/modules.rst => rest262/tutorial/modules.rst
98There is even a variant to import all names that a module defines::
99
100   >>> from fibo import *
101   >>> fib(500)
102   1 1 2 3 5 8 13 21 34 55 89 144 233 377
103
104This imports all names except those beginning with an underscore (``_``).
105
n106+.. note::
107+ 
108+   For efficiency reasons, each module is only imported once per interpreter
109+   session.  Therefore, if you change your modules, you must restart the
110+   interpreter -- or, if it's just one module you want to test interactively,
111+   use :func:`reload`, e.g. ``reload(modulename)``.
112+ 
113+ 
114+.. _tut-modulesasscripts:
115+ 
116+Executing modules as scripts
117+----------------------------
118+ 
119+When you run a Python module with ::
120+ 
121+   python fibo.py <arguments>
122+ 
123+the code in the module will be executed, just as if you imported it, but with
124+the ``__name__`` set to ``"__main__"``.  That means that by adding this code at
125+the end of your module::
126+ 
127+   if __name__ == "__main__":
128+       import sys
129+       fib(int(sys.argv[1]))
130+ 
131+you can make the file usable as a script as well as an importable module,
132+because the code that parses the command line only runs if the module is
133+executed as the "main" file::
134+ 
135+   $ python fibo.py 50
136+   1 1 2 3 5 8 13 21 34
137+ 
138+If the module is imported, the code is not run::
139+ 
140+   >>> import fibo
141+   >>>
142+ 
143+This is often used either to provide a convenient user interface to a module, or
144+for testing purposes (running the module as a script executes a test suite).
145+ 
106
107.. _tut-searchpath:
108
109The Module Search Path
110----------------------
111
112.. index:: triple: module; search; path
113
114When a module named :mod:`spam` is imported, the interpreter searches for a file
115named :file:`spam.py` in the current directory, and then in the list of
116directories specified by the environment variable :envvar:`PYTHONPATH`.  This
117has the same syntax as the shell variable :envvar:`PATH`, that is, a list of
118directory names.  When :envvar:`PYTHONPATH` is not set, or when the file is not
119found there, the search continues in an installation-dependent default path; on
120Unix, this is usually :file:`.:/usr/local/lib/python`.
121
n122-Actually, modules are searched in the list of directories given by the  variable
n162+Actually, modules are searched in the list of directories given by the variable
123-``sys.path`` which is initialized from the directory  containing the input
163+``sys.path`` which is initialized from the directory containing the input script
124-script (or the current directory), :envvar:`PYTHONPATH` and the installation-
164+(or the current directory), :envvar:`PYTHONPATH` and the installation- dependent
125-dependent default.  This allows Python programs that know what they're doing to
165+default.  This allows Python programs that know what they're doing to modify or
126-modify or replace the  module search path.  Note that because the directory
166+replace the module search path.  Note that because the directory containing the
127-containing the script being run is on the search path, it is important that the
167+script being run is on the search path, it is important that the script not have
128-script not have the same name as a standard module, or Python will attempt to
168+the same name as a standard module, or Python will attempt to load the script as
129-load the script as a module when that module is imported. This will generally be
169+a module when that module is imported. This will generally be an error.  See
130-an error.  See section :ref:`tut-standardmodules`, "Standard Modules," for more
170+section :ref:`tut-standardmodules` for more information.
131-information.
132
133
134"Compiled" Python files
135-----------------------
136
137As an important speed-up of the start-up time for short programs that use a lot
138of standard modules, if a file called :file:`spam.pyc` exists in the directory
n139-where :file:`spam.py` is found, this is assumed to contain an already-"byte-
n178+where :file:`spam.py` is found, this is assumed to contain an
140-compiled" version of the module :mod:`spam`. The modification time of the
179+already-"byte-compiled" version of the module :mod:`spam`. The modification time
141-version of :file:`spam.py` used to create :file:`spam.pyc` is recorded in
180+of the version of :file:`spam.py` used to create :file:`spam.pyc` is recorded in
142:file:`spam.pyc`, and the :file:`.pyc` file is ignored if these don't match.
143
144Normally, you don't need to do anything to create the :file:`spam.pyc` file.
145Whenever :file:`spam.py` is successfully compiled, an attempt is made to write
146the compiled version to :file:`spam.pyc`.  It is not an error if this attempt
147fails; if for any reason the file is not written completely, the resulting
148:file:`spam.pyc` file will be recognized as invalid and thus ignored later.  The
149contents of the :file:`spam.pyc` file are platform independent, so a Python
150module directory can be shared by machines of different architectures.
151
152Some tips for experts:
153
154* When the Python interpreter is invoked with the :option:`-O` flag, optimized
155  code is generated and stored in :file:`.pyo` files.  The optimizer currently
156  doesn't help much; it only removes :keyword:`assert` statements.  When
n157-  :option:`-O` is used, *all* bytecode is optimized; ``.pyc`` files are ignored
n196+  :option:`-O` is used, *all* :term:`bytecode` is optimized; ``.pyc`` files are
158-  and ``.py`` files are compiled to optimized bytecode.
197+  ignored and ``.py`` files are compiled to optimized bytecode.
159
160* Passing two :option:`-O` flags to the Python interpreter (:option:`-OO`) will
161  cause the bytecode compiler to perform optimizations that could in some rare
162  cases result in malfunctioning programs.  Currently only ``__doc__`` strings are
163  removed from the bytecode, resulting in more compact :file:`.pyo` files.  Since
164  some programs may rely on having these available, you should only use this
165  option if you know what you're doing.
166
178
179* It is possible to have a file called :file:`spam.pyc` (or :file:`spam.pyo`
180  when :option:`-O` is used) without a file :file:`spam.py` for the same module.
181  This can be used to distribute a library of Python code in a form that is
182  moderately hard to reverse engineer.
183
184  .. index:: module: compileall
185
n186-* The module :mod:`compileall` (XXX reference: ../lib/module-compileall.html)
n225+* The module :mod:`compileall` can create :file:`.pyc` files (or :file:`.pyo`
187-  can create :file:`.pyc` files (or :file:`.pyo` files when :option:`-O` is used)
226+  files when :option:`-O` is used) for all modules in a directory.
188-  for all modules in a directory.
189- 
190-  .. % 
191
192
193.. _tut-standardmodules:
194
195Standard Modules
196================
197
198.. index:: module: sys
199
200Python comes with a library of standard modules, described in a separate
n201-document, the Python Library Reference (XXX reference: ../lib/lib.html)
n237+document, the Python Library Reference ("Library Reference" hereafter).  Some
202-("Library Reference" hereafter).  Some modules are built into the interpreter;
238+modules are built into the interpreter; these provide access to operations that
203-these provide access to operations that are not part of the core of the language
239+are not part of the core of the language but are nevertheless built in, either
204-but are nevertheless built in, either for efficiency or to provide access to
240+for efficiency or to provide access to operating system primitives such as
205-operating system primitives such as system calls.  The set of such modules is a
241+system calls.  The set of such modules is a configuration option which also
206-configuration option which also depends on the underlying platform  For example,
242+depends on the underlying platform For example, the :mod:`winreg` module is only
207-the :mod:`amoeba` module is only provided on systems that somehow support Amoeba
243+provided on Windows systems. One particular module deserves some attention:
208-primitives.  One particular module deserves some attention: :mod:`sys` (XXX
244+:mod:`sys`, which is built into every Python interpreter.  The variables
209-reference: ../lib/module-sys.html), which is built into every  Python
245+``sys.ps1`` and ``sys.ps2`` define the strings used as primary and secondary
210-interpreter.  The variables ``sys.ps1`` and ``sys.ps2`` define the strings used
246+prompts::
211-as primary and secondary prompts:
212- 
213-.. % 
214- 
215-::
216
217   >>> import sys
218   >>> sys.ps1
219   '>>> '
220   >>> sys.ps2
221   '... '
222   >>> sys.ps1 = 'C> '
223   C> print 'Yuck!'
245The built-in function :func:`dir` is used to find out which names a module
246defines.  It returns a sorted list of strings::
247
248   >>> import fibo, sys
249   >>> dir(fibo)
250   ['__name__', 'fib', 'fib2']
251   >>> dir(sys)
252   ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
n253-    '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 
n284+    '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
254    'builtin_module_names', 'byteorder', 'callstats', 'copyright',
255    'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
256    'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
257    'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
258    'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
259    'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
260    'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
261    'version', 'version_info', 'warnoptions']
278
279   >>> import __builtin__
280   >>> dir(__builtin__)
281   ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
282    'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
283    'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
284    'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
285    'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
n286-    'NotImplementedError', 'OSError', 'OverflowError', 
n317+    'NotImplementedError', 'OSError', 'OverflowError',
287    'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
288    'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
289    'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
290    'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
291    'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
292    'UserWarning', 'ValueError', 'Warning', 'WindowsError',
293    'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
294    '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
323:file:`.aiff`, :file:`.au`), so you may need to create and maintain a growing
324collection of modules for the conversion between the various file formats.
325There are also many different operations you might want to perform on sound data
326(such as mixing, adding echo, applying an equalizer function, creating an
327artificial stereo effect), so in addition you will be writing a never-ending
328stream of modules to perform these operations.  Here's a possible structure for
329your package (expressed in terms of a hierarchical filesystem)::
330
n331-   Sound/                          Top-level package
n362+   sound/                          Top-level package
332         __init__.py               Initialize the sound package
n333-         Formats/                  Subpackage for file format conversions
n364+         formats/                  Subpackage for file format conversions
334                 __init__.py
335                 wavread.py
336                 wavwrite.py
337                 aiffread.py
338                 aiffwrite.py
339                 auread.py
340                 auwrite.py
341                 ...
n342-         Effects/                  Subpackage for sound effects
n373+         effects/                  Subpackage for sound effects
343                 __init__.py
344                 echo.py
345                 surround.py
346                 reverse.py
347                 ...
n348-         Filters/                  Subpackage for filters
n379+         filters/                  Subpackage for filters
349                 __init__.py
350                 equalizer.py
351                 vocoder.py
352                 karaoke.py
353                 ...
354
355When importing the package, Python searches through the directories on
356``sys.path`` looking for the package subdirectory.
360such as ``string``, from unintentionally hiding valid modules that occur later
361on the module search path. In the simplest case, :file:`__init__.py` can just be
362an empty file, but it can also execute initialization code for the package or
363set the ``__all__`` variable, described later.
364
365Users of the package can import individual modules from the package, for
366example::
367
n368-   import Sound.Effects.echo
n399+   import sound.effects.echo
369
n370-This loads the submodule :mod:`Sound.Effects.echo`.  It must be referenced with
n401+This loads the submodule :mod:`sound.effects.echo`.  It must be referenced with
371its full name. ::
372
n373-   Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
n404+   sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)
374
375An alternative way of importing the submodule is::
376
n377-   from Sound.Effects import echo
n408+   from sound.effects import echo
378
379This also loads the submodule :mod:`echo`, and makes it available without its
380package prefix, so it can be used as follows::
381
382   echo.echofilter(input, output, delay=0.7, atten=4)
383
384Yet another variation is to import the desired function or variable directly::
385
n386-   from Sound.Effects.echo import echofilter
n417+   from sound.effects.echo import echofilter
387
388Again, this loads the submodule :mod:`echo`, but this makes its function
389:func:`echofilter` directly available::
390
391   echofilter(input, output, delay=0.7, atten=4)
392
393Note that when using ``from package import item``, the item can be either a
394submodule (or subpackage) of the package, or some  other name defined in the
405
406.. _tut-pkg-import-star:
407
408Importing \* From a Package
409---------------------------
410
411.. index:: single: __all__
412
n413-Now what happens when the user writes ``from Sound.Effects import *``?  Ideally,
n444+Now what happens when the user writes ``from sound.effects import *``?  Ideally,
414one would hope that this somehow goes out to the filesystem, finds which
415submodules are present in the package, and imports them all.  Unfortunately,
n416-this operation does not work very well on Mac and Windows platforms, where the
n447+this operation does not work very well on Windows platforms, where the
417filesystem does not always have accurate information about the case of a
418filename!  On these platforms, there is no guaranteed way to know whether a file
419:file:`ECHO.PY` should be imported as a module :mod:`echo`, :mod:`Echo` or
420:mod:`ECHO`.  (For example, Windows 95 has the annoying practice of showing all
421file names with a capitalized first letter.)  The DOS 8+3 filename restriction
422adds another interesting problem for long module names.
n423- 
424-.. % The \code{__all__} Attribute
425
426The only solution is for the package author to provide an explicit index of the
427package.  The import statement uses the following convention: if a package's
428:file:`__init__.py` code defines a list named ``__all__``, it is taken to be the
429list of module names that should be imported when ``from package import *`` is
430encountered.  It is up to the package author to keep this list up-to-date when a
431new version of the package is released.  Package authors may also decide not to
432support it, if they don't see a use for importing \* from their package.  For
n433-example, the file :file:`Sounds/Effects/__init__.py` could contain the following
n462+example, the file :file:`sounds/effects/__init__.py` could contain the following
434code::
435
436   __all__ = ["echo", "surround", "reverse"]
437
n438-This would mean that ``from Sound.Effects import *`` would import the three
n467+This would mean that ``from sound.effects import *`` would import the three
439-named submodules of the :mod:`Sound` package.
468+named submodules of the :mod:`sound` package.
440
n441-If ``__all__`` is not defined, the statement ``from Sound.Effects import *``
n470+If ``__all__`` is not defined, the statement ``from sound.effects import *``
442-does *not* import all submodules from the package :mod:`Sound.Effects` into the
471+does *not* import all submodules from the package :mod:`sound.effects` into the
443-current namespace; it only ensures that the package :mod:`Sound.Effects` has
472+current namespace; it only ensures that the package :mod:`sound.effects` has
444been imported (possibly running any initialization code in :file:`__init__.py`)
445and then imports whatever names are defined in the package.  This includes any
446names defined (and submodules explicitly loaded) by :file:`__init__.py`.  It
447also includes any submodules of the package that were explicitly loaded by
448previous import statements.  Consider this code::
449
n450-   import Sound.Effects.echo
n479+   import sound.effects.echo
451-   import Sound.Effects.surround
480+   import sound.effects.surround
452-   from Sound.Effects import *
481+   from sound.effects import *
453
454In this example, the echo and surround modules are imported in the current
n455-namespace because they are defined in the :mod:`Sound.Effects` package when the
n484+namespace because they are defined in the :mod:`sound.effects` package when the
456``from...import`` statement is executed.  (This also works when ``__all__`` is
457defined.)
458
459Note that in general the practice of importing ``*`` from a module or package is
460frowned upon, since it often causes poorly readable code. However, it is okay to
461use it to save typing in interactive sessions, and certain modules are designed
462to export only names that follow certain patterns.
463
474:mod:`surround` module might use the :mod:`echo` module.  In fact, such
475references are so common that the :keyword:`import` statement first looks in the
476containing package before looking in the standard module search path. Thus, the
477:mod:`surround` module can simply use ``import echo`` or ``from echo import
478echofilter``.  If the imported module is not found in the current package (the
479package of which the current module is a submodule), the :keyword:`import`
480statement looks for a top-level module with the given name.
481
n482-When packages are structured into subpackages (as with the :mod:`Sound` package
n511+When packages are structured into subpackages (as with the :mod:`sound` package
483-in the example), there's no shortcut to refer to submodules of sibling packages
512+in the example), you can use absolute imports to refer to submodules of siblings
484-- the full name of the subpackage must be used.  For example, if the module
513+packages.  For example, if the module :mod:`sound.filters.vocoder` needs to use
485-:mod:`Sound.Filters.vocoder` needs to use the :mod:`echo` module in the
514+the :mod:`echo` module in the :mod:`sound.effects` package, it can use ``from
486-:mod:`Sound.Effects` package, it can use ``from Sound.Effects import echo``.
515+sound.effects import echo``.
487
488Starting with Python 2.5, in addition to the implicit relative imports described
489above, you can write explicit relative imports with the ``from module import
490name`` form of import statement. These explicit relative imports use leading
491dots to indicate the current and parent packages involved in the relative
492import. From the :mod:`surround` module for example, you might use::
493
494   from . import echo
t495-   from .. import Formats
t524+   from .. import formats
496-   from ..Filters import equalizer
525+   from ..filters import equalizer
497
498Note that both explicit and implicit relative imports are based on the name of
499the current module. Since the name of the main module is always ``"__main__"``,
500modules intended for use as the main module of a Python application should
501always use absolute imports.
502
503
504Packages in Multiple Directories
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op