Commit | Line | Data |
---|---|---|
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> | |
78 | 6. Modules | |
79 | </H1> | |
80 | ||
81 | <P> | |
82 | If you quit from the Python interpreter and enter it again, the | |
83 | definitions you have made (functions and variables) are lost. | |
84 | Therefore, if you want to write a somewhat longer program, you are | |
85 | better off using a text editor to prepare the input for the interpreter | |
86 | and 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 | |
88 | into several files for easier maintenance. You may also want to use a | |
89 | handy function that you've written in several programs without copying | |
90 | its definition into each program. | |
91 | ||
92 | <P> | |
93 | To support this, Python has a way to put definitions in a file and use | |
94 | them in a script or in an interactive instance of the interpreter. | |
95 | Such 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 | |
97 | collection of variables that you have access to in a script | |
98 | executed at the top level | |
99 | and in calculator mode). | |
100 | ||
101 | <P> | |
102 | A module is a file containing Python definitions and statements. The | |
103 | file name is the module name with the suffix <span class="file">.py</span> appended. Within | |
104 | a module, the module's name (as a string) is available as the value of | |
105 | the global variable <code>__name__</code>. For instance, use your favorite text | |
106 | editor to create a file called <span class="file">fibo.py</span> in the current directory | |
107 | with the following contents: | |
108 | ||
109 | <P> | |
110 | <div class="verbatim"><pre> | |
111 | # Fibonacci numbers module | |
112 | ||
113 | def fib(n): # write Fibonacci series up to n | |
114 | a, b = 0, 1 | |
115 | while b < n: | |
116 | print b, | |
117 | a, b = b, a+b | |
118 | ||
119 | def fib2(n): # return Fibonacci series up to n | |
120 | result = [] | |
121 | a, b = 0, 1 | |
122 | while b < n: | |
123 | result.append(b) | |
124 | a, b = b, a+b | |
125 | return result | |
126 | </pre></div> | |
127 | ||
128 | <P> | |
129 | Now enter the Python interpreter and import this module with the | |
130 | following command: | |
131 | ||
132 | <P> | |
133 | <div class="verbatim"><pre> | |
134 | >>> import fibo | |
135 | </pre></div> | |
136 | ||
137 | <P> | |
138 | This does not enter the names of the functions defined in <code>fibo</code> | |
139 | directly in the current symbol table; it only enters the module name | |
140 | <code>fibo</code> there. | |
141 | Using the module name you can access the functions: | |
142 | ||
143 | <P> | |
144 | <div class="verbatim"><pre> | |
145 | >>> fibo.fib(1000) | |
146 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 | |
147 | >>> fibo.fib2(100) | |
148 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] | |
149 | >>> fibo.__name__ | |
150 | 'fibo' | |
151 | </pre></div> | |
152 | ||
153 | <P> | |
154 | If you intend to use a function often you can assign it to a local name: | |
155 | ||
156 | <P> | |
157 | <div class="verbatim"><pre> | |
158 | >>> fib = fibo.fib | |
159 | >>> fib(500) | |
160 | 1 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> | |
167 | 6.1 More on Modules | |
168 | </H1> | |
169 | ||
170 | <P> | |
171 | A module can contain executable statements as well as function | |
172 | definitions. | |
173 | These statements are intended to initialize the module. | |
174 | They 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> | |
178 | Each module has its own private symbol table, which is used as the | |
179 | global symbol table by all functions defined in the module. | |
180 | Thus, the author of a module can use global variables in the module | |
181 | without worrying about accidental clashes with a user's global | |
182 | variables. | |
183 | On the other hand, if you know what you are doing you can touch a | |
184 | module's global variables with the same notation used to refer to its | |
185 | functions, | |
186 | <code>modname.itemname</code>. | |
187 | ||
188 | <P> | |
189 | Modules can import other modules. It is customary but not required to | |
190 | place all <tt class="keyword">import</tt> statements at the beginning of a module (or | |
191 | script, for that matter). The imported module names are placed in the | |
192 | importing module's global symbol table. | |
193 | ||
194 | <P> | |
195 | There is a variant of the <tt class="keyword">import</tt> statement that imports | |
196 | names from a module directly into the importing module's symbol | |
197 | table. For example: | |
198 | ||
199 | <P> | |
200 | <div class="verbatim"><pre> | |
201 | >>> from fibo import fib, fib2 | |
202 | >>> fib(500) | |
203 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 | |
204 | </pre></div> | |
205 | ||
206 | <P> | |
207 | This does not introduce the module name from which the imports are taken | |
208 | in the local symbol table (so in the example, <code>fibo</code> is not | |
209 | defined). | |
210 | ||
211 | <P> | |
212 | There is even a variant to import all names that a module defines: | |
213 | ||
214 | <P> | |
215 | <div class="verbatim"><pre> | |
216 | >>> from fibo import * | |
217 | >>> fib(500) | |
218 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 | |
219 | </pre></div> | |
220 | ||
221 | <P> | |
222 | This 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> | |
229 | 6.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 | |
234 | for a file named <span class="file">spam.py</span> in the current directory, | |
235 | and then in the list of directories specified by | |
236 | the environment variable <a class="envvar" id='l2h-19' xml:id='l2h-19'>PYTHONPATH</a>. This has the same syntax as | |
237 | the shell variable <a class="envvar" id='l2h-20' xml:id='l2h-20'>PATH</a>, that is, a list of | |
238 | directory names. When <a class="envvar" id='l2h-21' xml:id='l2h-21'>PYTHONPATH</a> is not set, or when the file | |
239 | is not found there, the search continues in an installation-dependent | |
240 | default path; on <span class="Unix">Unix</span>, this is usually <span class="file">.:/usr/local/lib/python</span>. | |
241 | ||
242 | <P> | |
243 | Actually, modules are searched in the list of directories given by the | |
244 | variable <code>sys.path</code> which is initialized from the directory | |
245 | containing 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 | |
247 | Python programs that know what they're doing to modify or replace the | |
248 | module search path. Note that because the directory containing the | |
249 | script being run is on the search path, it is important that the | |
250 | script not have the same name as a standard module, or Python will | |
251 | attempt to load the script as a module when that module is imported. | |
252 | This will generally be an error. See section <A HREF="#standardModules">6.2</A>, | |
253 | ``Standard Modules,'' for more information. | |
254 | ||
255 | <P> | |
256 | ||
257 | <H2><A NAME="SECTION008120000000000000000"> | |
258 | 6.1.2 ``Compiled'' Python files</A> | |
259 | </H2> | |
260 | ||
261 | <P> | |
262 | As an important speed-up of the start-up time for short programs that | |
263 | use a lot of standard modules, if a file called <span class="file">spam.pyc</span> exists | |
264 | in the directory where <span class="file">spam.py</span> is found, this is assumed to | |
265 | contain an already-``byte-compiled'' version of the module <tt class="module">spam</tt>. | |
266 | The 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> | |
271 | Normally, 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 | |
273 | compiled, 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 | |
275 | reason the file is not written completely, the resulting | |
276 | <span class="file">spam.pyc</span> file will be recognized as invalid and thus ignored | |
277 | later. The contents of the <span class="file">spam.pyc</span> file are platform | |
278 | independent, so a Python module directory can be shared by machines of | |
279 | different architectures. | |
280 | ||
281 | <P> | |
282 | Some 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, | |
288 | optimized code is generated and stored in <span class="file">.pyo</span> files. The | |
289 | optimizer 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> | |
291 | bytecode is optimized; <code>.pyc</code> files are ignored and <code>.py</code> | |
292 | files 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 | |
298 | optimizations that could in some rare cases result in malfunctioning | |
299 | programs. Currently only <code>__doc__</code> strings are removed from the | |
300 | bytecode, resulting in more compact <span class="file">.pyo</span> files. Since some | |
301 | programs may rely on having these available, you should only use this | |
302 | option 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 | |
308 | thing that's faster about <span class="file">.pyc</span> or <span class="file">.pyo</span> files is the | |
309 | speed 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 | |
314 | bytecode 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 | |
316 | by moving most of its code to a module and having a small bootstrap | |
317 | script 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 | |
325 | library of Python code in a form that is moderately hard to reverse | |
326 | engineer. | |
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 | |
333 | directory. | |
334 | ||
335 | <P> | |
336 | </LI> | |
337 | </UL> | |
338 | ||
339 | <P> | |
340 | ||
341 | <H1><A NAME="SECTION008200000000000000000"></A><A NAME="standardModules"></A> | |
342 | <BR> | |
343 | 6.2 Standard Modules | |
344 | </H1> | |
345 | ||
346 | <P> | |
347 | Python comes with a library of standard modules, described in a separate | |
348 | document, 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 | |
353 | interpreter; these provide access to operations that are not part of | |
354 | the core of the language but are nevertheless built in, either for | |
355 | efficiency or to provide access to operating system primitives such as | |
356 | system calls. The set of such modules is a configuration option which | |
357 | also depends on the underlying platform For example, | |
358 | the <tt class="module">amoeba</tt> module is only provided on systems that somehow | |
359 | support Amoeba primitives. One particular module deserves some | |
360 | attention: <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 | |
362 | Python interpreter. The variables <code>sys.ps1</code> and | |
363 | <code>sys.ps2</code> define the strings used as primary and secondary | |
364 | prompts: | |
365 | ||
366 | <P> | |
367 | <div class="verbatim"><pre> | |
368 | >>> import sys | |
369 | >>> sys.ps1 | |
370 | '>>> ' | |
371 | >>> sys.ps2 | |
372 | '... ' | |
373 | >>> sys.ps1 = 'C> ' | |
374 | C> print 'Yuck!' | |
375 | Yuck! | |
376 | C> | |
377 | </pre></div> | |
378 | ||
379 | <P> | |
380 | These two variables are only defined if the interpreter is in | |
381 | interactive mode. | |
382 | ||
383 | <P> | |
384 | The variable <code>sys.path</code> is a list of strings that determines the | |
385 | interpreter's search path for modules. It is initialized to a default | |
386 | path taken from the environment variable <a class="envvar" id='l2h-25' xml:id='l2h-25'>PYTHONPATH</a>, or from | |
387 | a built-in default if <a class="envvar" id='l2h-26' xml:id='l2h-26'>PYTHONPATH</a> is not set. You can modify | |
388 | it using standard list operations: | |
389 | ||
390 | <P> | |
391 | <div class="verbatim"><pre> | |
392 | >>> import sys | |
393 | >>> 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> | |
400 | 6.3 The <tt class="function">dir()</tt> Function | |
401 | </H1> | |
402 | ||
403 | <P> | |
404 | The built-in function <tt class="function">dir()</tt> is used to find out which names | |
405 | a module defines. It returns a sorted list of strings: | |
406 | ||
407 | <P> | |
408 | <div class="verbatim"><pre> | |
409 | >>> import fibo, sys | |
410 | >>> dir(fibo) | |
411 | ['__name__', 'fib', 'fib2'] | |
412 | >>> 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> | |
426 | Without arguments, <tt class="function">dir()</tt> lists the names you have defined | |
427 | currently: | |
428 | ||
429 | <P> | |
430 | <div class="verbatim"><pre> | |
431 | >>> a = [1, 2, 3, 4, 5] | |
432 | >>> import fibo | |
433 | >>> fib = fibo.fib | |
434 | >>> dir() | |
435 | ['__builtins__', '__doc__', '__file__', '__name__', 'a', 'fib', 'fibo', 'sys'] | |
436 | </pre></div> | |
437 | ||
438 | <P> | |
439 | Note 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 | |
443 | variables. If you want a list of those, they are defined in the | |
444 | standard module <tt class="module">__builtin__</tt><a id='l2h-27' xml:id='l2h-27'></a>: | |
445 | ||
446 | <P> | |
447 | <div class="verbatim"><pre> | |
448 | >>> import __builtin__ | |
449 | >>> 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> | |
480 | 6.4 Packages | |
481 | </H1> | |
482 | ||
483 | <P> | |
484 | Packages are a way of structuring Python's module namespace | |
485 | by 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 | |
488 | modules from having to worry about each other's global variable names, | |
489 | the use of dotted module names saves the authors of multi-module | |
490 | packages like NumPy or the Python Imaging Library from having to worry | |
491 | about each other's module names. | |
492 | ||
493 | <P> | |
494 | Suppose you want to design a collection of modules (a ``package'') for | |
495 | the uniform handling of sound files and sound data. There are many | |
496 | different sound file formats (usually recognized by their extension, | |
497 | for example: <span class="file">.wav</span>, <span class="file">.aiff</span>, <span class="file">.au</span>), so you may need | |
498 | to create and maintain a growing collection of modules for the | |
499 | conversion between the various file formats. There are also many | |
500 | different operations you might want to perform on sound data (such as | |
501 | mixing, adding echo, applying an equalizer function, creating an | |
502 | artificial stereo effect), so in addition you will be writing a | |
503 | never-ending stream of modules to perform these operations. Here's a | |
504 | possible structure for your package (expressed in terms of a | |
505 | hierarchical filesystem): | |
506 | ||
507 | <P> | |
508 | <div class="verbatim"><pre> | |
509 | Sound/ 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> | |
535 | When importing the package, Python searches through the directories | |
536 | on <code>sys.path</code> looking for the package subdirectory. | |
537 | ||
538 | <P> | |
539 | The <span class="file">__init__.py</span> files are required to make Python treat the | |
540 | directories as containing packages; this is done to prevent | |
541 | directories with a common name, such as "<tt class="samp">string</tt>", from | |
542 | unintentionally hiding valid modules that occur later on the module | |
543 | search path. In the simplest case, <span class="file">__init__.py</span> can just be an | |
544 | empty file, but it can also execute initialization code for the | |
545 | package or set the <code>__all__</code> variable, described later. | |
546 | ||
547 | <P> | |
548 | Users of the package can import individual modules from the | |
549 | package, for example: | |
550 | ||
551 | <P> | |
552 | <div class="verbatim"><pre> | |
553 | import Sound.Effects.echo | |
554 | </pre></div> | |
555 | ||
556 | <P> | |
557 | This loads the submodule <tt class="module">Sound.Effects.echo</tt>. It must be referenced | |
558 | with its full name. | |
559 | ||
560 | <P> | |
561 | <div class="verbatim"><pre> | |
562 | Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4) | |
563 | </pre></div> | |
564 | ||
565 | <P> | |
566 | An alternative way of importing the submodule is: | |
567 | ||
568 | <P> | |
569 | <div class="verbatim"><pre> | |
570 | from Sound.Effects import echo | |
571 | </pre></div> | |
572 | ||
573 | <P> | |
574 | This also loads the submodule <tt class="module">echo</tt>, and makes it available without | |
575 | its package prefix, so it can be used as follows: | |
576 | ||
577 | <P> | |
578 | <div class="verbatim"><pre> | |
579 | echo.echofilter(input, output, delay=0.7, atten=4) | |
580 | </pre></div> | |
581 | ||
582 | <P> | |
583 | Yet another variation is to import the desired function or variable directly: | |
584 | ||
585 | <P> | |
586 | <div class="verbatim"><pre> | |
587 | from Sound.Effects.echo import echofilter | |
588 | </pre></div> | |
589 | ||
590 | <P> | |
591 | Again, 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> | |
596 | echofilter(input, output, delay=0.7, atten=4) | |
597 | </pre></div> | |
598 | ||
599 | <P> | |
600 | Note that when using <code>from <var>package</var> import <var>item</var></code>, the | |
601 | item can be either a submodule (or subpackage) of the package, or some | |
602 | other name defined in the package, like a function, class or | |
603 | variable. The <code>import</code> statement first tests whether the item is | |
604 | defined in the package; if not, it assumes it is a module and attempts | |
605 | to load it. If it fails to find it, an | |
606 | <tt class="exception">ImportError</tt> exception is raised. | |
607 | ||
608 | <P> | |
609 | Contrarily, when using syntax like <code>import | |
610 | <var>item.subitem.subsubitem</var></code>, each item except for the last must be | |
611 | a package; the last item can be a module or a package but can't be a | |
612 | class 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> | |
618 | 6.4.1 Importing * From a Package | |
619 | </H2> | |
620 | ||
621 | <P> | |
622 | <a id='l2h-28' xml:id='l2h-28'></a> | |
623 | Now what happens when the user writes <code>from Sound.Effects import | |
624 | *</code>? Ideally, one would hope that this somehow goes out to the | |
625 | filesystem, finds which submodules are present in the package, and | |
626 | imports them all. Unfortunately, this operation does not work very | |
627 | well on Mac and Windows platforms, where the filesystem does not | |
628 | always have accurate information about the case of a filename! On | |
629 | these 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 | |
632 | annoying practice of showing all file names with a capitalized first | |
633 | letter.) The DOS 8+3 filename restriction adds another interesting | |
634 | problem for long module names. | |
635 | ||
636 | <P> | |
637 | The only solution is for the package author to provide an explicit | |
638 | index of the package. The import statement uses the following | |
639 | convention: if a package's <span class="file">__init__.py</span> code defines a list | |
640 | named <code>__all__</code>, it is taken to be the list of module names that | |
641 | should be imported when <code>from <var>package</var> import *</code> is | |
642 | encountered. It is up to the package author to keep this list | |
643 | up-to-date when a new version of the package is released. Package | |
644 | authors may also decide not to support it, if they don't see a use for | |
645 | importing * 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> | |
654 | This would mean that <code>from Sound.Effects import *</code> would | |
655 | import the three named submodules of the <tt class="module">Sound</tt> package. | |
656 | ||
657 | <P> | |
658 | If <code>__all__</code> is not defined, the statement <code>from Sound.Effects | |
659 | import *</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 | |
661 | package <tt class="module">Sound.Effects</tt> has been imported (possibly running any | |
662 | initialization code in <span class="file">__init__.py</span>) and then imports whatever names are | |
663 | defined in the package. This includes any names defined (and | |
664 | submodules explicitly loaded) by <span class="file">__init__.py</span>. It also includes any | |
665 | submodules of the package that were explicitly loaded by previous | |
666 | import statements. Consider this code: | |
667 | ||
668 | <P> | |
669 | <div class="verbatim"><pre> | |
670 | import Sound.Effects.echo | |
671 | import Sound.Effects.surround | |
672 | from Sound.Effects import * | |
673 | </pre></div> | |
674 | ||
675 | <P> | |
676 | In this example, the echo and surround modules are imported in the | |
677 | current namespace because they are defined in the | |
678 | <tt class="module">Sound.Effects</tt> package when the <code>from...import</code> statement | |
679 | is executed. (This also works when <code>__all__</code> is defined.) | |
680 | ||
681 | <P> | |
682 | Note that in general the practice of importing <code>*</code> from a module or | |
683 | package is frowned upon, since it often causes poorly readable code. | |
684 | However, it is okay to use it to save typing in interactive sessions, | |
685 | and certain modules are designed to export only names that follow | |
686 | certain patterns. | |
687 | ||
688 | <P> | |
689 | Remember, there is nothing wrong with using <code>from Package | |
690 | import specific_submodule</code>! In fact, this is the | |
691 | recommended notation unless the importing module needs to use | |
692 | submodules with the same name from different packages. | |
693 | ||
694 | <P> | |
695 | ||
696 | <H2><A NAME="SECTION008420000000000000000"> | |
697 | 6.4.2 Intra-package References</A> | |
698 | </H2> | |
699 | ||
700 | <P> | |
701 | The 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, | |
703 | such references | |
704 | are so common that the <tt class="keyword">import</tt> statement first looks in the | |
705 | containing package before looking in the standard module search path. | |
706 | Thus, the surround module can simply use <code>import echo</code> or | |
707 | <code>from echo import echofilter</code>. If the imported module is not | |
708 | found in the current package (the package of which the current module | |
709 | is a submodule), the <tt class="keyword">import</tt> statement looks for a top-level | |
710 | module with the given name. | |
711 | ||
712 | <P> | |
713 | When packages are structured into subpackages (as with the | |
714 | <tt class="module">Sound</tt> package in the example), there's no shortcut to refer | |
715 | to submodules of sibling packages - the full name of the subpackage | |
716 | must 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 | |
718 | in the <tt class="module">Sound.Effects</tt> package, it can use <code>from | |
719 | Sound.Effects import echo</code>. | |
720 | ||
721 | <P> | |
722 | ||
723 | <H2><A NAME="SECTION008430000000000000000"> | |
724 | 6.4.3 Packages in Multiple Directories</A> | |
725 | </H2> | |
726 | ||
727 | <P> | |
728 | Packages support one more special attribute, <tt class="member">__path__</tt>. This | |
729 | is initialized to be a list containing the name of the directory | |
730 | holding the package's <span class="file">__init__.py</span> before the code in that file | |
731 | is executed. This variable can be modified; doing so affects future | |
732 | searches for modules and subpackages contained in the package. | |
733 | ||
734 | <P> | |
735 | While this feature is not often needed, it can be used to extend the | |
736 | set 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> | |
789 | See <i><a href="about.html">About this document...</a></i> for information on suggesting changes. | |
790 | </ADDRESS> | |
791 | </BODY> | |
792 | </HTML> |