modules.html 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="6. Modules" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/tutorial/modules.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are bett..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are bett..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>6. Modules &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="7. Input and Output" href="inputoutput.html" />
  34. <link rel="prev" title="5. Data Structures" href="datastructures.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/tutorial/modules.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">6. Modules</a><ul>
  86. <li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
  87. <li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
  88. <li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
  89. <li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
  90. </ul>
  91. </li>
  92. <li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
  93. <li><a class="reference internal" href="#the-dir-function">6.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
  94. <li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
  95. <li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
  96. <li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
  97. <li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
  98. </ul>
  99. </li>
  100. </ul>
  101. </li>
  102. </ul>
  103. </div>
  104. <div>
  105. <h4>Previous topic</h4>
  106. <p class="topless"><a href="datastructures.html"
  107. title="previous chapter"><span class="section-number">5. </span>Data Structures</a></p>
  108. </div>
  109. <div>
  110. <h4>Next topic</h4>
  111. <p class="topless"><a href="inputoutput.html"
  112. title="next chapter"><span class="section-number">7. </span>Input and Output</a></p>
  113. </div>
  114. <div role="note" aria-label="source link">
  115. <h3>This Page</h3>
  116. <ul class="this-page-menu">
  117. <li><a href="../bugs.html">Report a Bug</a></li>
  118. <li>
  119. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/modules.rst"
  120. rel="nofollow">Show Source
  121. </a>
  122. </li>
  123. </ul>
  124. </div>
  125. </nav>
  126. </div>
  127. </div>
  128. <div class="related" role="navigation" aria-label="related navigation">
  129. <h3>Navigation</h3>
  130. <ul>
  131. <li class="right" style="margin-right: 10px">
  132. <a href="../genindex.html" title="General Index"
  133. accesskey="I">index</a></li>
  134. <li class="right" >
  135. <a href="../py-modindex.html" title="Python Module Index"
  136. >modules</a> |</li>
  137. <li class="right" >
  138. <a href="inputoutput.html" title="7. Input and Output"
  139. accesskey="N">next</a> |</li>
  140. <li class="right" >
  141. <a href="datastructures.html" title="5. Data Structures"
  142. accesskey="P">previous</a> |</li>
  143. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  144. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  145. <li class="switchers">
  146. <div class="language_switcher_placeholder"></div>
  147. <div class="version_switcher_placeholder"></div>
  148. </li>
  149. <li>
  150. </li>
  151. <li id="cpython-language-and-version">
  152. <a href="../index.html">3.12.0 Documentation</a> &#187;
  153. </li>
  154. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> &#187;</li>
  155. <li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Modules</a></li>
  156. <li class="right">
  157. <div class="inline-search" role="search">
  158. <form class="inline-search" action="../search.html" method="get">
  159. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  160. <input type="submit" value="Go" />
  161. </form>
  162. </div>
  163. |
  164. </li>
  165. <li class="right">
  166. <label class="theme-selector-label">
  167. Theme
  168. <select class="theme-selector" oninput="activateTheme(this.value)">
  169. <option value="auto" selected>Auto</option>
  170. <option value="light">Light</option>
  171. <option value="dark">Dark</option>
  172. </select>
  173. </label> |</li>
  174. </ul>
  175. </div>
  176. <div class="document">
  177. <div class="documentwrapper">
  178. <div class="bodywrapper">
  179. <div class="body" role="main">
  180. <section id="modules">
  181. <span id="tut-modules"></span><h1><span class="section-number">6. </span>Modules<a class="headerlink" href="#modules" title="Permalink to this headline">¶</a></h1>
  182. <p>If you quit from the Python interpreter and enter it again, the definitions you
  183. have made (functions and variables) are lost. Therefore, if you want to write a
  184. somewhat longer program, you are better off using a text editor to prepare the
  185. input for the interpreter and running it with that file as input instead. This
  186. is known as creating a <em>script</em>. As your program gets longer, you may want to
  187. split it into several files for easier maintenance. You may also want to use a
  188. handy function that you’ve written in several programs without copying its
  189. definition into each program.</p>
  190. <p>To support this, Python has a way to put definitions in a file and use them in a
  191. script or in an interactive instance of the interpreter. Such a file is called a
  192. <em>module</em>; definitions from a module can be <em>imported</em> into other modules or into
  193. the <em>main</em> module (the collection of variables that you have access to in a
  194. script executed at the top level and in calculator mode).</p>
  195. <p>A module is a file containing Python definitions and statements. The file name
  196. is the module name with the suffix <code class="file docutils literal notranslate"><span class="pre">.py</span></code> appended. Within a module, the
  197. module’s name (as a string) is available as the value of the global variable
  198. <code class="docutils literal notranslate"><span class="pre">__name__</span></code>. For instance, use your favorite text editor to create a file
  199. called <code class="file docutils literal notranslate"><span class="pre">fibo.py</span></code> in the current directory with the following contents:</p>
  200. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Fibonacci numbers module</span>
  201. <span class="k">def</span> <span class="nf">fib</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="c1"># write Fibonacci series up to n</span>
  202. <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
  203. <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
  204. <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39; &#39;</span><span class="p">)</span>
  205. <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
  206. <span class="nb">print</span><span class="p">()</span>
  207. <span class="k">def</span> <span class="nf">fib2</span><span class="p">(</span><span class="n">n</span><span class="p">):</span> <span class="c1"># return Fibonacci series up to n</span>
  208. <span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
  209. <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">1</span>
  210. <span class="k">while</span> <span class="n">a</span> <span class="o">&lt;</span> <span class="n">n</span><span class="p">:</span>
  211. <span class="n">result</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
  212. <span class="n">a</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="n">b</span><span class="p">,</span> <span class="n">a</span><span class="o">+</span><span class="n">b</span>
  213. <span class="k">return</span> <span class="n">result</span>
  214. </pre></div>
  215. </div>
  216. <p>Now enter the Python interpreter and import this module with the following
  217. command:</p>
  218. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
  219. </pre></div>
  220. </div>
  221. <p>This does not add the names of the functions defined in <code class="docutils literal notranslate"><span class="pre">fibo</span></code> directly to
  222. the current <a class="reference internal" href="../glossary.html#term-namespace"><span class="xref std std-term">namespace</span></a> (see <a class="reference internal" href="classes.html#tut-scopes"><span class="std std-ref">Python Scopes and Namespaces</span></a> for more details);
  223. it only adds the module name <code class="docutils literal notranslate"><span class="pre">fibo</span></code> there. Using
  224. the module name you can access the functions:</p>
  225. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span>
  226. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987</span>
  227. <span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="n">fib2</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
  228. <span class="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
  229. <span class="gp">&gt;&gt;&gt; </span><span class="n">fibo</span><span class="o">.</span><span class="vm">__name__</span>
  230. <span class="go">&#39;fibo&#39;</span>
  231. </pre></div>
  232. </div>
  233. <p>If you intend to use a function often you can assign it to a local name:</p>
  234. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
  235. <span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
  236. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
  237. </pre></div>
  238. </div>
  239. <section id="more-on-modules">
  240. <span id="tut-moremodules"></span><h2><span class="section-number">6.1. </span>More on Modules<a class="headerlink" href="#more-on-modules" title="Permalink to this headline">¶</a></h2>
  241. <p>A module can contain executable statements as well as function definitions.
  242. These statements are intended to initialize the module. They are executed only
  243. the <em>first</em> time the module name is encountered in an import statement. <a class="footnote-reference brackets" href="#id3" id="id1">1</a>
  244. (They are also run if the file is executed as a script.)</p>
  245. <p>Each module has its own private namespace, which is used as the global namespace
  246. by all functions defined in the module. Thus, the author of a module can
  247. use global variables in the module without worrying about accidental clashes
  248. with a user’s global variables. On the other hand, if you know what you are
  249. doing you can touch a module’s global variables with the same notation used to
  250. refer to its functions, <code class="docutils literal notranslate"><span class="pre">modname.itemname</span></code>.</p>
  251. <p>Modules can import other modules. It is customary but not required to place all
  252. <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements at the beginning of a module (or script, for that
  253. matter). The imported module names, if placed at the top level of a module
  254. (outside any functions or classes), are added to the module’s global namespace.</p>
  255. <p>There is a variant of the <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement that imports names from a
  256. module directly into the importing module’s namespace. For example:</p>
  257. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="kn">import</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib2</span>
  258. <span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
  259. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
  260. </pre></div>
  261. </div>
  262. <p>This does not introduce the module name from which the imports are taken in the
  263. local namespace (so in the example, <code class="docutils literal notranslate"><span class="pre">fibo</span></code> is not defined).</p>
  264. <p>There is even a variant to import all names that a module defines:</p>
  265. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="kn">import</span> <span class="o">*</span>
  266. <span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
  267. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
  268. </pre></div>
  269. </div>
  270. <p>This imports all names except those beginning with an underscore (<code class="docutils literal notranslate"><span class="pre">_</span></code>).
  271. In most cases Python programmers do not use this facility since it introduces
  272. an unknown set of names into the interpreter, possibly hiding some things
  273. you have already defined.</p>
  274. <p>Note that in general the practice of importing <code class="docutils literal notranslate"><span class="pre">*</span></code> from a module or package is
  275. frowned upon, since it often causes poorly readable code. However, it is okay to
  276. use it to save typing in interactive sessions.</p>
  277. <p>If the module name is followed by <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code>, then the name
  278. following <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> is bound directly to the imported module.</p>
  279. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span> <span class="k">as</span> <span class="nn">fib</span>
  280. <span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span><span class="o">.</span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
  281. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
  282. </pre></div>
  283. </div>
  284. <p>This is effectively importing the module in the same way that <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">fibo</span></code>
  285. will do, with the only difference of it being available as <code class="docutils literal notranslate"><span class="pre">fib</span></code>.</p>
  286. <p>It can also be used when utilising <a class="reference internal" href="../reference/simple_stmts.html#from"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> with similar effects:</p>
  287. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">fibo</span> <span class="kn">import</span> <span class="n">fib</span> <span class="k">as</span> <span class="n">fibonacci</span>
  288. <span class="gp">&gt;&gt;&gt; </span><span class="n">fibonacci</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
  289. <span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
  290. </pre></div>
  291. </div>
  292. <div class="admonition note">
  293. <p class="admonition-title">Note</p>
  294. <p>For efficiency reasons, each module is only imported once per interpreter
  295. session. Therefore, if you change your modules, you must restart the
  296. interpreter – or, if it’s just one module you want to test interactively,
  297. use <a class="reference internal" href="../library/importlib.html#importlib.reload" title="importlib.reload"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.reload()</span></code></a>, e.g. <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">importlib;</span>
  298. <span class="pre">importlib.reload(modulename)</span></code>.</p>
  299. </div>
  300. <section id="executing-modules-as-scripts">
  301. <span id="tut-modulesasscripts"></span><h3><span class="section-number">6.1.1. </span>Executing modules as scripts<a class="headerlink" href="#executing-modules-as-scripts" title="Permalink to this headline">¶</a></h3>
  302. <p>When you run a Python module with</p>
  303. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="n">fibo</span><span class="o">.</span><span class="n">py</span> <span class="o">&lt;</span><span class="n">arguments</span><span class="o">&gt;</span>
  304. </pre></div>
  305. </div>
  306. <p>the code in the module will be executed, just as if you imported it, but with
  307. the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> set to <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>. That means that by adding this code at
  308. the end of your module:</p>
  309. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="vm">__name__</span> <span class="o">==</span> <span class="s2">&quot;__main__&quot;</span><span class="p">:</span>
  310. <span class="kn">import</span> <span class="nn">sys</span>
  311. <span class="n">fib</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">]))</span>
  312. </pre></div>
  313. </div>
  314. <p>you can make the file usable as a script as well as an importable module,
  315. because the code that parses the command line only runs if the module is
  316. executed as the “main” file:</p>
  317. <div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python<span class="w"> </span>fibo.py<span class="w"> </span><span class="m">50</span>
  318. <span class="go">0 1 1 2 3 5 8 13 21 34</span>
  319. </pre></div>
  320. </div>
  321. <p>If the module is imported, the code is not run:</p>
  322. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
  323. <span class="gp">&gt;&gt;&gt;</span>
  324. </pre></div>
  325. </div>
  326. <p>This is often used either to provide a convenient user interface to a module, or
  327. for testing purposes (running the module as a script executes a test suite).</p>
  328. </section>
  329. <section id="the-module-search-path">
  330. <span id="tut-searchpath"></span><h3><span class="section-number">6.1.2. </span>The Module Search Path<a class="headerlink" href="#the-module-search-path" title="Permalink to this headline">¶</a></h3>
  331. <p id="index-0">When a module named <code class="xref py py-mod docutils literal notranslate"><span class="pre">spam</span></code> is imported, the interpreter first searches for
  332. a built-in module with that name. These module names are listed in
  333. <a class="reference internal" href="../library/sys.html#sys.builtin_module_names" title="sys.builtin_module_names"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.builtin_module_names</span></code></a>. If not found, it then searches for a file
  334. named <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> in a list of directories given by the variable
  335. <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>. <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a> is initialized from these locations:</p>
  336. <ul class="simple">
  337. <li><p>The directory containing the input script (or the current directory when no
  338. file is specified).</p></li>
  339. <li><p><span class="target" id="index-1"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> (a list of directory names, with the same syntax as the
  340. shell variable <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>).</p></li>
  341. <li><p>The installation-dependent default (by convention including a
  342. <code class="docutils literal notranslate"><span class="pre">site-packages</span></code> directory, handled by the <a class="reference internal" href="../library/site.html#module-site" title="site: Module responsible for site-specific configuration."><code class="xref py py-mod docutils literal notranslate"><span class="pre">site</span></code></a> module).</p></li>
  343. </ul>
  344. <p>More details are at <a class="reference internal" href="../library/sys_path_init.html#sys-path-init"><span class="std std-ref">The initialization of the sys.path module search path</span></a>.</p>
  345. <div class="admonition note">
  346. <p class="admonition-title">Note</p>
  347. <p>On file systems which support symlinks, the directory containing the input
  348. script is calculated after the symlink is followed. In other words the
  349. directory containing the symlink is <strong>not</strong> added to the module search path.</p>
  350. </div>
  351. <p>After initialization, Python programs can modify <a class="reference internal" href="../library/sys.html#sys.path" title="sys.path"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.path</span></code></a>. The
  352. directory containing the script being run is placed at the beginning of the
  353. search path, ahead of the standard library path. This means that scripts in that
  354. directory will be loaded instead of modules of the same name in the library
  355. directory. This is an error unless the replacement is intended. See section
  356. <a class="reference internal" href="#tut-standardmodules"><span class="std std-ref">Standard Modules</span></a> for more information.</p>
  357. </section>
  358. <section id="compiled-python-files">
  359. <span id="tut-pycache"></span><h3><span class="section-number">6.1.3. </span>“Compiled” Python files<a class="headerlink" href="#compiled-python-files" title="Permalink to this headline">¶</a></h3>
  360. <p>To speed up loading modules, Python caches the compiled version of each module
  361. in the <code class="docutils literal notranslate"><span class="pre">__pycache__</span></code> directory under the name <code class="file docutils literal notranslate"><span class="pre">module.</span><em><span class="pre">version</span></em><span class="pre">.pyc</span></code>,
  362. where the version encodes the format of the compiled file; it generally contains
  363. the Python version number. For example, in CPython release 3.3 the compiled
  364. version of spam.py would be cached as <code class="docutils literal notranslate"><span class="pre">__pycache__/spam.cpython-33.pyc</span></code>. This
  365. naming convention allows compiled modules from different releases and different
  366. versions of Python to coexist.</p>
  367. <p>Python checks the modification date of the source against the compiled version
  368. to see if it’s out of date and needs to be recompiled. This is a completely
  369. automatic process. Also, the compiled modules are platform-independent, so the
  370. same library can be shared among systems with different architectures.</p>
  371. <p>Python does not check the cache in two circumstances. First, it always
  372. recompiles and does not store the result for the module that’s loaded directly
  373. from the command line. Second, it does not check the cache if there is no
  374. source module. To support a non-source (compiled only) distribution, the
  375. compiled module must be in the source directory, and there must not be a source
  376. module.</p>
  377. <p>Some tips for experts:</p>
  378. <ul class="simple">
  379. <li><p>You can use the <a class="reference internal" href="../using/cmdline.html#cmdoption-O"><code class="xref std std-option docutils literal notranslate"><span class="pre">-O</span></code></a> or <a class="reference internal" href="../using/cmdline.html#cmdoption-OO"><code class="xref std std-option docutils literal notranslate"><span class="pre">-OO</span></code></a> switches on the Python command
  380. to reduce the size of a compiled module. The <code class="docutils literal notranslate"><span class="pre">-O</span></code> switch removes assert
  381. statements, the <code class="docutils literal notranslate"><span class="pre">-OO</span></code> switch removes both assert statements and __doc__
  382. strings. Since some programs may rely on having these available, you should
  383. only use this option if you know what you’re doing. “Optimized” modules have
  384. an <code class="docutils literal notranslate"><span class="pre">opt-</span></code> tag and are usually smaller. Future releases may
  385. change the effects of optimization.</p></li>
  386. <li><p>A program doesn’t run any faster when it is read from a <code class="docutils literal notranslate"><span class="pre">.pyc</span></code>
  387. file than when it is read from a <code class="docutils literal notranslate"><span class="pre">.py</span></code> file; the only thing that’s faster
  388. about <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files is the speed with which they are loaded.</p></li>
  389. <li><p>The module <a class="reference internal" href="../library/compileall.html#module-compileall" title="compileall: Tools for byte-compiling all Python source files in a directory tree."><code class="xref py py-mod docutils literal notranslate"><span class="pre">compileall</span></code></a> can create .pyc files for all modules in a
  390. directory.</p></li>
  391. <li><p>There is more detail on this process, including a flow chart of the
  392. decisions, in <span class="target" id="index-3"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>.</p></li>
  393. </ul>
  394. </section>
  395. </section>
  396. <section id="standard-modules">
  397. <span id="tut-standardmodules"></span><h2><span class="section-number">6.2. </span>Standard Modules<a class="headerlink" href="#standard-modules" title="Permalink to this headline">¶</a></h2>
  398. <p id="index-4">Python comes with a library of standard modules, described in a separate
  399. document, the Python Library Reference (“Library Reference” hereafter). Some
  400. modules are built into the interpreter; these provide access to operations that
  401. are not part of the core of the language but are nevertheless built in, either
  402. for efficiency or to provide access to operating system primitives such as
  403. system calls. The set of such modules is a configuration option which also
  404. depends on the underlying platform. For example, the <a class="reference internal" href="../library/winreg.html#module-winreg" title="winreg: Routines and objects for manipulating the Windows registry. (Windows)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">winreg</span></code></a> module is only
  405. provided on Windows systems. One particular module deserves some attention:
  406. <a class="reference internal" href="../library/sys.html#module-sys" title="sys: Access system-specific parameters and functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sys</span></code></a>, which is built into every Python interpreter. The variables
  407. <code class="docutils literal notranslate"><span class="pre">sys.ps1</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.ps2</span></code> define the strings used as primary and secondary
  408. prompts:</p>
  409. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
  410. <span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span>
  411. <span class="go">&#39;&gt;&gt;&gt; &#39;</span>
  412. <span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps2</span>
  413. <span class="go">&#39;... &#39;</span>
  414. <span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span> <span class="o">=</span> <span class="s1">&#39;C&gt; &#39;</span>
  415. <span class="go">C&gt; print(&#39;Yuck!&#39;)</span>
  416. <span class="go">Yuck!</span>
  417. <span class="go">C&gt;</span>
  418. </pre></div>
  419. </div>
  420. <p>These two variables are only defined if the interpreter is in interactive mode.</p>
  421. <p>The variable <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> is a list of strings that determines the interpreter’s
  422. search path for modules. It is initialized to a default path taken from the
  423. environment variable <span class="target" id="index-5"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a>, or from a built-in default if
  424. <span class="target" id="index-6"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONPATH"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONPATH</span></code></a> is not set. You can modify it using standard list
  425. operations:</p>
  426. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">sys</span>
  427. <span class="gp">&gt;&gt;&gt; </span><span class="n">sys</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;/ufs/guido/lib/python&#39;</span><span class="p">)</span>
  428. </pre></div>
  429. </div>
  430. </section>
  431. <section id="the-dir-function">
  432. <span id="tut-dir"></span><h2><span class="section-number">6.3. </span>The <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> Function<a class="headerlink" href="#the-dir-function" title="Permalink to this headline">¶</a></h2>
  433. <p>The built-in function <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> is used to find out which names a module
  434. defines. It returns a sorted list of strings:</p>
  435. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span><span class="o">,</span> <span class="nn">sys</span>
  436. <span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">fibo</span><span class="p">)</span>
  437. <span class="go">[&#39;__name__&#39;, &#39;fib&#39;, &#39;fib2&#39;]</span>
  438. <span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
  439. <span class="go">[&#39;__breakpointhook__&#39;, &#39;__displayhook__&#39;, &#39;__doc__&#39;, &#39;__excepthook__&#39;,</span>
  440. <span class="go"> &#39;__interactivehook__&#39;, &#39;__loader__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;__spec__&#39;,</span>
  441. <span class="go"> &#39;__stderr__&#39;, &#39;__stdin__&#39;, &#39;__stdout__&#39;, &#39;__unraisablehook__&#39;,</span>
  442. <span class="go"> &#39;_clear_type_cache&#39;, &#39;_current_frames&#39;, &#39;_debugmallocstats&#39;, &#39;_framework&#39;,</span>
  443. <span class="go"> &#39;_getframe&#39;, &#39;_git&#39;, &#39;_home&#39;, &#39;_xoptions&#39;, &#39;abiflags&#39;, &#39;addaudithook&#39;,</span>
  444. <span class="go"> &#39;api_version&#39;, &#39;argv&#39;, &#39;audit&#39;, &#39;base_exec_prefix&#39;, &#39;base_prefix&#39;,</span>
  445. <span class="go"> &#39;breakpointhook&#39;, &#39;builtin_module_names&#39;, &#39;byteorder&#39;, &#39;call_tracing&#39;,</span>
  446. <span class="go"> &#39;callstats&#39;, &#39;copyright&#39;, &#39;displayhook&#39;, &#39;dont_write_bytecode&#39;, &#39;exc_info&#39;,</span>
  447. <span class="go"> &#39;excepthook&#39;, &#39;exec_prefix&#39;, &#39;executable&#39;, &#39;exit&#39;, &#39;flags&#39;, &#39;float_info&#39;,</span>
  448. <span class="go"> &#39;float_repr_style&#39;, &#39;get_asyncgen_hooks&#39;, &#39;get_coroutine_origin_tracking_depth&#39;,</span>
  449. <span class="go"> &#39;getallocatedblocks&#39;, &#39;getdefaultencoding&#39;, &#39;getdlopenflags&#39;,</span>
  450. <span class="go"> &#39;getfilesystemencodeerrors&#39;, &#39;getfilesystemencoding&#39;, &#39;getprofile&#39;,</span>
  451. <span class="go"> &#39;getrecursionlimit&#39;, &#39;getrefcount&#39;, &#39;getsizeof&#39;, &#39;getswitchinterval&#39;,</span>
  452. <span class="go"> &#39;gettrace&#39;, &#39;hash_info&#39;, &#39;hexversion&#39;, &#39;implementation&#39;, &#39;int_info&#39;,</span>
  453. <span class="go"> &#39;intern&#39;, &#39;is_finalizing&#39;, &#39;last_traceback&#39;, &#39;last_type&#39;, &#39;last_value&#39;,</span>
  454. <span class="go"> &#39;maxsize&#39;, &#39;maxunicode&#39;, &#39;meta_path&#39;, &#39;modules&#39;, &#39;path&#39;, &#39;path_hooks&#39;,</span>
  455. <span class="go"> &#39;path_importer_cache&#39;, &#39;platform&#39;, &#39;prefix&#39;, &#39;ps1&#39;, &#39;ps2&#39;, &#39;pycache_prefix&#39;,</span>
  456. <span class="go"> &#39;set_asyncgen_hooks&#39;, &#39;set_coroutine_origin_tracking_depth&#39;, &#39;setdlopenflags&#39;,</span>
  457. <span class="go"> &#39;setprofile&#39;, &#39;setrecursionlimit&#39;, &#39;setswitchinterval&#39;, &#39;settrace&#39;, &#39;stderr&#39;,</span>
  458. <span class="go"> &#39;stdin&#39;, &#39;stdout&#39;, &#39;thread_info&#39;, &#39;unraisablehook&#39;, &#39;version&#39;, &#39;version_info&#39;,</span>
  459. <span class="go"> &#39;warnoptions&#39;]</span>
  460. </pre></div>
  461. </div>
  462. <p>Without arguments, <a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> lists the names you have defined currently:</p>
  463. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">]</span>
  464. <span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">fibo</span>
  465. <span class="gp">&gt;&gt;&gt; </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
  466. <span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">()</span>
  467. <span class="go">[&#39;__builtins__&#39;, &#39;__name__&#39;, &#39;a&#39;, &#39;fib&#39;, &#39;fibo&#39;, &#39;sys&#39;]</span>
  468. </pre></div>
  469. </div>
  470. <p>Note that it lists all types of names: variables, modules, functions, etc.</p>
  471. <p id="index-7"><a class="reference internal" href="../library/functions.html#dir" title="dir"><code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code></a> does not list the names of built-in functions and variables. If you
  472. want a list of those, they are defined in the standard module
  473. <a class="reference internal" href="../library/builtins.html#module-builtins" title="builtins: The module that provides the built-in namespace."><code class="xref py py-mod docutils literal notranslate"><span class="pre">builtins</span></code></a>:</p>
  474. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">builtins</span>
  475. <span class="gp">&gt;&gt;&gt; </span><span class="nb">dir</span><span class="p">(</span><span class="n">builtins</span><span class="p">)</span>
  476. <span class="go">[&#39;ArithmeticError&#39;, &#39;AssertionError&#39;, &#39;AttributeError&#39;, &#39;BaseException&#39;,</span>
  477. <span class="go"> &#39;BlockingIOError&#39;, &#39;BrokenPipeError&#39;, &#39;BufferError&#39;, &#39;BytesWarning&#39;,</span>
  478. <span class="go"> &#39;ChildProcessError&#39;, &#39;ConnectionAbortedError&#39;, &#39;ConnectionError&#39;,</span>
  479. <span class="go"> &#39;ConnectionRefusedError&#39;, &#39;ConnectionResetError&#39;, &#39;DeprecationWarning&#39;,</span>
  480. <span class="go"> &#39;EOFError&#39;, &#39;Ellipsis&#39;, &#39;EnvironmentError&#39;, &#39;Exception&#39;, &#39;False&#39;,</span>
  481. <span class="go"> &#39;FileExistsError&#39;, &#39;FileNotFoundError&#39;, &#39;FloatingPointError&#39;,</span>
  482. <span class="go"> &#39;FutureWarning&#39;, &#39;GeneratorExit&#39;, &#39;IOError&#39;, &#39;ImportError&#39;,</span>
  483. <span class="go"> &#39;ImportWarning&#39;, &#39;IndentationError&#39;, &#39;IndexError&#39;, &#39;InterruptedError&#39;,</span>
  484. <span class="go"> &#39;IsADirectoryError&#39;, &#39;KeyError&#39;, &#39;KeyboardInterrupt&#39;, &#39;LookupError&#39;,</span>
  485. <span class="go"> &#39;MemoryError&#39;, &#39;NameError&#39;, &#39;None&#39;, &#39;NotADirectoryError&#39;, &#39;NotImplemented&#39;,</span>
  486. <span class="go"> &#39;NotImplementedError&#39;, &#39;OSError&#39;, &#39;OverflowError&#39;,</span>
  487. <span class="go"> &#39;PendingDeprecationWarning&#39;, &#39;PermissionError&#39;, &#39;ProcessLookupError&#39;,</span>
  488. <span class="go"> &#39;ReferenceError&#39;, &#39;ResourceWarning&#39;, &#39;RuntimeError&#39;, &#39;RuntimeWarning&#39;,</span>
  489. <span class="go"> &#39;StopIteration&#39;, &#39;SyntaxError&#39;, &#39;SyntaxWarning&#39;, &#39;SystemError&#39;,</span>
  490. <span class="go"> &#39;SystemExit&#39;, &#39;TabError&#39;, &#39;TimeoutError&#39;, &#39;True&#39;, &#39;TypeError&#39;,</span>
  491. <span class="go"> &#39;UnboundLocalError&#39;, &#39;UnicodeDecodeError&#39;, &#39;UnicodeEncodeError&#39;,</span>
  492. <span class="go"> &#39;UnicodeError&#39;, &#39;UnicodeTranslateError&#39;, &#39;UnicodeWarning&#39;, &#39;UserWarning&#39;,</span>
  493. <span class="go"> &#39;ValueError&#39;, &#39;Warning&#39;, &#39;ZeroDivisionError&#39;, &#39;_&#39;, &#39;__build_class__&#39;,</span>
  494. <span class="go"> &#39;__debug__&#39;, &#39;__doc__&#39;, &#39;__import__&#39;, &#39;__name__&#39;, &#39;__package__&#39;, &#39;abs&#39;,</span>
  495. <span class="go"> &#39;all&#39;, &#39;any&#39;, &#39;ascii&#39;, &#39;bin&#39;, &#39;bool&#39;, &#39;bytearray&#39;, &#39;bytes&#39;, &#39;callable&#39;,</span>
  496. <span class="go"> &#39;chr&#39;, &#39;classmethod&#39;, &#39;compile&#39;, &#39;complex&#39;, &#39;copyright&#39;, &#39;credits&#39;,</span>
  497. <span class="go"> &#39;delattr&#39;, &#39;dict&#39;, &#39;dir&#39;, &#39;divmod&#39;, &#39;enumerate&#39;, &#39;eval&#39;, &#39;exec&#39;, &#39;exit&#39;,</span>
  498. <span class="go"> &#39;filter&#39;, &#39;float&#39;, &#39;format&#39;, &#39;frozenset&#39;, &#39;getattr&#39;, &#39;globals&#39;, &#39;hasattr&#39;,</span>
  499. <span class="go"> &#39;hash&#39;, &#39;help&#39;, &#39;hex&#39;, &#39;id&#39;, &#39;input&#39;, &#39;int&#39;, &#39;isinstance&#39;, &#39;issubclass&#39;,</span>
  500. <span class="go"> &#39;iter&#39;, &#39;len&#39;, &#39;license&#39;, &#39;list&#39;, &#39;locals&#39;, &#39;map&#39;, &#39;max&#39;, &#39;memoryview&#39;,</span>
  501. <span class="go"> &#39;min&#39;, &#39;next&#39;, &#39;object&#39;, &#39;oct&#39;, &#39;open&#39;, &#39;ord&#39;, &#39;pow&#39;, &#39;print&#39;, &#39;property&#39;,</span>
  502. <span class="go"> &#39;quit&#39;, &#39;range&#39;, &#39;repr&#39;, &#39;reversed&#39;, &#39;round&#39;, &#39;set&#39;, &#39;setattr&#39;, &#39;slice&#39;,</span>
  503. <span class="go"> &#39;sorted&#39;, &#39;staticmethod&#39;, &#39;str&#39;, &#39;sum&#39;, &#39;super&#39;, &#39;tuple&#39;, &#39;type&#39;, &#39;vars&#39;,</span>
  504. <span class="go"> &#39;zip&#39;]</span>
  505. </pre></div>
  506. </div>
  507. </section>
  508. <section id="packages">
  509. <span id="tut-packages"></span><h2><span class="section-number">6.4. </span>Packages<a class="headerlink" href="#packages" title="Permalink to this headline">¶</a></h2>
  510. <p>Packages are a way of structuring Python’s module namespace by using “dotted
  511. module names”. For example, the module name <code class="xref py py-mod docutils literal notranslate"><span class="pre">A.B</span></code> designates a submodule
  512. named <code class="docutils literal notranslate"><span class="pre">B</span></code> in a package named <code class="docutils literal notranslate"><span class="pre">A</span></code>. Just like the use of modules saves the
  513. authors of different modules from having to worry about each other’s global
  514. variable names, the use of dotted module names saves the authors of multi-module
  515. packages like NumPy or Pillow from having to worry about
  516. each other’s module names.</p>
  517. <p>Suppose you want to design a collection of modules (a “package”) for the uniform
  518. handling of sound files and sound data. There are many different sound file
  519. formats (usually recognized by their extension, for example: <code class="file docutils literal notranslate"><span class="pre">.wav</span></code>,
  520. <code class="file docutils literal notranslate"><span class="pre">.aiff</span></code>, <code class="file docutils literal notranslate"><span class="pre">.au</span></code>), so you may need to create and maintain a growing
  521. collection of modules for the conversion between the various file formats.
  522. There are also many different operations you might want to perform on sound data
  523. (such as mixing, adding echo, applying an equalizer function, creating an
  524. artificial stereo effect), so in addition you will be writing a never-ending
  525. stream of modules to perform these operations. Here’s a possible structure for
  526. your package (expressed in terms of a hierarchical filesystem):</p>
  527. <div class="highlight-text notranslate"><div class="highlight"><pre><span></span>sound/ Top-level package
  528. __init__.py Initialize the sound package
  529. formats/ Subpackage for file format conversions
  530. __init__.py
  531. wavread.py
  532. wavwrite.py
  533. aiffread.py
  534. aiffwrite.py
  535. auread.py
  536. auwrite.py
  537. ...
  538. effects/ Subpackage for sound effects
  539. __init__.py
  540. echo.py
  541. surround.py
  542. reverse.py
  543. ...
  544. filters/ Subpackage for filters
  545. __init__.py
  546. equalizer.py
  547. vocoder.py
  548. karaoke.py
  549. ...
  550. </pre></div>
  551. </div>
  552. <p>When importing the package, Python searches through the directories on
  553. <code class="docutils literal notranslate"><span class="pre">sys.path</span></code> looking for the package subdirectory.</p>
  554. <p>The <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> files are required to make Python treat directories
  555. containing the file as packages. This prevents directories with a common name,
  556. such as <code class="docutils literal notranslate"><span class="pre">string</span></code>, from unintentionally hiding valid modules that occur later
  557. on the module search path. In the simplest case, <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> can just be
  558. an empty file, but it can also execute initialization code for the package or
  559. set the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> variable, described later.</p>
  560. <p>Users of the package can import individual modules from the package, for
  561. example:</p>
  562. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
  563. </pre></div>
  564. </div>
  565. <p>This loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects.echo</span></code>. It must be referenced with
  566. its full name.</p>
  567. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">sound</span><span class="o">.</span><span class="n">effects</span><span class="o">.</span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
  568. </pre></div>
  569. </div>
  570. <p>An alternative way of importing the submodule is:</p>
  571. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects</span> <span class="kn">import</span> <span class="n">echo</span>
  572. </pre></div>
  573. </div>
  574. <p>This also loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, and makes it available without its
  575. package prefix, so it can be used as follows:</p>
  576. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">echo</span><span class="o">.</span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
  577. </pre></div>
  578. </div>
  579. <p>Yet another variation is to import the desired function or variable directly:</p>
  580. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">sound.effects.echo</span> <span class="kn">import</span> <span class="n">echofilter</span>
  581. </pre></div>
  582. </div>
  583. <p>Again, this loads the submodule <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code>, but this makes its function
  584. <code class="xref py py-func docutils literal notranslate"><span class="pre">echofilter()</span></code> directly available:</p>
  585. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">echofilter</span><span class="p">(</span><span class="nb">input</span><span class="p">,</span> <span class="n">output</span><span class="p">,</span> <span class="n">delay</span><span class="o">=</span><span class="mf">0.7</span><span class="p">,</span> <span class="n">atten</span><span class="o">=</span><span class="mi">4</span><span class="p">)</span>
  586. </pre></div>
  587. </div>
  588. <p>Note that when using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">item</span></code>, the item can be either a
  589. submodule (or subpackage) of the package, or some other name defined in the
  590. package, like a function, class or variable. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement first
  591. tests whether the item is defined in the package; if not, it assumes it is a
  592. module and attempts to load it. If it fails to find it, an <a class="reference internal" href="../library/exceptions.html#ImportError" title="ImportError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportError</span></code></a>
  593. exception is raised.</p>
  594. <p>Contrarily, when using syntax like <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">item.subitem.subsubitem</span></code>, each item
  595. except for the last must be a package; the last item can be a module or a
  596. package but can’t be a class or function or variable defined in the previous
  597. item.</p>
  598. <section id="importing-from-a-package">
  599. <span id="tut-pkg-import-star"></span><h3><span class="section-number">6.4.1. </span>Importing * From a Package<a class="headerlink" href="#importing-from-a-package" title="Permalink to this headline">¶</a></h3>
  600. <p id="index-8">Now what happens when the user writes <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>? Ideally,
  601. one would hope that this somehow goes out to the filesystem, finds which
  602. submodules are present in the package, and imports them all. This could take a
  603. long time and importing sub-modules might have unwanted side-effects that should
  604. only happen when the sub-module is explicitly imported.</p>
  605. <p>The only solution is for the package author to provide an explicit index of the
  606. package. The <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement uses the following convention: if a package’s
  607. <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> code defines a list named <code class="docutils literal notranslate"><span class="pre">__all__</span></code>, it is taken to be the
  608. list of module names that should be imported when <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span> <span class="pre">*</span></code> is
  609. encountered. It is up to the package author to keep this list up-to-date when a
  610. new version of the package is released. Package authors may also decide not to
  611. support it, if they don’t see a use for importing * from their package. For
  612. example, the file <code class="file docutils literal notranslate"><span class="pre">sound/effects/__init__.py</span></code> could contain the following
  613. code:</p>
  614. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span><span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="s2">&quot;surround&quot;</span><span class="p">,</span> <span class="s2">&quot;reverse&quot;</span><span class="p">]</span>
  615. </pre></div>
  616. </div>
  617. <p>This would mean that <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code> would import the three
  618. named submodules of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package.</p>
  619. <p>Be aware that submodules might become shadowed by locally defined names. For
  620. example, if you added a <code class="docutils literal notranslate"><span class="pre">reverse</span></code> function to the
  621. <code class="file docutils literal notranslate"><span class="pre">sound/effects/__init__.py</span></code> file, the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>
  622. would only import the two submodules <code class="docutils literal notranslate"><span class="pre">echo</span></code> and <code class="docutils literal notranslate"><span class="pre">surround</span></code>, but <em>not</em> the
  623. <code class="docutils literal notranslate"><span class="pre">reverse</span></code> submodule, because it is shadowed by the locally defined
  624. <code class="docutils literal notranslate"><span class="pre">reverse</span></code> function:</p>
  625. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">__all__</span> <span class="o">=</span> <span class="p">[</span>
  626. <span class="s2">&quot;echo&quot;</span><span class="p">,</span> <span class="c1"># refers to the &#39;echo.py&#39; file</span>
  627. <span class="s2">&quot;surround&quot;</span><span class="p">,</span> <span class="c1"># refers to the &#39;surround.py&#39; file</span>
  628. <span class="s2">&quot;reverse&quot;</span><span class="p">,</span> <span class="c1"># !!! refers to the &#39;reverse&#39; function now !!!</span>
  629. <span class="p">]</span>
  630. <span class="k">def</span> <span class="nf">reverse</span><span class="p">(</span><span class="n">msg</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span> <span class="c1"># &lt;-- this name shadows the &#39;reverse.py&#39; submodule</span>
  631. <span class="k">return</span> <span class="n">msg</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># in the case of a &#39;from sound.effects import *&#39;</span>
  632. </pre></div>
  633. </div>
  634. <p>If <code class="docutils literal notranslate"><span class="pre">__all__</span></code> is not defined, the statement <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">*</span></code>
  635. does <em>not</em> import all submodules from the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> into the
  636. current namespace; it only ensures that the package <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> has
  637. been imported (possibly running any initialization code in <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>)
  638. and then imports whatever names are defined in the package. This includes any
  639. names defined (and submodules explicitly loaded) by <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>. It
  640. also includes any submodules of the package that were explicitly loaded by
  641. previous <a class="reference internal" href="../reference/simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statements. Consider this code:</p>
  642. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sound.effects.echo</span>
  643. <span class="kn">import</span> <span class="nn">sound.effects.surround</span>
  644. <span class="kn">from</span> <span class="nn">sound.effects</span> <span class="kn">import</span> <span class="o">*</span>
  645. </pre></div>
  646. </div>
  647. <p>In this example, the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> and <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code> modules are imported in the
  648. current namespace because they are defined in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package
  649. when the <code class="docutils literal notranslate"><span class="pre">from...import</span></code> statement is executed. (This also works when
  650. <code class="docutils literal notranslate"><span class="pre">__all__</span></code> is defined.)</p>
  651. <p>Although certain modules are designed to export only names that follow certain
  652. patterns when you use <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">*</span></code>, it is still considered bad practice in
  653. production code.</p>
  654. <p>Remember, there is nothing wrong with using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">package</span> <span class="pre">import</span>
  655. <span class="pre">specific_submodule</span></code>! In fact, this is the recommended notation unless the
  656. importing module needs to use submodules with the same name from different
  657. packages.</p>
  658. </section>
  659. <section id="intra-package-references">
  660. <span id="id2"></span><h3><span class="section-number">6.4.2. </span>Intra-package References<a class="headerlink" href="#intra-package-references" title="Permalink to this headline">¶</a></h3>
  661. <p>When packages are structured into subpackages (as with the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound</span></code> package
  662. in the example), you can use absolute imports to refer to submodules of siblings
  663. packages. For example, if the module <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.filters.vocoder</span></code> needs to use
  664. the <code class="xref py py-mod docutils literal notranslate"><span class="pre">echo</span></code> module in the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package, it can use <code class="docutils literal notranslate"><span class="pre">from</span>
  665. <span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">echo</span></code>.</p>
  666. <p>You can also write relative imports, with the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">module</span> <span class="pre">import</span> <span class="pre">name</span></code> form
  667. of import statement. These imports use leading dots to indicate the current and
  668. parent packages involved in the relative import. From the <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code>
  669. module for example, you might use:</p>
  670. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">.</span> <span class="kn">import</span> <span class="n">echo</span>
  671. <span class="kn">from</span> <span class="nn">..</span> <span class="kn">import</span> <span class="n">formats</span>
  672. <span class="kn">from</span> <span class="nn">..filters</span> <span class="kn">import</span> <span class="n">equalizer</span>
  673. </pre></div>
  674. </div>
  675. <p>Note that relative imports are based on the name of the current module. Since
  676. the name of the main module is always <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>, modules intended for use
  677. as the main module of a Python application must always use absolute imports.</p>
  678. </section>
  679. <section id="packages-in-multiple-directories">
  680. <h3><span class="section-number">6.4.3. </span>Packages in Multiple Directories<a class="headerlink" href="#packages-in-multiple-directories" title="Permalink to this headline">¶</a></h3>
  681. <p>Packages support one more special attribute, <a class="reference internal" href="../reference/import.html#path__" title="__path__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code></a>. This is
  682. initialized to be a list containing the name of the directory holding the
  683. package’s <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> before the code in that file is executed. This
  684. variable can be modified; doing so affects future searches for modules and
  685. subpackages contained in the package.</p>
  686. <p>While this feature is not often needed, it can be used to extend the set of
  687. modules found in a package.</p>
  688. <p class="rubric">Footnotes</p>
  689. <dl class="footnote brackets">
  690. <dt class="label" id="id3"><span class="brackets"><a class="fn-backref" href="#id1">1</a></span></dt>
  691. <dd><p>In fact function definitions are also ‘statements’ that are ‘executed’; the
  692. execution of a module-level function definition adds the function name to
  693. the module’s global namespace.</p>
  694. </dd>
  695. </dl>
  696. </section>
  697. </section>
  698. </section>
  699. <div class="clearer"></div>
  700. </div>
  701. </div>
  702. </div>
  703. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  704. <div class="sphinxsidebarwrapper">
  705. <div>
  706. <h3><a href="../contents.html">Table of Contents</a></h3>
  707. <ul>
  708. <li><a class="reference internal" href="#">6. Modules</a><ul>
  709. <li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
  710. <li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
  711. <li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
  712. <li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
  713. </ul>
  714. </li>
  715. <li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
  716. <li><a class="reference internal" href="#the-dir-function">6.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
  717. <li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
  718. <li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
  719. <li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
  720. <li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
  721. </ul>
  722. </li>
  723. </ul>
  724. </li>
  725. </ul>
  726. </div>
  727. <div>
  728. <h4>Previous topic</h4>
  729. <p class="topless"><a href="datastructures.html"
  730. title="previous chapter"><span class="section-number">5. </span>Data Structures</a></p>
  731. </div>
  732. <div>
  733. <h4>Next topic</h4>
  734. <p class="topless"><a href="inputoutput.html"
  735. title="next chapter"><span class="section-number">7. </span>Input and Output</a></p>
  736. </div>
  737. <div role="note" aria-label="source link">
  738. <h3>This Page</h3>
  739. <ul class="this-page-menu">
  740. <li><a href="../bugs.html">Report a Bug</a></li>
  741. <li>
  742. <a href="https://github.com/python/cpython/blob/main/Doc/tutorial/modules.rst"
  743. rel="nofollow">Show Source
  744. </a>
  745. </li>
  746. </ul>
  747. </div>
  748. </div>
  749. </div>
  750. <div class="clearer"></div>
  751. </div>
  752. <div class="related" role="navigation" aria-label="related navigation">
  753. <h3>Navigation</h3>
  754. <ul>
  755. <li class="right" style="margin-right: 10px">
  756. <a href="../genindex.html" title="General Index"
  757. >index</a></li>
  758. <li class="right" >
  759. <a href="../py-modindex.html" title="Python Module Index"
  760. >modules</a> |</li>
  761. <li class="right" >
  762. <a href="inputoutput.html" title="7. Input and Output"
  763. >next</a> |</li>
  764. <li class="right" >
  765. <a href="datastructures.html" title="5. Data Structures"
  766. >previous</a> |</li>
  767. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  768. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  769. <li class="switchers">
  770. <div class="language_switcher_placeholder"></div>
  771. <div class="version_switcher_placeholder"></div>
  772. </li>
  773. <li>
  774. </li>
  775. <li id="cpython-language-and-version">
  776. <a href="../index.html">3.12.0 Documentation</a> &#187;
  777. </li>
  778. <li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> &#187;</li>
  779. <li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Modules</a></li>
  780. <li class="right">
  781. <div class="inline-search" role="search">
  782. <form class="inline-search" action="../search.html" method="get">
  783. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  784. <input type="submit" value="Go" />
  785. </form>
  786. </div>
  787. |
  788. </li>
  789. <li class="right">
  790. <label class="theme-selector-label">
  791. Theme
  792. <select class="theme-selector" oninput="activateTheme(this.value)">
  793. <option value="auto" selected>Auto</option>
  794. <option value="light">Light</option>
  795. <option value="dark">Dark</option>
  796. </select>
  797. </label> |</li>
  798. </ul>
  799. </div>
  800. <div class="footer">
  801. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  802. <br />
  803. This page is licensed under the Python Software Foundation License Version 2.
  804. <br />
  805. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  806. <br />
  807. See <a href="/license.html">History and License</a> for more information.<br />
  808. <br />
  809. The Python Software Foundation is a non-profit corporation.
  810. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  811. <br />
  812. <br />
  813. Last updated on Oct 02, 2023.
  814. <a href="/bugs.html">Found a bug</a>?
  815. <br />
  816. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  817. </div>
  818. </body>
  819. </html>