Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / amd64 / html / python / tut / node8.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="tut.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="tut.html" title='Python Tutorial' />
8<link rel='contents' href='node2.html' title="Contents" />
9<link rel='index' href='node19.html' title='Index' />
10<link rel='last' href='about.html' title='About this document...' />
11<link rel='help' href='about.html' title='About this document...' />
12<link rel="next" href="node9.html" />
13<link rel="prev" href="node7.html" />
14<link rel="parent" href="tut.html" />
15<link rel="next" href="node9.html" />
16<meta name='aesop' content='information' />
17<title>6. Modules </title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="5. Data Structures"
25 href="node7.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="Python Tutorial"
28 href="tut.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="7. Input and Output"
31 href="node9.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Python Tutorial</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="node2.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><a rel="index" title="Index"
40 href="node19.html"><img src='../icons/index.png'
41 border='0' height='32' alt='Index' width='32' /></A></td>
42</tr></table>
43<div class='online-navigation'>
44<b class="navlabel">Previous:</b>
45<a class="sectref" rel="prev" href="node7.html">5. Data Structures</A>
46<b class="navlabel">Up:</b>
47<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
48<b class="navlabel">Next:</b>
49<a class="sectref" rel="next" href="node9.html">7. Input and Output</A>
50</div>
51<hr /></div>
52</DIV>
53<!--End of Navigation Panel-->
54<div class='online-navigation'>
55<!--Table of Child-Links-->
56<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
57
58<UL CLASS="ChildLinks">
59<LI><A href="node8.html#SECTION008100000000000000000">6.1 More on Modules</a>
60<UL>
61<LI><A href="node8.html#SECTION008110000000000000000">6.1.1 The Module Search Path</a>
62<LI><A href="node8.html#SECTION008120000000000000000">6.1.2 ``Compiled'' Python files</a>
63</ul>
64<LI><A href="node8.html#SECTION008200000000000000000">6.2 Standard Modules</a>
65<LI><A href="node8.html#SECTION008300000000000000000">6.3 The <tt class="function">dir()</tt> Function</a>
66<LI><A href="node8.html#SECTION008400000000000000000">6.4 Packages</a>
67<UL>
68<LI><A href="node8.html#SECTION008410000000000000000">6.4.1 Importing * From a Package</a>
69<LI><A href="node8.html#SECTION008420000000000000000">6.4.2 Intra-package References</a>
70<LI><A href="node8.html#SECTION008430000000000000000">6.4.3 Packages in Multiple Directories</a>
71</ul></ul>
72<!--End of Table of Child-Links-->
73</div>
74<HR>
75
76<H1><A NAME="SECTION008000000000000000000"></A><A NAME="modules"></A>
77<BR>
786. Modules
79</H1>
80
81<P>
82If you quit from the Python interpreter and enter it again, the
83definitions you have made (functions and variables) are lost.
84Therefore, if you want to write a somewhat longer program, you are
85better off using a text editor to prepare the input for the interpreter
86and running it with that file as input instead. This is known as creating a
87<em>script</em>. As your program gets longer, you may want to split it
88into several files for easier maintenance. You may also want to use a
89handy function that you've written in several programs without copying
90its definition into each program.
91
92<P>
93To support this, Python has a way to put definitions in a file and use
94them in a script or in an interactive instance of the interpreter.
95Such a file is called a <em>module</em>; definitions from a module can be
96<em>imported</em> into other modules or into the <em>main</em> module (the
97collection of variables that you have access to in a script
98executed at the top level
99and in calculator mode).
100
101<P>
102A module is a file containing Python definitions and statements. The
103file name is the module name with the suffix <span class="file">.py</span> appended. Within
104a module, the module's name (as a string) is available as the value of
105the global variable <code>__name__</code>. For instance, use your favorite text
106editor to create a file called <span class="file">fibo.py</span> in the current directory
107with the following contents:
108
109<P>
110<div class="verbatim"><pre>
111# Fibonacci numbers module
112
113def fib(n): # write Fibonacci series up to n
114 a, b = 0, 1
115 while b &lt; n:
116 print b,
117 a, b = b, a+b
118
119def fib2(n): # return Fibonacci series up to n
120 result = []
121 a, b = 0, 1
122 while b &lt; n:
123 result.append(b)
124 a, b = b, a+b
125 return result
126</pre></div>
127
128<P>
129Now enter the Python interpreter and import this module with the
130following command:
131
132<P>
133<div class="verbatim"><pre>
134&gt;&gt;&gt; import fibo
135</pre></div>
136
137<P>
138This does not enter the names of the functions defined in <code>fibo</code>
139directly in the current symbol table; it only enters the module name
140<code>fibo</code> there.
141Using the module name you can access the functions:
142
143<P>
144<div class="verbatim"><pre>
145&gt;&gt;&gt; fibo.fib(1000)
1461 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
147&gt;&gt;&gt; fibo.fib2(100)
148[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
149&gt;&gt;&gt; fibo.__name__
150'fibo'
151</pre></div>
152
153<P>
154If you intend to use a function often you can assign it to a local name:
155
156<P>
157<div class="verbatim"><pre>
158&gt;&gt;&gt; fib = fibo.fib
159&gt;&gt;&gt; fib(500)
1601 1 2 3 5 8 13 21 34 55 89 144 233 377
161</pre></div>
162
163<P>
164
165<H1><A NAME="SECTION008100000000000000000"></A><A NAME="moreModules"></A>
166<BR>
1676.1 More on Modules
168</H1>
169
170<P>
171A module can contain executable statements as well as function
172definitions.
173These statements are intended to initialize the module.
174They are executed only the
175<em>first</em> time the module is imported somewhere.<A NAME="tex2html4"
176 HREF="#foot757"><SUP>6.1</SUP></A>
177<P>
178Each module has its own private symbol table, which is used as the
179global symbol table by all functions defined in the module.
180Thus, the author of a module can use global variables in the module
181without worrying about accidental clashes with a user's global
182variables.
183On the other hand, if you know what you are doing you can touch a
184module's global variables with the same notation used to refer to its
185functions,
186<code>modname.itemname</code>.
187
188<P>
189Modules can import other modules. It is customary but not required to
190place all <tt class="keyword">import</tt> statements at the beginning of a module (or
191script, for that matter). The imported module names are placed in the
192importing module's global symbol table.
193
194<P>
195There is a variant of the <tt class="keyword">import</tt> statement that imports
196names from a module directly into the importing module's symbol
197table. For example:
198
199<P>
200<div class="verbatim"><pre>
201&gt;&gt;&gt; from fibo import fib, fib2
202&gt;&gt;&gt; fib(500)
2031 1 2 3 5 8 13 21 34 55 89 144 233 377
204</pre></div>
205
206<P>
207This does not introduce the module name from which the imports are taken
208in the local symbol table (so in the example, <code>fibo</code> is not
209defined).
210
211<P>
212There is even a variant to import all names that a module defines:
213
214<P>
215<div class="verbatim"><pre>
216&gt;&gt;&gt; from fibo import *
217&gt;&gt;&gt; fib(500)
2181 1 2 3 5 8 13 21 34 55 89 144 233 377
219</pre></div>
220
221<P>
222This imports all names except those beginning with an underscore
223(<code>_</code>).
224
225<P>
226
227<H2><A NAME="SECTION008110000000000000000"></A><A NAME="searchPath"></A>
228<BR>
2296.1.1 The Module Search Path
230</H2>
231
232<P>
233<a id='l2h-18' xml:id='l2h-18'></a>When a module named <tt class="module">spam</tt> is imported, the interpreter searches
234for a file named <span class="file">spam.py</span> in the current directory,
235and then in the list of directories specified by
236the environment variable <a class="envvar" id='l2h-19' xml:id='l2h-19'>PYTHONPATH</a>. This has the same syntax as
237the shell variable <a class="envvar" id='l2h-20' xml:id='l2h-20'>PATH</a>, that is, a list of
238directory names. When <a class="envvar" id='l2h-21' xml:id='l2h-21'>PYTHONPATH</a> is not set, or when the file
239is not found there, the search continues in an installation-dependent
240default path; on <span class="Unix">Unix</span>, this is usually <span class="file">.:/usr/local/lib/python</span>.
241
242<P>
243Actually, modules are searched in the list of directories given by the
244variable <code>sys.path</code> which is initialized from the directory
245containing the input script (or the current directory),
246<a class="envvar" id='l2h-22' xml:id='l2h-22'>PYTHONPATH</a> and the installation-dependent default. This allows
247Python programs that know what they're doing to modify or replace the
248module search path. Note that because the directory containing the
249script being run is on the search path, it is important that the
250script not have the same name as a standard module, or Python will
251attempt to load the script as a module when that module is imported.
252This will generally be an error. See section&nbsp;<A HREF="#standardModules">6.2</A>,
253``Standard Modules,'' for more information.
254
255<P>
256
257<H2><A NAME="SECTION008120000000000000000">
2586.1.2 ``Compiled'' Python files</A>
259</H2>
260
261<P>
262As an important speed-up of the start-up time for short programs that
263use a lot of standard modules, if a file called <span class="file">spam.pyc</span> exists
264in the directory where <span class="file">spam.py</span> is found, this is assumed to
265contain an already-``byte-compiled'' version of the module <tt class="module">spam</tt>.
266The modification time of the version of <span class="file">spam.py</span> used to create
267<span class="file">spam.pyc</span> is recorded in <span class="file">spam.pyc</span>, and the
268<span class="file">.pyc</span> file is ignored if these don't match.
269
270<P>
271Normally, you don't need to do anything to create the
272<span class="file">spam.pyc</span> file. Whenever <span class="file">spam.py</span> is successfully
273compiled, an attempt is made to write the compiled version to
274<span class="file">spam.pyc</span>. It is not an error if this attempt fails; if for any
275reason the file is not written completely, the resulting
276<span class="file">spam.pyc</span> file will be recognized as invalid and thus ignored
277later. The contents of the <span class="file">spam.pyc</span> file are platform
278independent, so a Python module directory can be shared by machines of
279different architectures.
280
281<P>
282Some tips for experts:
283
284<P>
285
286<UL>
287<LI>When the Python interpreter is invoked with the <b class="programopt">-O</b> flag,
288optimized code is generated and stored in <span class="file">.pyo</span> files. The
289optimizer currently doesn't help much; it only removes
290<tt class="keyword">assert</tt> statements. When <b class="programopt">-O</b> is used, <em>all</em>
291bytecode is optimized; <code>.pyc</code> files are ignored and <code>.py</code>
292files are compiled to optimized bytecode.
293
294<P>
295</LI>
296<LI>Passing two <b class="programopt">-O</b> flags to the Python interpreter
297(<b class="programopt">-OO</b>) will cause the bytecode compiler to perform
298optimizations that could in some rare cases result in malfunctioning
299programs. Currently only <code>__doc__</code> strings are removed from the
300bytecode, resulting in more compact <span class="file">.pyo</span> files. Since some
301programs may rely on having these available, you should only use this
302option if you know what you're doing.
303
304<P>
305</LI>
306<LI>A program doesn't run any faster when it is read from a <span class="file">.pyc</span> or
307<span class="file">.pyo</span> file than when it is read from a <span class="file">.py</span> file; the only
308thing that's faster about <span class="file">.pyc</span> or <span class="file">.pyo</span> files is the
309speed with which they are loaded.
310
311<P>
312</LI>
313<LI>When a script is run by giving its name on the command line, the
314bytecode for the script is never written to a <span class="file">.pyc</span> or
315<span class="file">.pyo</span> file. Thus, the startup time of a script may be reduced
316by moving most of its code to a module and having a small bootstrap
317script that imports that module. It is also possible to name a
318<span class="file">.pyc</span> or <span class="file">.pyo</span> file directly on the command line.
319
320<P>
321</LI>
322<LI>It is possible to have a file called <span class="file">spam.pyc</span> (or
323<span class="file">spam.pyo</span> when <b class="programopt">-O</b> is used) without a file
324<span class="file">spam.py</span> for the same module. This can be used to distribute a
325library of Python code in a form that is moderately hard to reverse
326engineer.
327
328<P>
329</LI>
330<LI>The module <a class="ulink" href="../lib/module-compileall.html"
331 ><tt class="module">compileall</tt></a> <a id='l2h-23' xml:id='l2h-23'></a> can create <span class="file">.pyc</span> files (or
332<span class="file">.pyo</span> files when <b class="programopt">-O</b> is used) for all modules in a
333directory.
334
335<P>
336</LI>
337</UL>
338
339<P>
340
341<H1><A NAME="SECTION008200000000000000000"></A><A NAME="standardModules"></A>
342<BR>
3436.2 Standard Modules
344</H1>
345
346<P>
347Python comes with a library of standard modules, described in a separate
348document, the <em class="citetitle"><a
349 href="../lib/lib.html"
350 title="Python Library Reference"
351 >Python Library Reference</a></em>
352(``Library Reference'' hereafter). Some modules are built into the
353interpreter; these provide access to operations that are not part of
354the core of the language but are nevertheless built in, either for
355efficiency or to provide access to operating system primitives such as
356system calls. The set of such modules is a configuration option which
357also depends on the underlying platform For example,
358the <tt class="module">amoeba</tt> module is only provided on systems that somehow
359support Amoeba primitives. One particular module deserves some
360attention: <a class="ulink" href="../lib/module-sys.html"
361 ><tt class="module">sys</tt></a><a id='l2h-24' xml:id='l2h-24'></a>, which is built into every
362Python interpreter. The variables <code>sys.ps1</code> and
363<code>sys.ps2</code> define the strings used as primary and secondary
364prompts:
365
366<P>
367<div class="verbatim"><pre>
368&gt;&gt;&gt; import sys
369&gt;&gt;&gt; sys.ps1
370'&gt;&gt;&gt; '
371&gt;&gt;&gt; sys.ps2
372'... '
373&gt;&gt;&gt; sys.ps1 = 'C&gt; '
374C&gt; print 'Yuck!'
375Yuck!
376C&gt;
377</pre></div>
378
379<P>
380These two variables are only defined if the interpreter is in
381interactive mode.
382
383<P>
384The variable <code>sys.path</code> is a list of strings that determines the
385interpreter's search path for modules. It is initialized to a default
386path taken from the environment variable <a class="envvar" id='l2h-25' xml:id='l2h-25'>PYTHONPATH</a>, or from
387a built-in default if <a class="envvar" id='l2h-26' xml:id='l2h-26'>PYTHONPATH</a> is not set. You can modify
388it using standard list operations:
389
390<P>
391<div class="verbatim"><pre>
392&gt;&gt;&gt; import sys
393&gt;&gt;&gt; sys.path.append('/ufs/guido/lib/python')
394</pre></div>
395
396<P>
397
398<H1><A NAME="SECTION008300000000000000000"></A><A NAME="dir"></A>
399<BR>
4006.3 The <tt class="function">dir()</tt> Function
401</H1>
402
403<P>
404The built-in function <tt class="function">dir()</tt> is used to find out which names
405a module defines. It returns a sorted list of strings:
406
407<P>
408<div class="verbatim"><pre>
409&gt;&gt;&gt; import fibo, sys
410&gt;&gt;&gt; dir(fibo)
411['__name__', 'fib', 'fib2']
412&gt;&gt;&gt; dir(sys)
413['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
414 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
415 'builtin_module_names', 'byteorder', 'callstats', 'copyright',
416 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
417 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
418 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
419 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
420 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
421 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
422 'version', 'version_info', 'warnoptions']
423</pre></div>
424
425<P>
426Without arguments, <tt class="function">dir()</tt> lists the names you have defined
427currently:
428
429<P>
430<div class="verbatim"><pre>
431&gt;&gt;&gt; a = [1, 2, 3, 4, 5]
432&gt;&gt;&gt; import fibo
433&gt;&gt;&gt; fib = fibo.fib
434&gt;&gt;&gt; dir()
435['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys']
436</pre></div>
437
438<P>
439Note that it lists all types of names: variables, modules, functions, etc.
440
441<P>
442<tt class="function">dir()</tt> does not list the names of built-in functions and
443variables. If you want a list of those, they are defined in the
444standard module <tt class="module">__builtin__</tt><a id='l2h-27' xml:id='l2h-27'></a>:
445
446<P>
447<div class="verbatim"><pre>
448&gt;&gt;&gt; import __builtin__
449&gt;&gt;&gt; dir(__builtin__)
450['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning',
451 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
452 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError',
453 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
454 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
455 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
456 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError',
457 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError',
458 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True',
459 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError',
460 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError',
461 'UserWarning', 'ValueError', 'Warning', 'WindowsError',
462 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
463 '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer',
464 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile',
465 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
466 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
467 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
468 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
469 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
470 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range',
471 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set',
472 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super',
473 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
474</pre></div>
475
476<P>
477
478<H1><A NAME="SECTION008400000000000000000"></A><A NAME="packages"></A>
479<BR>
4806.4 Packages
481</H1>
482
483<P>
484Packages are a way of structuring Python's module namespace
485by using ``dotted module names''. For example, the module name
486<tt class="module">A.B</tt> designates a submodule named "<tt class="samp">B</tt>" in a package named
487"<tt class="samp">A</tt>". Just like the use of modules saves the authors of different
488modules from having to worry about each other's global variable names,
489the use of dotted module names saves the authors of multi-module
490packages like NumPy or the Python Imaging Library from having to worry
491about each other's module names.
492
493<P>
494Suppose you want to design a collection of modules (a ``package'') for
495the uniform handling of sound files and sound data. There are many
496different sound file formats (usually recognized by their extension,
497for example: <span class="file">.wav</span>, <span class="file">.aiff</span>, <span class="file">.au</span>), so you may need
498to create and maintain a growing collection of modules for the
499conversion between the various file formats. There are also many
500different operations you might want to perform on sound data (such as
501mixing, adding echo, applying an equalizer function, creating an
502artificial stereo effect), so in addition you will be writing a
503never-ending stream of modules to perform these operations. Here's a
504possible structure for your package (expressed in terms of a
505hierarchical filesystem):
506
507<P>
508<div class="verbatim"><pre>
509Sound/ Top-level package
510 __init__.py Initialize the sound package
511 Formats/ Subpackage for file format conversions
512 __init__.py
513 wavread.py
514 wavwrite.py
515 aiffread.py
516 aiffwrite.py
517 auread.py
518 auwrite.py
519 ...
520 Effects/ Subpackage for sound effects
521 __init__.py
522 echo.py
523 surround.py
524 reverse.py
525 ...
526 Filters/ Subpackage for filters
527 __init__.py
528 equalizer.py
529 vocoder.py
530 karaoke.py
531 ...
532</pre></div>
533
534<P>
535When importing the package, Python searches through the directories
536on <code>sys.path</code> looking for the package subdirectory.
537
538<P>
539The <span class="file">__init__.py</span> files are required to make Python treat the
540directories as containing packages; this is done to prevent
541directories with a common name, such as "<tt class="samp">string</tt>", from
542unintentionally hiding valid modules that occur later on the module
543search path. In the simplest case, <span class="file">__init__.py</span> can just be an
544empty file, but it can also execute initialization code for the
545package or set the <code>__all__</code> variable, described later.
546
547<P>
548Users of the package can import individual modules from the
549package, for example:
550
551<P>
552<div class="verbatim"><pre>
553import Sound.Effects.echo
554</pre></div>
555
556<P>
557This loads the submodule <tt class="module">Sound.Effects.echo</tt>. It must be referenced
558with its full name.
559
560<P>
561<div class="verbatim"><pre>
562Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
563</pre></div>
564
565<P>
566An alternative way of importing the submodule is:
567
568<P>
569<div class="verbatim"><pre>
570from Sound.Effects import echo
571</pre></div>
572
573<P>
574This also loads the submodule <tt class="module">echo</tt>, and makes it available without
575its package prefix, so it can be used as follows:
576
577<P>
578<div class="verbatim"><pre>
579echo.echofilter(input, output, delay=0.7, atten=4)
580</pre></div>
581
582<P>
583Yet another variation is to import the desired function or variable directly:
584
585<P>
586<div class="verbatim"><pre>
587from Sound.Effects.echo import echofilter
588</pre></div>
589
590<P>
591Again, this loads the submodule <tt class="module">echo</tt>, but this makes its function
592<tt class="function">echofilter()</tt> directly available:
593
594<P>
595<div class="verbatim"><pre>
596echofilter(input, output, delay=0.7, atten=4)
597</pre></div>
598
599<P>
600Note that when using <code>from <var>package</var> import <var>item</var></code>, the
601item can be either a submodule (or subpackage) of the package, or some
602other name defined in the package, like a function, class or
603variable. The <code>import</code> statement first tests whether the item is
604defined in the package; if not, it assumes it is a module and attempts
605to load it. If it fails to find it, an
606<tt class="exception">ImportError</tt> exception is raised.
607
608<P>
609Contrarily, when using syntax like <code>import
610<var>item.subitem.subsubitem</var></code>, each item except for the last must be
611a package; the last item can be a module or a package but can't be a
612class or function or variable defined in the previous item.
613
614<P>
615
616<H2><A NAME="SECTION008410000000000000000"></A><A NAME="pkg-import-star"></A>
617<BR>
6186.4.1 Importing * From a Package
619</H2>
620
621<P>
622<a id='l2h-28' xml:id='l2h-28'></a>
623Now what happens when the user writes <code>from Sound.Effects import
624*</code>? Ideally, one would hope that this somehow goes out to the
625filesystem, finds which submodules are present in the package, and
626imports them all. Unfortunately, this operation does not work very
627well on Mac and Windows platforms, where the filesystem does not
628always have accurate information about the case of a filename! On
629these platforms, there is no guaranteed way to know whether a file
630<span class="file">ECHO.PY</span> should be imported as a module <tt class="module">echo</tt>,
631<tt class="module">Echo</tt> or <tt class="module">ECHO</tt>. (For example, Windows 95 has the
632annoying practice of showing all file names with a capitalized first
633letter.) The DOS 8+3 filename restriction adds another interesting
634problem for long module names.
635
636<P>
637The only solution is for the package author to provide an explicit
638index of the package. The import statement uses the following
639convention: if a package's <span class="file">__init__.py</span> code defines a list
640named <code>__all__</code>, it is taken to be the list of module names that
641should be imported when <code>from <var>package</var> import *</code> is
642encountered. It is up to the package author to keep this list
643up-to-date when a new version of the package is released. Package
644authors may also decide not to support it, if they don't see a use for
645importing * from their package. For example, the file
646<span class="file">Sounds/Effects/__init__.py</span> could contain the following code:
647
648<P>
649<div class="verbatim"><pre>
650__all__ = ["echo", "surround", "reverse"]
651</pre></div>
652
653<P>
654This would mean that <code>from Sound.Effects import *</code> would
655import the three named submodules of the <tt class="module">Sound</tt> package.
656
657<P>
658If <code>__all__</code> is not defined, the statement <code>from Sound.Effects
659import *</code> does <em>not</em> import all submodules from the package
660<tt class="module">Sound.Effects</tt> into the current namespace; it only ensures that the
661package <tt class="module">Sound.Effects</tt> has been imported (possibly running any
662initialization code in <span class="file">__init__.py</span>) and then imports whatever names are
663defined in the package. This includes any names defined (and
664submodules explicitly loaded) by <span class="file">__init__.py</span>. It also includes any
665submodules of the package that were explicitly loaded by previous
666import statements. Consider this code:
667
668<P>
669<div class="verbatim"><pre>
670import Sound.Effects.echo
671import Sound.Effects.surround
672from Sound.Effects import *
673</pre></div>
674
675<P>
676In this example, the echo and surround modules are imported in the
677current namespace because they are defined in the
678<tt class="module">Sound.Effects</tt> package when the <code>from...import</code> statement
679is executed. (This also works when <code>__all__</code> is defined.)
680
681<P>
682Note that in general the practice of importing <code>*</code> from a module or
683package is frowned upon, since it often causes poorly readable code.
684However, it is okay to use it to save typing in interactive sessions,
685and certain modules are designed to export only names that follow
686certain patterns.
687
688<P>
689Remember, there is nothing wrong with using <code>from Package
690import specific_submodule</code>! In fact, this is the
691recommended notation unless the importing module needs to use
692submodules with the same name from different packages.
693
694<P>
695
696<H2><A NAME="SECTION008420000000000000000">
6976.4.2 Intra-package References</A>
698</H2>
699
700<P>
701The submodules often need to refer to each other. For example, the
702<tt class="module">surround</tt> module might use the <tt class="module">echo</tt> module. In fact,
703such references
704are so common that the <tt class="keyword">import</tt> statement first looks in the
705containing package before looking in the standard module search path.
706Thus, the surround module can simply use <code>import echo</code> or
707<code>from echo import echofilter</code>. If the imported module is not
708found in the current package (the package of which the current module
709is a submodule), the <tt class="keyword">import</tt> statement looks for a top-level
710module with the given name.
711
712<P>
713When packages are structured into subpackages (as with the
714<tt class="module">Sound</tt> package in the example), there's no shortcut to refer
715to submodules of sibling packages - the full name of the subpackage
716must be used. For example, if the module
717<tt class="module">Sound.Filters.vocoder</tt> needs to use the <tt class="module">echo</tt> module
718in the <tt class="module">Sound.Effects</tt> package, it can use <code>from
719Sound.Effects import echo</code>.
720
721<P>
722
723<H2><A NAME="SECTION008430000000000000000">
7246.4.3 Packages in Multiple Directories</A>
725</H2>
726
727<P>
728Packages support one more special attribute, <tt class="member">__path__</tt>. This
729is initialized to be a list containing the name of the directory
730holding the package's <span class="file">__init__.py</span> before the code in that file
731is executed. This variable can be modified; doing so affects future
732searches for modules and subpackages contained in the package.
733
734<P>
735While this feature is not often needed, it can be used to extend the
736set of modules found in a package.
737
738<P>
739<BR><HR><H4>Footnotes</H4>
740<DL>
741<DT><A NAME="foot757">... somewhere.</A><A
742 HREF="node8.html#tex2html4"><SUP>6.1</SUP></A></DT>
743<DD>
744 In fact function definitions are also `statements' that are
745 `executed'; the execution enters the function name in the
746 module's global symbol table.
747
748
749</DD>
750</DL>
751<DIV CLASS="navigation">
752<div class='online-navigation'>
753<p></p><hr />
754<table align="center" width="100%" cellpadding="0" cellspacing="2">
755<tr>
756<td class='online-navigation'><a rel="prev" title="5. Data Structures"
757 href="node7.html"><img src='../icons/previous.png'
758 border='0' height='32' alt='Previous Page' width='32' /></A></td>
759<td class='online-navigation'><a rel="parent" title="Python Tutorial"
760 href="tut.html"><img src='../icons/up.png'
761 border='0' height='32' alt='Up One Level' width='32' /></A></td>
762<td class='online-navigation'><a rel="next" title="7. Input and Output"
763 href="node9.html"><img src='../icons/next.png'
764 border='0' height='32' alt='Next Page' width='32' /></A></td>
765<td align="center" width="100%">Python Tutorial</td>
766<td class='online-navigation'><a rel="contents" title="Table of Contents"
767 href="node2.html"><img src='../icons/contents.png'
768 border='0' height='32' alt='Contents' width='32' /></A></td>
769<td class='online-navigation'><img src='../icons/blank.png'
770 border='0' height='32' alt='' width='32' /></td>
771<td class='online-navigation'><a rel="index" title="Index"
772 href="node19.html"><img src='../icons/index.png'
773 border='0' height='32' alt='Index' width='32' /></A></td>
774</tr></table>
775<div class='online-navigation'>
776<b class="navlabel">Previous:</b>
777<a class="sectref" rel="prev" href="node7.html">5. Data Structures</A>
778<b class="navlabel">Up:</b>
779<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
780<b class="navlabel">Next:</b>
781<a class="sectref" rel="next" href="node9.html">7. Input and Output</A>
782</div>
783</div>
784<hr />
785<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
786</DIV>
787<!--End of Navigation Panel-->
788<ADDRESS>
789See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
790</ADDRESS>
791</BODY>
792</HTML>