mirror of
https://github.com/bunny-lab-io/Borealis.git
synced 2025-10-27 09:01:58 -06:00
Removed the Requirement to Install Python and NodeJS (Now Bundled with Borealis)
This commit is contained in:
458
Dependencies/Python/Doc/html/tutorial/appendix.html
vendored
Normal file
458
Dependencies/Python/Doc/html/tutorial/appendix.html
vendored
Normal file
@@ -0,0 +1,458 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="16. Appendix" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/appendix.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Interactive Mode: There are two variants of the interactive REPL. The classic basic interpreter is supported on all platforms with minimal line control capabilities. On Windows, or Unix-like system..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Interactive Mode: There are two variants of the interactive REPL. The classic basic interpreter is supported on all platforms with minimal line control capabilities. On Windows, or Unix-like system..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>16. Appendix — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="Python Setup and Usage" href="../using/index.html" />
|
||||
<link rel="prev" title="15. Floating-Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/appendix.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">16. Appendix</a><ul>
|
||||
<li><a class="reference internal" href="#interactive-mode">16.1. Interactive Mode</a><ul>
|
||||
<li><a class="reference internal" href="#error-handling">16.1.1. Error Handling</a></li>
|
||||
<li><a class="reference internal" href="#executable-python-scripts">16.1.2. Executable Python Scripts</a></li>
|
||||
<li><a class="reference internal" href="#the-interactive-startup-file">16.1.3. The Interactive Startup File</a></li>
|
||||
<li><a class="reference internal" href="#the-customization-modules">16.1.4. The Customization Modules</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="floatingpoint.html"
|
||||
title="previous chapter"><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="../using/index.html"
|
||||
title="next chapter">Python Setup and Usage</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/appendix.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="../using/index.html" title="Python Setup and Usage"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="floatingpoint.html" title="15. Floating-Point Arithmetic: Issues and Limitations"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">16. </span>Appendix</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="appendix">
|
||||
<span id="tut-appendix"></span><h1><span class="section-number">16. </span>Appendix<a class="headerlink" href="#appendix" title="Link to this heading">¶</a></h1>
|
||||
<section id="interactive-mode">
|
||||
<span id="tut-interac"></span><h2><span class="section-number">16.1. </span>Interactive Mode<a class="headerlink" href="#interactive-mode" title="Link to this heading">¶</a></h2>
|
||||
<p>There are two variants of the interactive <a class="reference internal" href="../glossary.html#term-REPL"><span class="xref std std-term">REPL</span></a>. The classic
|
||||
basic interpreter is supported on all platforms with minimal line
|
||||
control capabilities.</p>
|
||||
<p>On Windows, or Unix-like systems with <a class="reference internal" href="../library/curses.html#module-curses" title="curses: An interface to the curses library, providing portable terminal handling. (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">curses</span></code></a> support,
|
||||
a new interactive shell is used by default.
|
||||
This one supports color, multiline editing, history browsing, and
|
||||
paste mode. To disable color, see <a class="reference internal" href="../using/cmdline.html#using-on-controlling-color"><span class="std std-ref">Controlling color</span></a> for
|
||||
details. Function keys provide some additional functionality.
|
||||
<kbd class="kbd docutils literal notranslate">F1</kbd> enters the interactive help browser <a class="reference internal" href="../library/pydoc.html#module-pydoc" title="pydoc: Documentation generator and online help system."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pydoc</span></code></a>.
|
||||
<kbd class="kbd docutils literal notranslate">F2</kbd> allows for browsing command-line history with neither output nor the
|
||||
<a class="reference internal" href="../glossary.html#term-0"><span class="xref std std-term">>>></span></a> and <a class="reference internal" href="../glossary.html#term-..."><span class="xref std std-term">…</span></a> prompts. <kbd class="kbd docutils literal notranslate">F3</kbd> enters “paste mode”, which
|
||||
makes pasting larger blocks of code easier. Press <kbd class="kbd docutils literal notranslate">F3</kbd> to return to
|
||||
the regular prompt.</p>
|
||||
<p>When using the new interactive shell, exit the shell by typing <kbd class="kbd docutils literal notranslate">exit</kbd>
|
||||
or <kbd class="kbd docutils literal notranslate">quit</kbd>. Adding call parentheses after those commands is not
|
||||
required.</p>
|
||||
<p>If the new interactive shell is not desired, it can be disabled via
|
||||
the <span class="target" id="index-0"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHON_BASIC_REPL"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHON_BASIC_REPL</span></code></a> environment variable.</p>
|
||||
<section id="error-handling">
|
||||
<span id="tut-error"></span><h3><span class="section-number">16.1.1. </span>Error Handling<a class="headerlink" href="#error-handling" title="Link to this heading">¶</a></h3>
|
||||
<p>When an error occurs, the interpreter prints an error message and a stack trace.
|
||||
In interactive mode, it then returns to the primary prompt; when input came from
|
||||
a file, it exits with a nonzero exit status after printing the stack trace.
|
||||
(Exceptions handled by an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause in a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement
|
||||
are not errors in this context.) Some errors are unconditionally fatal and
|
||||
cause an exit with a nonzero exit status; this applies to internal inconsistencies and
|
||||
some cases of running out of memory. All error messages are written to the
|
||||
standard error stream; normal output from executed commands is written to
|
||||
standard output.</p>
|
||||
<p>Typing the interrupt character (usually <kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd> or <kbd class="kbd docutils literal notranslate">Delete</kbd>) to the primary or
|
||||
secondary prompt cancels the input and returns to the primary prompt. <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>
|
||||
Typing an interrupt while a command is executing raises the
|
||||
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception, which may be handled by a <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
|
||||
statement.</p>
|
||||
</section>
|
||||
<section id="executable-python-scripts">
|
||||
<span id="tut-scripts"></span><h3><span class="section-number">16.1.2. </span>Executable Python Scripts<a class="headerlink" href="#executable-python-scripts" title="Link to this heading">¶</a></h3>
|
||||
<p>On BSD’ish Unix systems, Python scripts can be made directly executable, like
|
||||
shell scripts, by putting the line</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python3</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>(assuming that the interpreter is on the user’s <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PATH</span></code>) at the beginning
|
||||
of the script and giving the file an executable mode. The <code class="docutils literal notranslate"><span class="pre">#!</span></code> must be the
|
||||
first two characters of the file. On some platforms, this first line must end
|
||||
with a Unix-style line ending (<code class="docutils literal notranslate"><span class="pre">'\n'</span></code>), not a Windows (<code class="docutils literal notranslate"><span class="pre">'\r\n'</span></code>) line
|
||||
ending. Note that the hash, or pound, character, <code class="docutils literal notranslate"><span class="pre">'#'</span></code>, is used to start a
|
||||
comment in Python.</p>
|
||||
<p>The script can be given an executable mode, or permission, using the
|
||||
<strong class="program">chmod</strong> command.</p>
|
||||
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>chmod<span class="w"> </span>+x<span class="w"> </span>myscript.py
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>On Windows systems, there is no notion of an “executable mode”. The Python
|
||||
installer automatically associates <code class="docutils literal notranslate"><span class="pre">.py</span></code> files with <code class="docutils literal notranslate"><span class="pre">python.exe</span></code> so that
|
||||
a double-click on a Python file will run it as a script. The extension can
|
||||
also be <code class="docutils literal notranslate"><span class="pre">.pyw</span></code>, in that case, the console window that normally appears is
|
||||
suppressed.</p>
|
||||
</section>
|
||||
<section id="the-interactive-startup-file">
|
||||
<span id="tut-startup"></span><h3><span class="section-number">16.1.3. </span>The Interactive Startup File<a class="headerlink" href="#the-interactive-startup-file" title="Link to this heading">¶</a></h3>
|
||||
<p>When you use Python interactively, it is frequently handy to have some standard
|
||||
commands executed every time the interpreter is started. You can do this by
|
||||
setting an environment variable named <span class="target" id="index-2"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONSTARTUP</span></code></a> to the name of a
|
||||
file containing your start-up commands. This is similar to the <code class="file docutils literal notranslate"><span class="pre">.profile</span></code>
|
||||
feature of the Unix shells.</p>
|
||||
<p>This file is only read in interactive sessions, not when Python reads commands
|
||||
from a script, and not when <code class="file docutils literal notranslate"><span class="pre">/dev/tty</span></code> is given as the explicit source of
|
||||
commands (which otherwise behaves like an interactive session). It is executed
|
||||
in the same namespace where interactive commands are executed, so that objects
|
||||
that it defines or imports can be used without qualification in the interactive
|
||||
session. You can also change the prompts <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> in this
|
||||
file.</p>
|
||||
<p>If you want to read an additional start-up file from the current directory, you
|
||||
can program this in the global start-up file using code like <code class="docutils literal notranslate"><span class="pre">if</span>
|
||||
<span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">exec(open('.pythonrc.py').read())</span></code>.
|
||||
If you want to use the startup file in a script, you must do this explicitly
|
||||
in the script:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">os</span>
|
||||
<span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">'PYTHONSTARTUP'</span><span class="p">)</span>
|
||||
<span class="k">if</span> <span class="n">filename</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
|
||||
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span> <span class="k">as</span> <span class="n">fobj</span><span class="p">:</span>
|
||||
<span class="n">startup_file</span> <span class="o">=</span> <span class="n">fobj</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
<span class="n">exec</span><span class="p">(</span><span class="n">startup_file</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="the-customization-modules">
|
||||
<span id="tut-customize"></span><h3><span class="section-number">16.1.4. </span>The Customization Modules<a class="headerlink" href="#the-customization-modules" title="Link to this heading">¶</a></h3>
|
||||
<p>Python provides two hooks to let you customize it: <span class="target" id="index-3"></span>sitecustomize and
|
||||
<span class="target" id="index-4"></span>usercustomize. To see how it works, you need first to find the location
|
||||
of your user site-packages directory. Start Python and run this code:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">site</span>
|
||||
<span class="gp">>>> </span><span class="n">site</span><span class="o">.</span><span class="n">getusersitepackages</span><span class="p">()</span>
|
||||
<span class="go">'/home/user/.local/lib/python3.x/site-packages'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Now you can create a file named <code class="file docutils literal notranslate"><span class="pre">usercustomize.py</span></code> in that directory and
|
||||
put anything you want in it. It will affect every invocation of Python, unless
|
||||
it is started with the <a class="reference internal" href="../using/cmdline.html#cmdoption-s"><code class="xref std std-option docutils literal notranslate"><span class="pre">-s</span></code></a> option to disable the automatic import.</p>
|
||||
<p><span class="target" id="index-5"></span>sitecustomize works in the same way, but is typically created by an
|
||||
administrator of the computer in the global site-packages directory, and is
|
||||
imported before <span class="target" id="index-6"></span>usercustomize. See the documentation of 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 for more details.</p>
|
||||
<p class="rubric">Footnotes</p>
|
||||
<aside class="footnote-list brackets">
|
||||
<aside class="footnote brackets" id="id2" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>A problem with the GNU Readline package may prevent this.</p>
|
||||
</aside>
|
||||
</aside>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">16. Appendix</a><ul>
|
||||
<li><a class="reference internal" href="#interactive-mode">16.1. Interactive Mode</a><ul>
|
||||
<li><a class="reference internal" href="#error-handling">16.1.1. Error Handling</a></li>
|
||||
<li><a class="reference internal" href="#executable-python-scripts">16.1.2. Executable Python Scripts</a></li>
|
||||
<li><a class="reference internal" href="#the-interactive-startup-file">16.1.3. The Interactive Startup File</a></li>
|
||||
<li><a class="reference internal" href="#the-customization-modules">16.1.4. The Customization Modules</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="floatingpoint.html"
|
||||
title="previous chapter"><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="../using/index.html"
|
||||
title="next chapter">Python Setup and Usage</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/appendix.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="../using/index.html" title="Python Setup and Usage"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="floatingpoint.html" title="15. Floating-Point Arithmetic: Issues and Limitations"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">16. </span>Appendix</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
377
Dependencies/Python/Doc/html/tutorial/appetite.html
vendored
Normal file
377
Dependencies/Python/Doc/html/tutorial/appetite.html
vendored
Normal file
@@ -0,0 +1,377 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="1. Whetting Your Appetite" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/appetite.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or ..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or ..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>1. Whetting Your Appetite — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="2. Using the Python Interpreter" href="interpreter.html" />
|
||||
<link rel="prev" title="The Python Tutorial" href="index.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/appetite.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="index.html"
|
||||
title="previous chapter">The Python Tutorial</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="interpreter.html"
|
||||
title="next chapter"><span class="section-number">2. </span>Using the Python Interpreter</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/appetite.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interpreter.html" title="2. Using the Python Interpreter"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="index.html" title="The Python Tutorial"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">1. </span>Whetting Your Appetite</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="whetting-your-appetite">
|
||||
<span id="tut-intro"></span><h1><span class="section-number">1. </span>Whetting Your Appetite<a class="headerlink" href="#whetting-your-appetite" title="Link to this heading">¶</a></h1>
|
||||
<p>If you do much work on computers, eventually you find that there’s some task
|
||||
you’d like to automate. For example, you may wish to perform a
|
||||
search-and-replace over a large number of text files, or rename and rearrange a
|
||||
bunch of photo files in a complicated way. Perhaps you’d like to write a small
|
||||
custom database, or a specialized GUI application, or a simple game.</p>
|
||||
<p>If you’re a professional software developer, you may have to work with several
|
||||
C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is
|
||||
too slow. Perhaps you’re writing a test suite for such a library and find
|
||||
writing the testing code a tedious task. Or maybe you’ve written a program that
|
||||
could use an extension language, and you don’t want to design and implement a
|
||||
whole new language for your application.</p>
|
||||
<p>Python is just the language for you.</p>
|
||||
<p>You could write a Unix shell script or Windows batch files for some of these
|
||||
tasks, but shell scripts are best at moving around files and changing text data,
|
||||
not well-suited for GUI applications or games. You could write a C/C++/Java
|
||||
program, but it can take a lot of development time to get even a first-draft
|
||||
program. Python is simpler to use, available on Windows, macOS, and Unix
|
||||
operating systems, and will help you get the job done more quickly.</p>
|
||||
<p>Python is simple to use, but it is a real programming language, offering much
|
||||
more structure and support for large programs than shell scripts or batch files
|
||||
can offer. On the other hand, Python also offers much more error checking than
|
||||
C, and, being a <em>very-high-level language</em>, it has high-level data types built
|
||||
in, such as flexible arrays and dictionaries. Because of its more general data
|
||||
types Python is applicable to a much larger problem domain than Awk or even
|
||||
Perl, yet many things are at least as easy in Python as in those languages.</p>
|
||||
<p>Python allows you to split your program into modules that can be reused in other
|
||||
Python programs. It comes with a large collection of standard modules that you
|
||||
can use as the basis of your programs — or as examples to start learning to
|
||||
program in Python. Some of these modules provide things like file I/O, system
|
||||
calls, sockets, and even interfaces to graphical user interface toolkits like
|
||||
Tk.</p>
|
||||
<p>Python is an interpreted language, which can save you considerable time during
|
||||
program development because no compilation and linking is necessary. The
|
||||
interpreter can be used interactively, which makes it easy to experiment with
|
||||
features of the language, to write throw-away programs, or to test functions
|
||||
during bottom-up program development. It is also a handy desk calculator.</p>
|
||||
<p>Python enables programs to be written compactly and readably. Programs written
|
||||
in Python are typically much shorter than equivalent C, C++, or Java programs,
|
||||
for several reasons:</p>
|
||||
<ul class="simple">
|
||||
<li><p>the high-level data types allow you to express complex operations in a single
|
||||
statement;</p></li>
|
||||
<li><p>statement grouping is done by indentation instead of beginning and ending
|
||||
brackets;</p></li>
|
||||
<li><p>no variable or argument declarations are necessary.</p></li>
|
||||
</ul>
|
||||
<p>Python is <em>extensible</em>: if you know how to program in C it is easy to add a new
|
||||
built-in function or module to the interpreter, either to perform critical
|
||||
operations at maximum speed, or to link Python programs to libraries that may
|
||||
only be available in binary form (such as a vendor-specific graphics library).
|
||||
Once you are really hooked, you can link the Python interpreter into an
|
||||
application written in C and use it as an extension or command language for that
|
||||
application.</p>
|
||||
<p>By the way, the language is named after the BBC show “Monty Python’s Flying
|
||||
Circus” and has nothing to do with reptiles. Making references to Monty
|
||||
Python skits in documentation is not only allowed, it is encouraged!</p>
|
||||
<p>Now that you are all excited about Python, you’ll want to examine it in some
|
||||
more detail. Since the best way to learn a language is to use it, the tutorial
|
||||
invites you to play with the Python interpreter as you read.</p>
|
||||
<p>In the next chapter, the mechanics of using the interpreter are explained. This
|
||||
is rather mundane information, but essential for trying out the examples shown
|
||||
later.</p>
|
||||
<p>The rest of the tutorial introduces various features of the Python language and
|
||||
system through examples, beginning with simple expressions, statements and data
|
||||
types, through functions and modules, and finally touching upon advanced
|
||||
concepts like exceptions and user-defined classes.</p>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="index.html"
|
||||
title="previous chapter">The Python Tutorial</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="interpreter.html"
|
||||
title="next chapter"><span class="section-number">2. </span>Using the Python Interpreter</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/appetite.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interpreter.html" title="2. Using the Python Interpreter"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="index.html" title="The Python Tutorial"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">1. </span>Whetting Your Appetite</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
1179
Dependencies/Python/Doc/html/tutorial/classes.html
vendored
Normal file
1179
Dependencies/Python/Doc/html/tutorial/classes.html
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1393
Dependencies/Python/Doc/html/tutorial/controlflow.html
vendored
Normal file
1393
Dependencies/Python/Doc/html/tutorial/controlflow.html
vendored
Normal file
File diff suppressed because it is too large
Load Diff
1021
Dependencies/Python/Doc/html/tutorial/datastructures.html
vendored
Normal file
1021
Dependencies/Python/Doc/html/tutorial/datastructures.html
vendored
Normal file
File diff suppressed because it is too large
Load Diff
978
Dependencies/Python/Doc/html/tutorial/errors.html
vendored
Normal file
978
Dependencies/Python/Doc/html/tutorial/errors.html
vendored
Normal file
@@ -0,0 +1,978 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="8. Errors and Exceptions" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/errors.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax error..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Until now error messages haven’t been more than mentioned, but if you have tried out the examples you have probably seen some. There are (at least) two distinguishable kinds of errors: syntax error..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>8. Errors and Exceptions — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="9. Classes" href="classes.html" />
|
||||
<link rel="prev" title="7. Input and Output" href="inputoutput.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/errors.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
|
||||
<li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
|
||||
<li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
|
||||
<li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
|
||||
<li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
|
||||
<li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="inputoutput.html"
|
||||
title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="classes.html"
|
||||
title="next chapter"><span class="section-number">9. </span>Classes</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="classes.html" title="9. Classes"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="inputoutput.html" title="7. Input and Output"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="errors-and-exceptions">
|
||||
<span id="tut-errors"></span><h1><span class="section-number">8. </span>Errors and Exceptions<a class="headerlink" href="#errors-and-exceptions" title="Link to this heading">¶</a></h1>
|
||||
<p>Until now error messages haven’t been more than mentioned, but if you have tried
|
||||
out the examples you have probably seen some. There are (at least) two
|
||||
distinguishable kinds of errors: <em>syntax errors</em> and <em>exceptions</em>.</p>
|
||||
<section id="syntax-errors">
|
||||
<span id="tut-syntaxerrors"></span><h2><span class="section-number">8.1. </span>Syntax Errors<a class="headerlink" href="#syntax-errors" title="Link to this heading">¶</a></h2>
|
||||
<p>Syntax errors, also known as parsing errors, are perhaps the most common kind of
|
||||
complaint you get while you are still learning Python:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Hello world'</span><span class="p">)</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>
|
||||
<span class="w"> </span><span class="k">while</span> <span class="kc">True</span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Hello world'</span><span class="p">)</span>
|
||||
<span class="w"> </span><span class="pm">^^^^^</span>
|
||||
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The parser repeats the offending line and displays little arrows pointing
|
||||
at the place where the error was detected. Note that this is not always the
|
||||
place that needs to be fixed. In the example, the error is detected at the
|
||||
function <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a>, since a colon (<code class="docutils literal notranslate"><span class="pre">':'</span></code>) is missing just before it.</p>
|
||||
<p>The file name (<code class="docutils literal notranslate"><span class="pre"><stdin></span></code> in our example) and line number are printed so you
|
||||
know where to look in case the input came from a file.</p>
|
||||
</section>
|
||||
<section id="exceptions">
|
||||
<span id="tut-exceptions"></span><h2><span class="section-number">8.2. </span>Exceptions<a class="headerlink" href="#exceptions" title="Link to this heading">¶</a></h2>
|
||||
<p>Even if a statement or expression is syntactically correct, it may cause an
|
||||
error when an attempt is made to execute it. Errors detected during execution
|
||||
are called <em>exceptions</em> and are not unconditionally fatal: you will soon learn
|
||||
how to handle them in Python programs. Most exceptions are not handled by
|
||||
programs, however, and result in error messages as shown here:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">0</span><span class="p">)</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="mi">10</span> <span class="o">*</span> <span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">0</span><span class="p">)</span>
|
||||
<span class="w"> </span><span class="pm">~^~</span>
|
||||
<span class="gr">ZeroDivisionError</span>: <span class="n">division by zero</span>
|
||||
<span class="gp">>>> </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="mi">4</span> <span class="o">+</span> <span class="n">spam</span><span class="o">*</span><span class="mi">3</span>
|
||||
<span class="w"> </span><span class="pm">^^^^</span>
|
||||
<span class="gr">NameError</span>: <span class="n">name 'spam' is not defined</span>
|
||||
<span class="gp">>>> </span><span class="s1">'2'</span> <span class="o">+</span> <span class="mi">2</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="s1">'2'</span> <span class="o">+</span> <span class="mi">2</span>
|
||||
<span class="w"> </span><span class="pm">~~~~^~~</span>
|
||||
<span class="gr">TypeError</span>: <span class="n">can only concatenate str (not "int") to str</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The last line of the error message indicates what happened. Exceptions come in
|
||||
different types, and the type is printed as part of the message: the types in
|
||||
the example are <a class="reference internal" href="../library/exceptions.html#ZeroDivisionError" title="ZeroDivisionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ZeroDivisionError</span></code></a>, <a class="reference internal" href="../library/exceptions.html#NameError" title="NameError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">NameError</span></code></a> and <a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a>.
|
||||
The string printed as the exception type is the name of the built-in exception
|
||||
that occurred. This is true for all built-in exceptions, but need not be true
|
||||
for user-defined exceptions (although it is a useful convention). Standard
|
||||
exception names are built-in identifiers (not reserved keywords).</p>
|
||||
<p>The rest of the line provides detail based on the type of exception and what
|
||||
caused it.</p>
|
||||
<p>The preceding part of the error message shows the context where the exception
|
||||
occurred, in the form of a stack traceback. In general it contains a stack
|
||||
traceback listing source lines; however, it will not display lines read from
|
||||
standard input.</p>
|
||||
<p><a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a> lists the built-in exceptions and their meanings.</p>
|
||||
</section>
|
||||
<section id="handling-exceptions">
|
||||
<span id="tut-handling"></span><h2><span class="section-number">8.3. </span>Handling Exceptions<a class="headerlink" href="#handling-exceptions" title="Link to this heading">¶</a></h2>
|
||||
<p>It is possible to write programs that handle selected exceptions. Look at the
|
||||
following example, which asks the user for input until a valid integer has been
|
||||
entered, but allows the user to interrupt the program (using <kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">C</kbd> or
|
||||
whatever the operating system supports); note that a user-generated interruption
|
||||
is signalled by raising the <a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> exception.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="nb">input</span><span class="p">(</span><span class="s2">"Please enter a number: "</span><span class="p">))</span>
|
||||
<span class="gp">... </span> <span class="k">break</span>
|
||||
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Oops! That was no valid number. Try again..."</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement works as follows.</p>
|
||||
<ul class="simple">
|
||||
<li><p>First, the <em>try clause</em> (the statement(s) between the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> and
|
||||
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keywords) is executed.</p></li>
|
||||
<li><p>If no exception occurs, the <em>except clause</em> is skipped and execution of the
|
||||
<a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement is finished.</p></li>
|
||||
<li><p>If an exception occurs during execution of the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause, the rest of the
|
||||
clause is skipped. Then, if its type matches the exception named after the
|
||||
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> keyword, the <em>except clause</em> is executed, and then execution
|
||||
continues after the try/except block.</p></li>
|
||||
<li><p>If an exception occurs which does not match the exception named in the <em>except
|
||||
clause</em>, it is passed on to outer <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statements; if no handler is
|
||||
found, it is an <em>unhandled exception</em> and execution stops with an error message.</p></li>
|
||||
</ul>
|
||||
<p>A <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement may have more than one <em>except clause</em>, to specify
|
||||
handlers for different exceptions. At most one handler will be executed.
|
||||
Handlers only handle exceptions that occur in the corresponding <em>try clause</em>,
|
||||
not in other handlers of the same <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement. An <em>except clause</em>
|
||||
may name multiple exceptions as a parenthesized tuple, for example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="o">...</span> <span class="k">except</span> <span class="p">(</span><span class="ne">RuntimeError</span><span class="p">,</span> <span class="ne">TypeError</span><span class="p">,</span> <span class="ne">NameError</span><span class="p">):</span>
|
||||
<span class="o">...</span> <span class="k">pass</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>A class in an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause matches exceptions which are instances of the
|
||||
class itself or one of its derived classes (but not the other way around — an
|
||||
<em>except clause</em> listing a derived class does not match instances of its base classes).
|
||||
For example, the following code will print B, C, D in that order:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span><span class="w"> </span><span class="nc">B</span><span class="p">(</span><span class="ne">Exception</span><span class="p">):</span>
|
||||
<span class="k">pass</span>
|
||||
|
||||
<span class="k">class</span><span class="w"> </span><span class="nc">C</span><span class="p">(</span><span class="n">B</span><span class="p">):</span>
|
||||
<span class="k">pass</span>
|
||||
|
||||
<span class="k">class</span><span class="w"> </span><span class="nc">D</span><span class="p">(</span><span class="n">C</span><span class="p">):</span>
|
||||
<span class="k">pass</span>
|
||||
|
||||
<span class="k">for</span> <span class="bp">cls</span> <span class="ow">in</span> <span class="p">[</span><span class="n">B</span><span class="p">,</span> <span class="n">C</span><span class="p">,</span> <span class="n">D</span><span class="p">]:</span>
|
||||
<span class="k">try</span><span class="p">:</span>
|
||||
<span class="k">raise</span> <span class="bp">cls</span><span class="p">()</span>
|
||||
<span class="k">except</span> <span class="n">D</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"D"</span><span class="p">)</span>
|
||||
<span class="k">except</span> <span class="n">C</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"C"</span><span class="p">)</span>
|
||||
<span class="k">except</span> <span class="n">B</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"B"</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that if the <em>except clauses</em> were reversed (with <code class="docutils literal notranslate"><span class="pre">except</span> <span class="pre">B</span></code> first), it
|
||||
would have printed B, B, B — the first matching <em>except clause</em> is triggered.</p>
|
||||
<p>When an exception occurs, it may have associated values, also known as the
|
||||
exception’s <em>arguments</em>. The presence and types of the arguments depend on the
|
||||
exception type.</p>
|
||||
<p>The <em>except clause</em> may specify a variable after the exception name. The
|
||||
variable is bound to the exception instance which typically has an <code class="docutils literal notranslate"><span class="pre">args</span></code>
|
||||
attribute that stores the arguments. For convenience, builtin exception
|
||||
types define <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> to print all the arguments without explicitly
|
||||
accessing <code class="docutils literal notranslate"><span class="pre">.args</span></code>.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">Exception</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">inst</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">type</span><span class="p">(</span><span class="n">inst</span><span class="p">))</span> <span class="c1"># the exception type</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="o">.</span><span class="n">args</span><span class="p">)</span> <span class="c1"># arguments stored in .args</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">inst</span><span class="p">)</span> <span class="c1"># __str__ allows args to be printed directly,</span>
|
||||
<span class="gp">... </span> <span class="c1"># but may be overridden in exception subclasses</span>
|
||||
<span class="gp">... </span> <span class="n">x</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">inst</span><span class="o">.</span><span class="n">args</span> <span class="c1"># unpack args</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'x ='</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'y ='</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go"><class 'Exception'></span>
|
||||
<span class="go">('spam', 'eggs')</span>
|
||||
<span class="go">('spam', 'eggs')</span>
|
||||
<span class="go">x = spam</span>
|
||||
<span class="go">y = eggs</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The exception’s <a class="reference internal" href="../reference/datamodel.html#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> output is printed as the last part (‘detail’)
|
||||
of the message for unhandled exceptions.</p>
|
||||
<p><a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-exc docutils literal notranslate"><span class="pre">BaseException</span></code></a> is the common base class of all exceptions. One of its
|
||||
subclasses, <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a>, is the base class of all the non-fatal exceptions.
|
||||
Exceptions which are not subclasses of <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> are not typically
|
||||
handled, because they are used to indicate that the program should terminate.
|
||||
They include <a class="reference internal" href="../library/exceptions.html#SystemExit" title="SystemExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SystemExit</span></code></a> which is raised by <a class="reference internal" href="../library/sys.html#sys.exit" title="sys.exit"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sys.exit()</span></code></a> and
|
||||
<a class="reference internal" href="../library/exceptions.html#KeyboardInterrupt" title="KeyboardInterrupt"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyboardInterrupt</span></code></a> which is raised when a user wishes to interrupt
|
||||
the program.</p>
|
||||
<p><a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> can be used as a wildcard that catches (almost) everything.
|
||||
However, it is good practice to be as specific as possible with the types
|
||||
of exceptions that we intend to handle, and to allow any unexpected
|
||||
exceptions to propagate on.</p>
|
||||
<p>The most common pattern for handling <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> is to print or log
|
||||
the exception and then re-raise it (allowing a caller to handle the
|
||||
exception as well):</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
|
||||
|
||||
<span class="k">try</span><span class="p">:</span>
|
||||
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'myfile.txt'</span><span class="p">)</span>
|
||||
<span class="n">s</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
|
||||
<span class="n">i</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">s</span><span class="o">.</span><span class="n">strip</span><span class="p">())</span>
|
||||
<span class="k">except</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"OS error:"</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
|
||||
<span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s2">"Could not convert data to an integer."</span><span class="p">)</span>
|
||||
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s2">"Unexpected </span><span class="si">{</span><span class="n">err</span><span class="si">=}</span><span class="s2">, </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">err</span><span class="p">)</span><span class="si">=}</span><span class="s2">"</span><span class="p">)</span>
|
||||
<span class="k">raise</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> … <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement has an optional <em>else
|
||||
clause</em>, which, when present, must follow all <em>except clauses</em>. It is useful
|
||||
for code that must be executed if the <em>try clause</em> does not raise an exception.
|
||||
For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">arg</span> <span class="ow">in</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>
|
||||
<span class="k">try</span><span class="p">:</span>
|
||||
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">'r'</span><span class="p">)</span>
|
||||
<span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s1">'cannot open'</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
|
||||
<span class="k">else</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s1">'has'</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">readlines</span><span class="p">()),</span> <span class="s1">'lines'</span><span class="p">)</span>
|
||||
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The use of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause is better than adding additional code to
|
||||
the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> clause because it avoids accidentally catching an exception
|
||||
that wasn’t raised by the code being protected by the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> …
|
||||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code> statement.</p>
|
||||
<p>Exception handlers do not handle only exceptions that occur immediately in the
|
||||
<em>try clause</em>, but also those that occur inside functions that are called (even
|
||||
indirectly) in the <em>try clause</em>. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">this_fails</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="n">x</span> <span class="o">=</span> <span class="mi">1</span><span class="o">/</span><span class="mi">0</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">this_fails</span><span class="p">()</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">ZeroDivisionError</span> <span class="k">as</span> <span class="n">err</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Handling run-time error:'</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">Handling run-time error: division by zero</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="raising-exceptions">
|
||||
<span id="tut-raising"></span><h2><span class="section-number">8.4. </span>Raising Exceptions<a class="headerlink" href="#raising-exceptions" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows the programmer to force a specified
|
||||
exception to occur. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
|
||||
<span class="gr">NameError</span>: <span class="n">HiThere</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The sole argument to <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> indicates the exception to be raised.
|
||||
This must be either an exception instance or an exception class (a class that
|
||||
derives from <a class="reference internal" href="../library/exceptions.html#BaseException" title="BaseException"><code class="xref py py-class docutils literal notranslate"><span class="pre">BaseException</span></code></a>, such as <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> or one of its
|
||||
subclasses). If an exception class is passed, it will be implicitly
|
||||
instantiated by calling its constructor with no arguments:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">raise</span> <span class="ne">ValueError</span> <span class="c1"># shorthand for 'raise ValueError()'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you need to determine whether an exception was raised but don’t intend to
|
||||
handle it, a simpler form of the <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows you to
|
||||
re-raise the exception:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">NameError</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'An exception flew by!'</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">An exception flew by!</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">NameError</span><span class="p">(</span><span class="s1">'HiThere'</span><span class="p">)</span>
|
||||
<span class="gr">NameError</span>: <span class="n">HiThere</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="exception-chaining">
|
||||
<span id="tut-exception-chaining"></span><h2><span class="section-number">8.5. </span>Exception Chaining<a class="headerlink" href="#exception-chaining" title="Link to this heading">¶</a></h2>
|
||||
<p>If an unhandled exception occurs inside an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> section, it will
|
||||
have the exception being handled attached to it and included in the error
|
||||
message:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s2">"database.sqlite"</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">"unable to handle error"</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="nb">open</span><span class="p">(</span><span class="s2">"database.sqlite"</span><span class="p">)</span>
|
||||
<span class="w"> </span><span class="pm">~~~~^^^^^^^^^^^^^^^^^^^</span>
|
||||
<span class="gr">FileNotFoundError</span>: <span class="n">[Errno 2] No such file or directory: 'database.sqlite'</span>
|
||||
|
||||
<span class="gt">During handling of the above exception, another exception occurred:</span>
|
||||
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s2">"unable to handle error"</span><span class="p">)</span>
|
||||
<span class="gr">RuntimeError</span>: <span class="n">unable to handle error</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>To indicate that an exception is a direct consequence of another, the
|
||||
<a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">raise</span></code></a> statement allows an optional <a class="reference internal" href="../reference/simple_stmts.html#raise"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">from</span></code></a> clause:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># exc must be exception instance or None.</span>
|
||||
<span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span><span class="w"> </span><span class="nn">exc</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This can be useful when you are transforming exceptions. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">func</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">ConnectionError</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">func</span><span class="p">()</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">ConnectionError</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s1">'Failed to open database'</span><span class="p">)</span> <span class="kn">from</span><span class="w"> </span><span class="nn">exc</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="n">func</span><span class="p">()</span>
|
||||
<span class="w"> </span><span class="pm">~~~~^^</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n">func</span>
|
||||
<span class="gr">ConnectionError</span>
|
||||
|
||||
<span class="gt">The above exception was the direct cause of the following exception:</span>
|
||||
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">RuntimeError</span><span class="p">(</span><span class="s1">'Failed to open database'</span><span class="p">)</span> <span class="kn">from</span><span class="w"> </span><span class="nn">exc</span>
|
||||
<span class="gr">RuntimeError</span>: <span class="n">Failed to open database</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>It also allows disabling automatic exception chaining using the <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">None</span></code>
|
||||
idiom:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">open</span><span class="p">(</span><span class="s1">'database.sqlite'</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">OSError</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span><span class="w"> </span><span class="kc">None</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">4</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">RuntimeError</span> <span class="kn">from</span><span class="w"> </span><span class="kc">None</span>
|
||||
<span class="gr">RuntimeError</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For more information about chaining mechanics, see <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">Built-in Exceptions</span></a>.</p>
|
||||
</section>
|
||||
<section id="user-defined-exceptions">
|
||||
<span id="tut-userexceptions"></span><h2><span class="section-number">8.6. </span>User-defined Exceptions<a class="headerlink" href="#user-defined-exceptions" title="Link to this heading">¶</a></h2>
|
||||
<p>Programs may name their own exceptions by creating a new exception class (see
|
||||
<a class="reference internal" href="classes.html#tut-classes"><span class="std std-ref">Classes</span></a> for more about Python classes). Exceptions should typically
|
||||
be derived from the <a class="reference internal" href="../library/exceptions.html#Exception" title="Exception"><code class="xref py py-exc docutils literal notranslate"><span class="pre">Exception</span></code></a> class, either directly or indirectly.</p>
|
||||
<p>Exception classes can be defined which do anything any other class can do, but
|
||||
are usually kept simple, often only offering a number of attributes that allow
|
||||
information about the error to be extracted by handlers for the exception.</p>
|
||||
<p>Most exceptions are defined with names that end in “Error”, similar to the
|
||||
naming of the standard exceptions.</p>
|
||||
<p>Many standard modules define their own exceptions to report errors that may
|
||||
occur in functions they define.</p>
|
||||
</section>
|
||||
<section id="defining-clean-up-actions">
|
||||
<span id="tut-cleanup"></span><h2><span class="section-number">8.7. </span>Defining Clean-up Actions<a class="headerlink" href="#defining-clean-up-actions" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement has another optional clause which is intended to
|
||||
define clean-up actions that must be executed under all circumstances. For
|
||||
example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
|
||||
<span class="gp">... </span><span class="k">finally</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'Goodbye, world!'</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">Goodbye, world!</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">KeyboardInterrupt</span>
|
||||
<span class="nc">KeyboardInterrupt</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If a <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is present, the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
|
||||
clause will execute as the last task before the <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>
|
||||
statement completes. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause runs whether or
|
||||
not the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement produces an exception. The following
|
||||
points discuss more complex cases when an exception occurs:</p>
|
||||
<ul class="simple">
|
||||
<li><p>If an exception occurs during execution of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code>
|
||||
clause, the exception may be handled by an <a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a>
|
||||
clause. If the exception is not handled by an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code>
|
||||
clause, the exception is re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
|
||||
clause has been executed.</p></li>
|
||||
<li><p>An exception could occur during execution of an <code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code>
|
||||
or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> clause. Again, the exception is re-raised after
|
||||
the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause has been executed.</p></li>
|
||||
<li><p>If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause executes a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>,
|
||||
<a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, exceptions are not
|
||||
re-raised.</p></li>
|
||||
<li><p>If the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> statement reaches a <a class="reference internal" href="../reference/simple_stmts.html#break"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code></a>,
|
||||
<a class="reference internal" href="../reference/simple_stmts.html#continue"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code></a> or <a class="reference internal" href="../reference/simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement, the
|
||||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause will execute just prior to the
|
||||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code>, <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> or <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
|
||||
statement’s execution.</p></li>
|
||||
<li><p>If a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause includes a <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
|
||||
statement, the returned value will be the one from the
|
||||
<code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code> clause’s <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code> statement, not the
|
||||
value from the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code> clause’s <code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code>
|
||||
statement.</p></li>
|
||||
</ul>
|
||||
<p>For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">bool_return</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">return</span> <span class="kc">True</span>
|
||||
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">return</span> <span class="kc">False</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">bool_return</span><span class="p">()</span>
|
||||
<span class="go">False</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>A more complicated example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">divide</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
|
||||
<span class="gp">... </span> <span class="k">except</span> <span class="ne">ZeroDivisionError</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"division by zero!"</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="k">else</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"result is"</span><span class="p">,</span> <span class="n">result</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="k">finally</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"executing finally clause"</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
|
||||
<span class="go">result is 2.0</span>
|
||||
<span class="go">executing finally clause</span>
|
||||
<span class="gp">>>> </span><span class="n">divide</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
|
||||
<span class="go">division by zero!</span>
|
||||
<span class="go">executing finally clause</span>
|
||||
<span class="gp">>>> </span><span class="n">divide</span><span class="p">(</span><span class="s2">"2"</span><span class="p">,</span> <span class="s2">"1"</span><span class="p">)</span>
|
||||
<span class="go">executing finally clause</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="n">divide</span><span class="p">(</span><span class="s2">"2"</span><span class="p">,</span> <span class="s2">"1"</span><span class="p">)</span>
|
||||
<span class="w"> </span><span class="pm">~~~~~~^^^^^^^^^^</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">3</span>, in <span class="n">divide</span>
|
||||
<span class="w"> </span><span class="n">result</span> <span class="o">=</span> <span class="n">x</span> <span class="o">/</span> <span class="n">y</span>
|
||||
<span class="w"> </span><span class="pm">~~^~~</span>
|
||||
<span class="gr">TypeError</span>: <span class="n">unsupported operand type(s) for /: 'str' and 'str'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>As you can see, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is executed in any event. The
|
||||
<a class="reference internal" href="../library/exceptions.html#TypeError" title="TypeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TypeError</span></code></a> raised by dividing two strings is not handled by the
|
||||
<a class="reference internal" href="../reference/compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> clause and therefore re-raised after the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code>
|
||||
clause has been executed.</p>
|
||||
<p>In real world applications, the <a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause is useful for
|
||||
releasing external resources (such as files or network connections), regardless
|
||||
of whether the use of the resource was successful.</p>
|
||||
</section>
|
||||
<section id="predefined-clean-up-actions">
|
||||
<span id="tut-cleanup-with"></span><h2><span class="section-number">8.8. </span>Predefined Clean-up Actions<a class="headerlink" href="#predefined-clean-up-actions" title="Link to this heading">¶</a></h2>
|
||||
<p>Some objects define standard clean-up actions to be undertaken when the object
|
||||
is no longer needed, regardless of whether or not the operation using the object
|
||||
succeeded or failed. Look at the following example, which tries to open a file
|
||||
and print its contents to the screen.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"myfile.txt"</span><span class="p">):</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">""</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The problem with this code is that it leaves the file open for an indeterminate
|
||||
amount of time after this part of the code has finished executing.
|
||||
This is not an issue in simple scripts, but can be a problem for larger
|
||||
applications. The <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement allows objects like files to be
|
||||
used in a way that ensures they are always cleaned up promptly and correctly.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s2">"myfile.txt"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
|
||||
<span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s2">""</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>After the statement is executed, the file <em>f</em> is always closed, even if a
|
||||
problem was encountered while processing the lines. Objects which, like files,
|
||||
provide predefined clean-up actions will indicate this in their documentation.</p>
|
||||
</section>
|
||||
<section id="raising-and-handling-multiple-unrelated-exceptions">
|
||||
<span id="tut-exception-groups"></span><h2><span class="section-number">8.9. </span>Raising and Handling Multiple Unrelated Exceptions<a class="headerlink" href="#raising-and-handling-multiple-unrelated-exceptions" title="Link to this heading">¶</a></h2>
|
||||
<p>There are situations where it is necessary to report several exceptions that
|
||||
have occurred. This is often the case in concurrency frameworks, when several
|
||||
tasks may have failed in parallel, but there are also other use cases where
|
||||
it is desirable to continue execution and collect multiple errors rather than
|
||||
raise the first exception.</p>
|
||||
<p>The builtin <a class="reference internal" href="../library/exceptions.html#ExceptionGroup" title="ExceptionGroup"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ExceptionGroup</span></code></a> wraps a list of exception instances so
|
||||
that they can be raised together. It is an exception itself, so it can be
|
||||
caught like any other exception.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="n">excs</span> <span class="o">=</span> <span class="p">[</span><span class="ne">OSError</span><span class="p">(</span><span class="s1">'error 1'</span><span class="p">),</span> <span class="ne">SystemError</span><span class="p">(</span><span class="s1">'error 2'</span><span class="p">)]</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">'there were problems'</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="p">()</span>
|
||||
<span class="go"> + Exception Group Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 1, in <module></span>
|
||||
<span class="go"> | f()</span>
|
||||
<span class="go"> | ~^^</span>
|
||||
<span class="go"> | File "<stdin>", line 3, in f</span>
|
||||
<span class="go"> | raise ExceptionGroup('there were problems', excs)</span>
|
||||
<span class="go"> | ExceptionGroup: there were problems (2 sub-exceptions)</span>
|
||||
<span class="go"> +-+---------------- 1 ----------------</span>
|
||||
<span class="go"> | OSError: error 1</span>
|
||||
<span class="go"> +---------------- 2 ----------------</span>
|
||||
<span class="go"> | SystemError: error 2</span>
|
||||
<span class="go"> +------------------------------------</span>
|
||||
<span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'caught </span><span class="si">{</span><span class="nb">type</span><span class="p">(</span><span class="n">e</span><span class="p">)</span><span class="si">}</span><span class="s1">: e'</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">caught <class 'ExceptionGroup'>: e</span>
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>By using <code class="docutils literal notranslate"><span class="pre">except*</span></code> instead of <code class="docutils literal notranslate"><span class="pre">except</span></code>, we can selectively
|
||||
handle only the exceptions in the group that match a certain
|
||||
type. In the following example, which shows a nested exception
|
||||
group, each <code class="docutils literal notranslate"><span class="pre">except*</span></code> clause extracts from the group exceptions
|
||||
of a certain type while letting all other exceptions propagate to
|
||||
other clauses and eventually to be reraised.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span>
|
||||
<span class="gp">... </span> <span class="s2">"group1"</span><span class="p">,</span>
|
||||
<span class="gp">... </span> <span class="p">[</span>
|
||||
<span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span>
|
||||
<span class="gp">... </span> <span class="ne">SystemError</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span>
|
||||
<span class="gp">... </span> <span class="n">ExceptionGroup</span><span class="p">(</span>
|
||||
<span class="gp">... </span> <span class="s2">"group2"</span><span class="p">,</span>
|
||||
<span class="gp">... </span> <span class="p">[</span>
|
||||
<span class="gp">... </span> <span class="ne">OSError</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span>
|
||||
<span class="gp">... </span> <span class="ne">RecursionError</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="p">]</span>
|
||||
<span class="gp">... </span> <span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="p">]</span>
|
||||
<span class="gp">... </span> <span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
|
||||
<span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">OSError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"There were OSErrors"</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span><span class="o">*</span> <span class="ne">SystemError</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"There were SystemErrors"</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">There were OSErrors</span>
|
||||
<span class="go">There were SystemErrors</span>
|
||||
<span class="go"> + Exception Group Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 2, in <module></span>
|
||||
<span class="go"> | f()</span>
|
||||
<span class="go"> | ~^^</span>
|
||||
<span class="go"> | File "<stdin>", line 2, in f</span>
|
||||
<span class="go"> | raise ExceptionGroup(</span>
|
||||
<span class="go"> | ...<12 lines>...</span>
|
||||
<span class="go"> | )</span>
|
||||
<span class="go"> | ExceptionGroup: group1 (1 sub-exception)</span>
|
||||
<span class="go"> +-+---------------- 1 ----------------</span>
|
||||
<span class="go"> | ExceptionGroup: group2 (1 sub-exception)</span>
|
||||
<span class="go"> +-+---------------- 1 ----------------</span>
|
||||
<span class="go"> | RecursionError: 4</span>
|
||||
<span class="go"> +------------------------------------</span>
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that the exceptions nested in an exception group must be instances,
|
||||
not types. This is because in practice the exceptions would typically
|
||||
be ones that have already been raised and caught by the program, along
|
||||
the following pattern:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
|
||||
<span class="gp">... </span><span class="k">for</span> <span class="n">test</span> <span class="ow">in</span> <span class="n">tests</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">test</span><span class="o">.</span><span class="n">run</span><span class="p">()</span>
|
||||
<span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">excs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="k">if</span> <span class="n">excs</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s2">"Test Failures"</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="enriching-exceptions-with-notes">
|
||||
<span id="tut-exception-notes"></span><h2><span class="section-number">8.10. </span>Enriching Exceptions with Notes<a class="headerlink" href="#enriching-exceptions-with-notes" title="Link to this heading">¶</a></h2>
|
||||
<p>When an exception is created in order to be raised, it is usually initialized
|
||||
with information that describes the error that has occurred. There are cases
|
||||
where it is useful to add information after the exception was caught. For this
|
||||
purpose, exceptions have a method <code class="docutils literal notranslate"><span class="pre">add_note(note)</span></code> that accepts a string and
|
||||
adds it to the exception’s notes list. The standard traceback rendering
|
||||
includes all notes, in the order they were added, after the exception.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">'bad type'</span><span class="p">)</span>
|
||||
<span class="gp">... </span><span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="s1">'Add some information'</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="s1">'Add some more information'</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">2</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span><span class="s1">'bad type'</span><span class="p">)</span>
|
||||
<span class="gr">TypeError</span>: <span class="n">bad type</span>
|
||||
<span class="x">Add some information</span>
|
||||
<span class="x">Add some more information</span>
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For example, when collecting exceptions into an exception group, we may want
|
||||
to add context information for the individual errors. In the following each
|
||||
exception in the group has a note indicating when this error has occurred.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">def</span><span class="w"> </span><span class="nf">f</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="k">raise</span> <span class="ne">OSError</span><span class="p">(</span><span class="s1">'operation failed'</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">excs</span> <span class="o">=</span> <span class="p">[]</span>
|
||||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="k">try</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">f</span><span class="p">()</span>
|
||||
<span class="gp">... </span> <span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">e</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">e</span><span class="o">.</span><span class="n">add_note</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Happened in Iteration </span><span class="si">{</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="n">excs</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">e</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="k">raise</span> <span class="n">ExceptionGroup</span><span class="p">(</span><span class="s1">'We have some problems'</span><span class="p">,</span> <span class="n">excs</span><span class="p">)</span>
|
||||
<span class="go"> + Exception Group Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 1, in <module></span>
|
||||
<span class="go"> | raise ExceptionGroup('We have some problems', excs)</span>
|
||||
<span class="go"> | ExceptionGroup: We have some problems (3 sub-exceptions)</span>
|
||||
<span class="go"> +-+---------------- 1 ----------------</span>
|
||||
<span class="go"> | Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 3, in <module></span>
|
||||
<span class="go"> | f()</span>
|
||||
<span class="go"> | ~^^</span>
|
||||
<span class="go"> | File "<stdin>", line 2, in f</span>
|
||||
<span class="go"> | raise OSError('operation failed')</span>
|
||||
<span class="go"> | OSError: operation failed</span>
|
||||
<span class="go"> | Happened in Iteration 1</span>
|
||||
<span class="go"> +---------------- 2 ----------------</span>
|
||||
<span class="go"> | Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 3, in <module></span>
|
||||
<span class="go"> | f()</span>
|
||||
<span class="go"> | ~^^</span>
|
||||
<span class="go"> | File "<stdin>", line 2, in f</span>
|
||||
<span class="go"> | raise OSError('operation failed')</span>
|
||||
<span class="go"> | OSError: operation failed</span>
|
||||
<span class="go"> | Happened in Iteration 2</span>
|
||||
<span class="go"> +---------------- 3 ----------------</span>
|
||||
<span class="go"> | Traceback (most recent call last):</span>
|
||||
<span class="go"> | File "<stdin>", line 3, in <module></span>
|
||||
<span class="go"> | f()</span>
|
||||
<span class="go"> | ~^^</span>
|
||||
<span class="go"> | File "<stdin>", line 2, in f</span>
|
||||
<span class="go"> | raise OSError('operation failed')</span>
|
||||
<span class="go"> | OSError: operation failed</span>
|
||||
<span class="go"> | Happened in Iteration 3</span>
|
||||
<span class="go"> +------------------------------------</span>
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">8. Errors and Exceptions</a><ul>
|
||||
<li><a class="reference internal" href="#syntax-errors">8.1. Syntax Errors</a></li>
|
||||
<li><a class="reference internal" href="#exceptions">8.2. Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#handling-exceptions">8.3. Handling Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#raising-exceptions">8.4. Raising Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#exception-chaining">8.5. Exception Chaining</a></li>
|
||||
<li><a class="reference internal" href="#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
|
||||
<li><a class="reference internal" href="#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
|
||||
<li><a class="reference internal" href="#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
|
||||
<li><a class="reference internal" href="#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="inputoutput.html"
|
||||
title="previous chapter"><span class="section-number">7. </span>Input and Output</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="classes.html"
|
||||
title="next chapter"><span class="section-number">9. </span>Classes</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/errors.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="classes.html" title="9. Classes"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="inputoutput.html" title="7. Input and Output"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">8. </span>Errors and Exceptions</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
623
Dependencies/Python/Doc/html/tutorial/floatingpoint.html
vendored
Normal file
623
Dependencies/Python/Doc/html/tutorial/floatingpoint.html
vendored
Normal file
@@ -0,0 +1,623 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="15. Floating-Point Arithmetic: Issues and Limitations" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/floatingpoint.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.625 has value 6/10 + 2/100 + 5/1000, and in the same way the binary fra..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. For example, the decimal fraction 0.625 has value 6/10 + 2/100 + 5/1000, and in the same way the binary fra..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>15. Floating-Point Arithmetic: Issues and Limitations — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="16. Appendix" href="appendix.html" />
|
||||
<link rel="prev" title="14. Interactive Input Editing and History Substitution" href="interactive.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/floatingpoint.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">15. Floating-Point Arithmetic: Issues and Limitations</a><ul>
|
||||
<li><a class="reference internal" href="#representation-error">15.1. Representation Error</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="interactive.html"
|
||||
title="previous chapter"><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="appendix.html"
|
||||
title="next chapter"><span class="section-number">16. </span>Appendix</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/floatingpoint.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appendix.html" title="16. Appendix"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="floating-point-arithmetic-issues-and-limitations">
|
||||
<span id="tut-fp-issues"></span><h1><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations<a class="headerlink" href="#floating-point-arithmetic-issues-and-limitations" title="Link to this heading">¶</a></h1>
|
||||
<p>Floating-point numbers are represented in computer hardware as base 2 (binary)
|
||||
fractions. For example, the <strong>decimal</strong> fraction <code class="docutils literal notranslate"><span class="pre">0.625</span></code>
|
||||
has value 6/10 + 2/100 + 5/1000, and in the same way the <strong>binary</strong> fraction <code class="docutils literal notranslate"><span class="pre">0.101</span></code>
|
||||
has value 1/2 + 0/4 + 1/8. These two fractions have identical values, the only
|
||||
real difference being that the first is written in base 10 fractional notation,
|
||||
and the second in base 2.</p>
|
||||
<p>Unfortunately, most decimal fractions cannot be represented exactly as binary
|
||||
fractions. A consequence is that, in general, the decimal floating-point
|
||||
numbers you enter are only approximated by the binary floating-point numbers
|
||||
actually stored in the machine.</p>
|
||||
<p>The problem is easier to understand at first in base 10. Consider the fraction
|
||||
1/3. You can approximate that as a base 10 fraction:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.3</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>or, better,</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.33</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>or, better,</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.333</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>and so on. No matter how many digits you’re willing to write down, the result
|
||||
will never be exactly 1/3, but will be an increasingly better approximation of
|
||||
1/3.</p>
|
||||
<p>In the same way, no matter how many base 2 digits you’re willing to use, the
|
||||
decimal value 0.1 cannot be represented exactly as a base 2 fraction. In base
|
||||
2, 1/10 is the infinitely repeating fraction</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mf">0.0001100110011001100110011001100110011001100110011</span><span class="o">...</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Stop at any finite number of bits, and you get an approximation. On most
|
||||
machines today, floats are approximated using a binary fraction with
|
||||
the numerator using the first 53 bits starting with the most significant bit and
|
||||
with the denominator as a power of two. In the case of 1/10, the binary fraction
|
||||
is <code class="docutils literal notranslate"><span class="pre">3602879701896397</span> <span class="pre">/</span> <span class="pre">2</span> <span class="pre">**</span> <span class="pre">55</span></code> which is close to but not exactly
|
||||
equal to the true value of 1/10.</p>
|
||||
<p>Many users are not aware of the approximation because of the way values are
|
||||
displayed. Python only prints a decimal approximation to the true decimal
|
||||
value of the binary approximation stored by the machine. On most machines, if
|
||||
Python were to print the true decimal value of the binary approximation stored
|
||||
for 0.1, it would have to display:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mf">0.1</span>
|
||||
<span class="go">0.1000000000000000055511151231257827021181583404541015625</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>That is more digits than most people find useful, so Python keeps the number
|
||||
of digits manageable by displaying a rounded value instead:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">1</span> <span class="o">/</span> <span class="mi">10</span>
|
||||
<span class="go">0.1</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Just remember, even though the printed result looks like the exact value
|
||||
of 1/10, the actual stored value is the nearest representable binary fraction.</p>
|
||||
<p>Interestingly, there are many different decimal numbers that share the same
|
||||
nearest approximate binary fraction. For example, the numbers <code class="docutils literal notranslate"><span class="pre">0.1</span></code> and
|
||||
<code class="docutils literal notranslate"><span class="pre">0.10000000000000001</span></code> and
|
||||
<code class="docutils literal notranslate"><span class="pre">0.1000000000000000055511151231257827021181583404541015625</span></code> are all
|
||||
approximated by <code class="docutils literal notranslate"><span class="pre">3602879701896397</span> <span class="pre">/</span> <span class="pre">2</span> <span class="pre">**</span> <span class="pre">55</span></code>. Since all of these decimal
|
||||
values share the same approximation, any one of them could be displayed
|
||||
while still preserving the invariant <code class="docutils literal notranslate"><span class="pre">eval(repr(x))</span> <span class="pre">==</span> <span class="pre">x</span></code>.</p>
|
||||
<p>Historically, the Python prompt and built-in <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> function would choose
|
||||
the one with 17 significant digits, <code class="docutils literal notranslate"><span class="pre">0.10000000000000001</span></code>. Starting with
|
||||
Python 3.1, Python (on most systems) is now able to choose the shortest of
|
||||
these and simply display <code class="docutils literal notranslate"><span class="pre">0.1</span></code>.</p>
|
||||
<p>Note that this is in the very nature of binary floating point: this is not a bug
|
||||
in Python, and it is not a bug in your code either. You’ll see the same kind of
|
||||
thing in all languages that support your hardware’s floating-point arithmetic
|
||||
(although some languages may not <em>display</em> the difference by default, or in all
|
||||
output modes).</p>
|
||||
<p>For more pleasant output, you may wish to use string formatting to produce a
|
||||
limited number of significant digits:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="s1">'.12g'</span><span class="p">)</span> <span class="c1"># give 12 significant digits</span>
|
||||
<span class="go">'3.14159265359'</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="nb">format</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="s1">'.2f'</span><span class="p">)</span> <span class="c1"># give 2 digits after the point</span>
|
||||
<span class="go">'3.14'</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="nb">repr</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
|
||||
<span class="go">'3.141592653589793'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>It’s important to realize that this is, in a real sense, an illusion: you’re
|
||||
simply rounding the <em>display</em> of the true machine value.</p>
|
||||
<p>One illusion may beget another. For example, since 0.1 is not exactly 1/10,
|
||||
summing three values of 0.1 may not yield exactly 0.3, either:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">==</span> <span class="mf">0.3</span>
|
||||
<span class="go">False</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Also, since the 0.1 cannot get any closer to the exact value of 1/10 and
|
||||
0.3 cannot get any closer to the exact value of 3/10, then pre-rounding with
|
||||
<a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function cannot help:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="mf">0.1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">round</span><span class="p">(</span><span class="mf">0.1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">+</span> <span class="nb">round</span><span class="p">(</span><span class="mf">0.1</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">round</span><span class="p">(</span><span class="mf">0.3</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
|
||||
<span class="go">False</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Though the numbers cannot be made closer to their intended exact values,
|
||||
the <a class="reference internal" href="../library/math.html#math.isclose" title="math.isclose"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.isclose()</span></code></a> function can be useful for comparing inexact values:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">math</span><span class="o">.</span><span class="n">isclose</span><span class="p">(</span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">)</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Alternatively, the <a class="reference internal" href="../library/functions.html#round" title="round"><code class="xref py py-func docutils literal notranslate"><span class="pre">round()</span></code></a> function can be used to compare rough
|
||||
approximations:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">,</span> <span class="n">ndigits</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span> <span class="o">==</span> <span class="nb">round</span><span class="p">(</span><span class="mi">22</span> <span class="o">/</span> <span class="mi">7</span><span class="p">,</span> <span class="n">ndigits</span><span class="o">=</span><span class="mi">2</span><span class="p">)</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Binary floating-point arithmetic holds many surprises like this. The problem
|
||||
with “0.1” is explained in precise detail below, in the “Representation Error”
|
||||
section. See <a class="reference external" href="https://jvns.ca/blog/2023/01/13/examples-of-floating-point-problems/">Examples of Floating Point Problems</a> for
|
||||
a pleasant summary of how binary floating point works and the kinds of
|
||||
problems commonly encountered in practice. Also see
|
||||
<a class="reference external" href="http://www.indowsway.com/floatingpoint.htm">The Perils of Floating Point</a>
|
||||
for a more complete account of other common surprises.</p>
|
||||
<p>As that says near the end, “there are no easy answers.” Still, don’t be unduly
|
||||
wary of floating point! The errors in Python float operations are inherited
|
||||
from the floating-point hardware, and on most machines are on the order of no
|
||||
more than 1 part in 2**53 per operation. That’s more than adequate for most
|
||||
tasks, but you do need to keep in mind that it’s not decimal arithmetic and
|
||||
that every float operation can suffer a new rounding error.</p>
|
||||
<p>While pathological cases do exist, for most casual use of floating-point
|
||||
arithmetic you’ll see the result you expect in the end if you simply round the
|
||||
display of your final results to the number of decimal digits you expect.
|
||||
<a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> usually suffices, and for finer control see the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>
|
||||
method’s format specifiers in <a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
|
||||
<p>For use cases which require exact decimal representation, try using the
|
||||
<a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module which implements decimal arithmetic suitable for
|
||||
accounting applications and high-precision applications.</p>
|
||||
<p>Another form of exact arithmetic is supported by the <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> module
|
||||
which implements arithmetic based on rational numbers (so the numbers like
|
||||
1/3 can be represented exactly).</p>
|
||||
<p>If you are a heavy user of floating-point operations you should take a look
|
||||
at the NumPy package and many other packages for mathematical and
|
||||
statistical operations supplied by the SciPy project. See <<a class="reference external" href="https://scipy.org">https://scipy.org</a>>.</p>
|
||||
<p>Python provides tools that may help on those rare occasions when you really
|
||||
<em>do</em> want to know the exact value of a float. The
|
||||
<a class="reference internal" href="../library/stdtypes.html#float.as_integer_ratio" title="float.as_integer_ratio"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.as_integer_ratio()</span></code></a> method expresses the value of a float as a
|
||||
fraction:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mf">3.14159</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
|
||||
<span class="go">(3537115888337719, 1125899906842624)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Since the ratio is exact, it can be used to losslessly recreate the
|
||||
original value:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">==</span> <span class="mi">3537115888337719</span> <span class="o">/</span> <span class="mi">1125899906842624</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/stdtypes.html#float.hex" title="float.hex"><code class="xref py py-meth docutils literal notranslate"><span class="pre">float.hex()</span></code></a> method expresses a float in hexadecimal (base
|
||||
16), again giving the exact value stored by your computer:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span><span class="o">.</span><span class="n">hex</span><span class="p">()</span>
|
||||
<span class="go">'0x1.921f9f01b866ep+1'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This precise hexadecimal representation can be used to reconstruct
|
||||
the float value exactly:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">x</span> <span class="o">==</span> <span class="nb">float</span><span class="o">.</span><span class="n">fromhex</span><span class="p">(</span><span class="s1">'0x1.921f9f01b866ep+1'</span><span class="p">)</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Since the representation is exact, it is useful for reliably porting values
|
||||
across different versions of Python (platform independence) and exchanging
|
||||
data with other languages that support the same format (such as Java and C99).</p>
|
||||
<p>Another helpful tool is the <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> function which helps mitigate
|
||||
loss-of-precision during summation. It uses extended precision for
|
||||
intermediate rounding steps as values are added onto a running total.
|
||||
That can make a difference in overall accuracy so that the errors do not
|
||||
accumulate to the point where they affect the final total:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">==</span> <span class="mf">1.0</span>
|
||||
<span class="go">False</span>
|
||||
<span class="gp">>>> </span><span class="nb">sum</span><span class="p">([</span><span class="mf">0.1</span><span class="p">]</span> <span class="o">*</span> <span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="mf">1.0</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/math.html#math.fsum" title="math.fsum"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.fsum()</span></code></a> goes further and tracks all of the “lost digits”
|
||||
as values are added onto a running total so that the result has only a
|
||||
single rounding. This is slower than <a class="reference internal" href="../library/functions.html#sum" title="sum"><code class="xref py py-func docutils literal notranslate"><span class="pre">sum()</span></code></a> but will be more
|
||||
accurate in uncommon cases where large magnitude inputs mostly cancel
|
||||
each other out leaving a final sum near zero:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">arr</span> <span class="o">=</span> <span class="p">[</span><span class="o">-</span><span class="mf">0.10430216751806065</span><span class="p">,</span> <span class="o">-</span><span class="mf">266310978.67179024</span><span class="p">,</span> <span class="mf">143401161448607.16</span><span class="p">,</span>
|
||||
<span class="gp">... </span> <span class="o">-</span><span class="mf">143401161400469.7</span><span class="p">,</span> <span class="mf">266262841.31058735</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.003244936839808227</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="nb">float</span><span class="p">(</span><span class="nb">sum</span><span class="p">(</span><span class="nb">map</span><span class="p">(</span><span class="n">Fraction</span><span class="p">,</span> <span class="n">arr</span><span class="p">)))</span> <span class="c1"># Exact summation with single rounding</span>
|
||||
<span class="go">8.042173697819788e-13</span>
|
||||
<span class="gp">>>> </span><span class="n">math</span><span class="o">.</span><span class="n">fsum</span><span class="p">(</span><span class="n">arr</span><span class="p">)</span> <span class="c1"># Single rounding</span>
|
||||
<span class="go">8.042173697819788e-13</span>
|
||||
<span class="gp">>>> </span><span class="nb">sum</span><span class="p">(</span><span class="n">arr</span><span class="p">)</span> <span class="c1"># Multiple roundings in extended precision</span>
|
||||
<span class="go">8.042178034628478e-13</span>
|
||||
<span class="gp">>>> </span><span class="n">total</span> <span class="o">=</span> <span class="mf">0.0</span>
|
||||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="n">arr</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">total</span> <span class="o">+=</span> <span class="n">x</span> <span class="c1"># Multiple roundings in standard precision</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">total</span> <span class="c1"># Straight addition has no correct digits!</span>
|
||||
<span class="go">-0.0051575902860057365</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<section id="representation-error">
|
||||
<span id="tut-fp-error"></span><h2><span class="section-number">15.1. </span>Representation Error<a class="headerlink" href="#representation-error" title="Link to this heading">¶</a></h2>
|
||||
<p>This section explains the “0.1” example in detail, and shows how you can perform
|
||||
an exact analysis of cases like this yourself. Basic familiarity with binary
|
||||
floating-point representation is assumed.</p>
|
||||
<p><em class="dfn">Representation error</em> refers to the fact that some (most, actually)
|
||||
decimal fractions cannot be represented exactly as binary (base 2) fractions.
|
||||
This is the chief reason why Python (or Perl, C, C++, Java, Fortran, and many
|
||||
others) often won’t display the exact decimal number you expect.</p>
|
||||
<p>Why is that? 1/10 is not exactly representable as a binary fraction. Since at
|
||||
least 2000, almost all machines use IEEE 754 binary floating-point arithmetic,
|
||||
and almost all platforms map Python floats to IEEE 754 binary64 “double
|
||||
precision” values. IEEE 754 binary64 values contain 53 bits of precision, so
|
||||
on input the computer strives to convert 0.1 to the closest fraction it can of
|
||||
the form <em>J</em>/2**<em>N</em> where <em>J</em> is an integer containing exactly 53 bits.
|
||||
Rewriting</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">1</span> <span class="o">/</span> <span class="mi">10</span> <span class="o">~=</span> <span class="n">J</span> <span class="o">/</span> <span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="n">N</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>as</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">J</span> <span class="o">~=</span> <span class="mi">2</span><span class="o">**</span><span class="n">N</span> <span class="o">/</span> <span class="mi">10</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>and recalling that <em>J</em> has exactly 53 bits (is <code class="docutils literal notranslate"><span class="pre">>=</span> <span class="pre">2**52</span></code> but <code class="docutils literal notranslate"><span class="pre"><</span> <span class="pre">2**53</span></code>),
|
||||
the best value for <em>N</em> is 56:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">2</span><span class="o">**</span><span class="mi">52</span> <span class="o"><=</span> <span class="mi">2</span><span class="o">**</span><span class="mi">56</span> <span class="o">//</span> <span class="mi">10</span> <span class="o"><</span> <span class="mi">2</span><span class="o">**</span><span class="mi">53</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>That is, 56 is the only value for <em>N</em> that leaves <em>J</em> with exactly 53 bits. The
|
||||
best possible value for <em>J</em> is then that quotient rounded:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span><span class="p">,</span> <span class="n">r</span> <span class="o">=</span> <span class="nb">divmod</span><span class="p">(</span><span class="mi">2</span><span class="o">**</span><span class="mi">56</span><span class="p">,</span> <span class="mi">10</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">r</span>
|
||||
<span class="go">6</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Since the remainder is more than half of 10, the best approximation is obtained
|
||||
by rounding up:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">q</span><span class="o">+</span><span class="mi">1</span>
|
||||
<span class="go">7205759403792794</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Therefore the best possible approximation to 1/10 in IEEE 754 double precision
|
||||
is:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">7205759403792794</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">56</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Dividing both the numerator and denominator by two reduces the fraction to:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="mi">3602879701896397</span> <span class="o">/</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that since we rounded up, this is actually a little bit larger than 1/10;
|
||||
if we had not rounded up, the quotient would have been a little bit smaller than
|
||||
1/10. But in no case can it be <em>exactly</em> 1/10!</p>
|
||||
<p>So the computer never “sees” 1/10: what it sees is the exact fraction given
|
||||
above, the best IEEE 754 double approximation it can get:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mf">0.1</span> <span class="o">*</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
|
||||
<span class="go">3602879701896397.0</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If we multiply that fraction by 10**55, we can see the value out to
|
||||
55 decimal digits:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">3602879701896397</span> <span class="o">*</span> <span class="mi">10</span> <span class="o">**</span> <span class="mi">55</span> <span class="o">//</span> <span class="mi">2</span> <span class="o">**</span> <span class="mi">55</span>
|
||||
<span class="go">1000000000000000055511151231257827021181583404541015625</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>meaning that the exact number stored in the computer is equal to
|
||||
the decimal value 0.1000000000000000055511151231257827021181583404541015625.
|
||||
Instead of displaying the full decimal value, many languages (including
|
||||
older versions of Python), round the result to 17 significant digits:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">format</span><span class="p">(</span><span class="mf">0.1</span><span class="p">,</span> <span class="s1">'.17f'</span><span class="p">)</span>
|
||||
<span class="go">'0.10000000000000001'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/fractions.html#module-fractions" title="fractions: Rational numbers."><code class="xref py py-mod docutils literal notranslate"><span class="pre">fractions</span></code></a> and <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> modules make these calculations
|
||||
easy:</p>
|
||||
<div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">decimal</span><span class="w"> </span><span class="kn">import</span> <span class="n">Decimal</span>
|
||||
<span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">fractions</span><span class="w"> </span><span class="kn">import</span> <span class="n">Fraction</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="n">Fraction</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
|
||||
<span class="go">Fraction(3602879701896397, 36028797018963968)</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span><span class="o">.</span><span class="n">as_integer_ratio</span><span class="p">()</span>
|
||||
<span class="go">(3602879701896397, 36028797018963968)</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">)</span>
|
||||
<span class="go">Decimal('0.1000000000000000055511151231257827021181583404541015625')</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="nb">format</span><span class="p">(</span><span class="n">Decimal</span><span class="o">.</span><span class="n">from_float</span><span class="p">(</span><span class="mf">0.1</span><span class="p">),</span> <span class="s1">'.17'</span><span class="p">)</span>
|
||||
<span class="go">'0.10000000000000001'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">15. Floating-Point Arithmetic: Issues and Limitations</a><ul>
|
||||
<li><a class="reference internal" href="#representation-error">15.1. Representation Error</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="interactive.html"
|
||||
title="previous chapter"><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="appendix.html"
|
||||
title="next chapter"><span class="section-number">16. </span>Appendix</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/floatingpoint.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appendix.html" title="16. Appendix"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
534
Dependencies/Python/Doc/html/tutorial/index.html
vendored
Normal file
534
Dependencies/Python/Doc/html/tutorial/index.html
vendored
Normal file
@@ -0,0 +1,534 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="The Python Tutorial" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/index.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax an..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax an..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>The Python Tutorial — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="1. Whetting Your Appetite" href="appetite.html" />
|
||||
<link rel="prev" title="Changelog" href="../whatsnew/changelog.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/index.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="../whatsnew/changelog.html"
|
||||
title="previous chapter">Changelog</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="appetite.html"
|
||||
title="next chapter"><span class="section-number">1. </span>Whetting Your Appetite</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/index.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appetite.html" title="1. Whetting Your Appetite"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="../whatsnew/changelog.html" title="Changelog"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-this"><a href="">The Python Tutorial</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="the-python-tutorial">
|
||||
<span id="tutorial-index"></span><h1>The Python Tutorial<a class="headerlink" href="#the-python-tutorial" title="Link to this heading">¶</a></h1>
|
||||
<p>Python is an easy to learn, powerful programming language. It has efficient
|
||||
high-level data structures and a simple but effective approach to
|
||||
object-oriented programming. Python’s elegant syntax and dynamic typing,
|
||||
together with its interpreted nature, make it an ideal language for scripting
|
||||
and rapid application development in many areas on most platforms.</p>
|
||||
<p>The Python interpreter and the extensive standard library are freely available
|
||||
in source or binary form for all major platforms from the Python web site,
|
||||
<a class="reference external" href="https://www.python.org/">https://www.python.org/</a>, and may be freely distributed. The same site also
|
||||
contains distributions of and pointers to many free third party Python modules,
|
||||
programs and tools, and additional documentation.</p>
|
||||
<p>The Python interpreter is easily extended with new functions and data types
|
||||
implemented in C or C++ (or other languages callable from C). Python is also
|
||||
suitable as an extension language for customizable applications.</p>
|
||||
<p>This tutorial introduces the reader informally to the basic concepts and
|
||||
features of the Python language and system. It helps to have a Python
|
||||
interpreter handy for hands-on experience, but all examples are self-contained,
|
||||
so the tutorial can be read off-line as well.</p>
|
||||
<p>For a description of standard objects and modules, see <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.
|
||||
<a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a> gives a more formal definition of the language. To write
|
||||
extensions in C or C++, read <a class="reference internal" href="../extending/index.html#extending-index"><span class="std std-ref">Extending and Embedding the Python Interpreter</span></a> and
|
||||
<a class="reference internal" href="../c-api/index.html#c-api-index"><span class="std std-ref">Python/C API Reference Manual</span></a>. There are also several books covering Python in depth.</p>
|
||||
<p>This tutorial does not attempt to be comprehensive and cover every single
|
||||
feature, or even every commonly used feature. Instead, it introduces many of
|
||||
Python’s most noteworthy features, and will give you a good idea of the
|
||||
language’s flavor and style. After reading it, you will be able to read and
|
||||
write Python modules and programs, and you will be ready to learn more about the
|
||||
various Python library modules described in <a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>.</p>
|
||||
<p>The <a class="reference internal" href="../glossary.html#glossary"><span class="std std-ref">Glossary</span></a> is also worth going through.</p>
|
||||
<div class="toctree-wrapper compound">
|
||||
<ul>
|
||||
<li class="toctree-l1"><a class="reference internal" href="appetite.html">1. Whetting Your Appetite</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="interpreter.html">2. Using the Python Interpreter</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#argument-passing">2.1.1. Argument Passing</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#interactive-mode">2.1.2. Interactive Mode</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interpreter.html#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="interpreter.html#source-code-encoding">2.2.1. Source Code Encoding</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="introduction.html">3. An Informal Introduction to Python</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="introduction.html#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="introduction.html#numbers">3.1.1. Numbers</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="introduction.html#text">3.1.2. Text</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="introduction.html#lists">3.1.3. Lists</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="introduction.html#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="controlflow.html">4. More Control Flow Tools</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#if-statements">4.1. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code> Statements</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#for-statements">4.2. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code> Statements</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#the-range-function">4.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">range()</span></code> Function</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#break-and-continue-statements">4.4. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">break</span></code> and <code class="xref std std-keyword docutils literal notranslate"><span class="pre">continue</span></code> Statements</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#else-clauses-on-loops">4.5. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">else</span></code> Clauses on Loops</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#pass-statements">4.6. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">pass</span></code> Statements</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#match-statements">4.7. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">match</span></code> Statements</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#defining-functions">4.8. Defining Functions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#more-on-defining-functions">4.9. More on Defining Functions</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#default-argument-values">4.9.1. Default Argument Values</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#keyword-arguments">4.9.2. Keyword Arguments</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#special-parameters">4.9.3. Special parameters</a><ul>
|
||||
<li class="toctree-l4"><a class="reference internal" href="controlflow.html#positional-or-keyword-arguments">4.9.3.1. Positional-or-Keyword Arguments</a></li>
|
||||
<li class="toctree-l4"><a class="reference internal" href="controlflow.html#positional-only-parameters">4.9.3.2. Positional-Only Parameters</a></li>
|
||||
<li class="toctree-l4"><a class="reference internal" href="controlflow.html#keyword-only-arguments">4.9.3.3. Keyword-Only Arguments</a></li>
|
||||
<li class="toctree-l4"><a class="reference internal" href="controlflow.html#function-examples">4.9.3.4. Function Examples</a></li>
|
||||
<li class="toctree-l4"><a class="reference internal" href="controlflow.html#recap">4.9.3.5. Recap</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#arbitrary-argument-lists">4.9.4. Arbitrary Argument Lists</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#unpacking-argument-lists">4.9.5. Unpacking Argument Lists</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#lambda-expressions">4.9.6. Lambda Expressions</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#documentation-strings">4.9.7. Documentation Strings</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="controlflow.html#function-annotations">4.9.8. Function Annotations</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="controlflow.html#intermezzo-coding-style">4.10. Intermezzo: Coding Style</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="datastructures.html">5. Data Structures</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-lists">5.1. More on Lists</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-stacks">5.1.1. Using Lists as Stacks</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#using-lists-as-queues">5.1.2. Using Lists as Queues</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#list-comprehensions">5.1.3. List Comprehensions</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="datastructures.html#nested-list-comprehensions">5.1.4. Nested List Comprehensions</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#the-del-statement">5.2. The <code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code> statement</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#tuples-and-sequences">5.3. Tuples and Sequences</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#sets">5.4. Sets</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#dictionaries">5.5. Dictionaries</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#looping-techniques">5.6. Looping Techniques</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#more-on-conditions">5.7. More on Conditions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="datastructures.html#comparing-sequences-and-other-types">5.8. Comparing Sequences and Other Types</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="modules.html">6. Modules</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="modules.html#more-on-modules">6.1. More on Modules</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#the-module-search-path">6.1.2. The Module Search Path</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="modules.html#standard-modules">6.2. Standard Modules</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="modules.html#the-dir-function">6.3. The <code class="xref py py-func docutils literal notranslate"><span class="pre">dir()</span></code> Function</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="modules.html#packages">6.4. Packages</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#intra-package-references">6.4.2. Intra-package References</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="modules.html#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="inputoutput.html">7. Input and Output</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#the-string-format-method">7.1.2. The String format() Method</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#old-string-formatting">7.1.4. Old string formatting</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="inputoutput.html#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="inputoutput.html#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="errors.html">8. Errors and Exceptions</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#syntax-errors">8.1. Syntax Errors</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#exceptions">8.2. Exceptions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#handling-exceptions">8.3. Handling Exceptions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#raising-exceptions">8.4. Raising Exceptions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#exception-chaining">8.5. Exception Chaining</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#user-defined-exceptions">8.6. User-defined Exceptions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#defining-clean-up-actions">8.7. Defining Clean-up Actions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#predefined-clean-up-actions">8.8. Predefined Clean-up Actions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#raising-and-handling-multiple-unrelated-exceptions">8.9. Raising and Handling Multiple Unrelated Exceptions</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="errors.html#enriching-exceptions-with-notes">8.10. Enriching Exceptions with Notes</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="classes.html">9. Classes</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-word-about-names-and-objects">9.1. A Word About Names and Objects</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#python-scopes-and-namespaces">9.2. Python Scopes and Namespaces</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#scopes-and-namespaces-example">9.2.1. Scopes and Namespaces Example</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#a-first-look-at-classes">9.3. A First Look at Classes</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-definition-syntax">9.3.1. Class Definition Syntax</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-objects">9.3.2. Class Objects</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#instance-objects">9.3.3. Instance Objects</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#method-objects">9.3.4. Method Objects</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#class-and-instance-variables">9.3.5. Class and Instance Variables</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#random-remarks">9.4. Random Remarks</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#inheritance">9.5. Inheritance</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="classes.html#multiple-inheritance">9.5.1. Multiple Inheritance</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#private-variables">9.6. Private Variables</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#odds-and-ends">9.7. Odds and Ends</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#iterators">9.8. Iterators</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#generators">9.9. Generators</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="classes.html#generator-expressions">9.10. Generator Expressions</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="stdlib.html">10. Brief Tour of the Standard Library</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#operating-system-interface">10.1. Operating System Interface</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#file-wildcards">10.2. File Wildcards</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#command-line-arguments">10.3. Command Line Arguments</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#string-pattern-matching">10.5. String Pattern Matching</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#mathematics">10.6. Mathematics</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#internet-access">10.7. Internet Access</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#dates-and-times">10.8. Dates and Times</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#data-compression">10.9. Data Compression</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#performance-measurement">10.10. Performance Measurement</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#quality-control">10.11. Quality Control</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib.html#batteries-included">10.12. Batteries Included</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="stdlib2.html">11. Brief Tour of the Standard Library — Part II</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#output-formatting">11.1. Output Formatting</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#templating">11.2. Templating</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#multi-threading">11.4. Multi-threading</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#logging">11.5. Logging</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#weak-references">11.6. Weak References</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="stdlib2.html#decimal-floating-point-arithmetic">11.8. Decimal Floating-Point Arithmetic</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="venv.html">12. Virtual Environments and Packages</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="venv.html#introduction">12.1. Introduction</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="venv.html#creating-virtual-environments">12.2. Creating Virtual Environments</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="venv.html#managing-packages-with-pip">12.3. Managing Packages with pip</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="whatnow.html">13. What Now?</a></li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="interactive.html">14. Interactive Input Editing and History Substitution</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interactive.html#tab-completion-and-history-editing">14.1. Tab Completion and History Editing</a></li>
|
||||
<li class="toctree-l2"><a class="reference internal" href="interactive.html#alternatives-to-the-interactive-interpreter">14.2. Alternatives to the Interactive Interpreter</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="floatingpoint.html">15. Floating-Point Arithmetic: Issues and Limitations</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="floatingpoint.html#representation-error">15.1. Representation Error</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="toctree-l1"><a class="reference internal" href="appendix.html">16. Appendix</a><ul>
|
||||
<li class="toctree-l2"><a class="reference internal" href="appendix.html#interactive-mode">16.1. Interactive Mode</a><ul>
|
||||
<li class="toctree-l3"><a class="reference internal" href="appendix.html#error-handling">16.1.1. Error Handling</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="appendix.html#executable-python-scripts">16.1.2. Executable Python Scripts</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-interactive-startup-file">16.1.3. The Interactive Startup File</a></li>
|
||||
<li class="toctree-l3"><a class="reference internal" href="appendix.html#the-customization-modules">16.1.4. The Customization Modules</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="../whatsnew/changelog.html"
|
||||
title="previous chapter">Changelog</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="appetite.html"
|
||||
title="next chapter"><span class="section-number">1. </span>Whetting Your Appetite</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/index.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appetite.html" title="1. Whetting Your Appetite"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="../whatsnew/changelog.html" title="Changelog"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-this"><a href="">The Python Tutorial</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
829
Dependencies/Python/Doc/html/tutorial/inputoutput.html
vendored
Normal file
829
Dependencies/Python/Doc/html/tutorial/inputoutput.html
vendored
Normal file
@@ -0,0 +1,829 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="7. Input and Output" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/inputoutput.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Fa..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="There are several ways to present the output of a program; data can be printed in a human-readable form, or written to a file for future use. This chapter will discuss some of the possibilities. Fa..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>7. Input and Output — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="8. Errors and Exceptions" href="errors.html" />
|
||||
<link rel="prev" title="6. Modules" href="modules.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/inputoutput.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
|
||||
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
|
||||
<li><a class="reference internal" href="#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
|
||||
<li><a class="reference internal" href="#the-string-format-method">7.1.2. The String format() Method</a></li>
|
||||
<li><a class="reference internal" href="#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
|
||||
<li><a class="reference internal" href="#old-string-formatting">7.1.4. Old string formatting</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
|
||||
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
|
||||
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="modules.html"
|
||||
title="previous chapter"><span class="section-number">6. </span>Modules</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="errors.html"
|
||||
title="next chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/inputoutput.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="errors.html" title="8. Errors and Exceptions"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="modules.html" title="6. Modules"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">7. </span>Input and Output</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="input-and-output">
|
||||
<span id="tut-io"></span><h1><span class="section-number">7. </span>Input and Output<a class="headerlink" href="#input-and-output" title="Link to this heading">¶</a></h1>
|
||||
<p>There are several ways to present the output of a program; data can be printed
|
||||
in a human-readable form, or written to a file for future use. This chapter will
|
||||
discuss some of the possibilities.</p>
|
||||
<section id="fancier-output-formatting">
|
||||
<span id="tut-formatting"></span><h2><span class="section-number">7.1. </span>Fancier Output Formatting<a class="headerlink" href="#fancier-output-formatting" title="Link to this heading">¶</a></h2>
|
||||
<p>So far we’ve encountered two ways of writing values: <em>expression statements</em> and
|
||||
the <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function. (A third way is using the <a class="reference internal" href="../library/io.html#io.TextIOBase.write" title="io.TextIOBase.write"><code class="xref py py-meth docutils literal notranslate"><span class="pre">write()</span></code></a> method
|
||||
of file objects; the standard output file can be referenced as <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code>.
|
||||
See the Library Reference for more information on this.)</p>
|
||||
<p>Often you’ll want more control over the formatting of your output than simply
|
||||
printing space-separated values. There are several ways to format output.</p>
|
||||
<ul>
|
||||
<li><p>To use <a class="reference internal" href="#tut-f-strings"><span class="std std-ref">formatted string literals</span></a>, begin a string
|
||||
with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> before the opening quotation mark or triple quotation mark.
|
||||
Inside this string, you can write a Python expression between <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code>
|
||||
characters that can refer to variables or literal values.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">year</span> <span class="o">=</span> <span class="mi">2016</span>
|
||||
<span class="gp">>>> </span><span class="n">event</span> <span class="o">=</span> <span class="s1">'Referendum'</span>
|
||||
<span class="gp">>>> </span><span class="sa">f</span><span class="s1">'Results of the </span><span class="si">{</span><span class="n">year</span><span class="si">}</span><span class="s1"> </span><span class="si">{</span><span class="n">event</span><span class="si">}</span><span class="s1">'</span>
|
||||
<span class="go">'Results of the 2016 Referendum'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</li>
|
||||
<li><p>The <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method of strings requires more manual
|
||||
effort. You’ll still use <code class="docutils literal notranslate"><span class="pre">{</span></code> and <code class="docutils literal notranslate"><span class="pre">}</span></code> to mark where a variable
|
||||
will be substituted and can provide detailed formatting directives,
|
||||
but you’ll also need to provide the information to be formatted. In the following code
|
||||
block there are two examples of how to format variables:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">yes_votes</span> <span class="o">=</span> <span class="mi">42_572_654</span>
|
||||
<span class="gp">>>> </span><span class="n">total_votes</span> <span class="o">=</span> <span class="mi">85_705_149</span>
|
||||
<span class="gp">>>> </span><span class="n">percentage</span> <span class="o">=</span> <span class="n">yes_votes</span> <span class="o">/</span> <span class="n">total_votes</span>
|
||||
<span class="gp">>>> </span><span class="s1">'</span><span class="si">{:-9}</span><span class="s1"> YES votes </span><span class="si">{:2.2%}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">yes_votes</span><span class="p">,</span> <span class="n">percentage</span><span class="p">)</span>
|
||||
<span class="go">' 42572654 YES votes 49.67%'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Notice how the <code class="docutils literal notranslate"><span class="pre">yes_votes</span></code> are padded with spaces and a negative sign only for negative numbers.
|
||||
The example also prints <code class="docutils literal notranslate"><span class="pre">percentage</span></code> multiplied by 100, with 2 decimal
|
||||
places and followed by a percent sign (see <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a> for details).</p>
|
||||
</li>
|
||||
<li><p>Finally, you can do all the string handling yourself by using string slicing and
|
||||
concatenation operations to create any layout you can imagine. The
|
||||
string type has some methods that perform useful operations for padding
|
||||
strings to a given column width.</p></li>
|
||||
</ul>
|
||||
<p>When you don’t need fancy output but just want a quick display of some
|
||||
variables for debugging purposes, you can convert any value to a string with
|
||||
the <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> functions.</p>
|
||||
<p>The <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> function is meant to return representations of values which are
|
||||
fairly human-readable, while <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> is meant to generate representations
|
||||
which can be read by the interpreter (or will force a <a class="reference internal" href="../library/exceptions.html#SyntaxError" title="SyntaxError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">SyntaxError</span></code></a> if
|
||||
there is no equivalent syntax). For objects which don’t have a particular
|
||||
representation for human consumption, <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a> will return the same value as
|
||||
<a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>. Many values, such as numbers or structures like lists and
|
||||
dictionaries, have the same representation using either function. Strings, in
|
||||
particular, have two distinct representations.</p>
|
||||
<p>Some examples:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'Hello, world.'</span>
|
||||
<span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">'Hello, world.'</span>
|
||||
<span class="gp">>>> </span><span class="nb">repr</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">"'Hello, world.'"</span>
|
||||
<span class="gp">>>> </span><span class="nb">str</span><span class="p">(</span><span class="mi">1</span><span class="o">/</span><span class="mi">7</span><span class="p">)</span>
|
||||
<span class="go">'0.14285714285714285'</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mi">10</span> <span class="o">*</span> <span class="mf">3.25</span>
|
||||
<span class="gp">>>> </span><span class="n">y</span> <span class="o">=</span> <span class="mi">200</span> <span class="o">*</span> <span class="mi">200</span>
|
||||
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'The value of x is '</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="o">+</span> <span class="s1">', and y is '</span> <span class="o">+</span> <span class="nb">repr</span><span class="p">(</span><span class="n">y</span><span class="p">)</span> <span class="o">+</span> <span class="s1">'...'</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">The value of x is 32.5, and y is 40000...</span>
|
||||
<span class="gp">>>> </span><span class="c1"># The repr() of a string adds string quotes and backslashes:</span>
|
||||
<span class="gp">>>> </span><span class="n">hello</span> <span class="o">=</span> <span class="s1">'hello, world</span><span class="se">\n</span><span class="s1">'</span>
|
||||
<span class="gp">>>> </span><span class="n">hellos</span> <span class="o">=</span> <span class="nb">repr</span><span class="p">(</span><span class="n">hello</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">hellos</span><span class="p">)</span>
|
||||
<span class="go">'hello, world\n'</span>
|
||||
<span class="gp">>>> </span><span class="c1"># The argument to repr() may be any Python object:</span>
|
||||
<span class="gp">>>> </span><span class="nb">repr</span><span class="p">((</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">)))</span>
|
||||
<span class="go">"(32.5, 40000, ('spam', 'eggs'))"</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module contains a <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class that offers
|
||||
yet another way to substitute values into strings, using placeholders like
|
||||
<code class="docutils literal notranslate"><span class="pre">$x</span></code> and replacing them with values from a dictionary, but offers much less
|
||||
control of the formatting.</p>
|
||||
<section id="formatted-string-literals">
|
||||
<span id="tut-f-strings"></span><span id="index-0"></span><h3><span class="section-number">7.1.1. </span>Formatted String Literals<a class="headerlink" href="#formatted-string-literals" title="Link to this heading">¶</a></h3>
|
||||
<p><a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">Formatted string literals</span></a> (also called f-strings for
|
||||
short) let you include the value of Python expressions inside a string by
|
||||
prefixing the string with <code class="docutils literal notranslate"><span class="pre">f</span></code> or <code class="docutils literal notranslate"><span class="pre">F</span></code> and writing expressions as
|
||||
<code class="docutils literal notranslate"><span class="pre">{expression}</span></code>.</p>
|
||||
<p>An optional format specifier can follow the expression. This allows greater
|
||||
control over how the value is formatted. The following example rounds pi to
|
||||
three places after the decimal:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">math</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'The value of pi is approximately </span><span class="si">{</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="si">:</span><span class="s1">.3f</span><span class="si">}</span><span class="s1">.'</span><span class="p">)</span>
|
||||
<span class="go">The value of pi is approximately 3.142.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Passing an integer after the <code class="docutils literal notranslate"><span class="pre">':'</span></code> will cause that field to be a minimum
|
||||
number of characters wide. This is useful for making columns line up.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'Sjoerd'</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">'Jack'</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">'Dcab'</span><span class="p">:</span> <span class="mi">7678</span><span class="p">}</span>
|
||||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">name</span><span class="p">,</span> <span class="n">phone</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">items</span><span class="p">():</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">name</span><span class="si">:</span><span class="s1">10</span><span class="si">}</span><span class="s1"> ==> </span><span class="si">{</span><span class="n">phone</span><span class="si">:</span><span class="s1">10d</span><span class="si">}</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">Sjoerd ==> 4127</span>
|
||||
<span class="go">Jack ==> 4098</span>
|
||||
<span class="go">Dcab ==> 7678</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Other modifiers can be used to convert the value before it is formatted.
|
||||
<code class="docutils literal notranslate"><span class="pre">'!a'</span></code> applies <a class="reference internal" href="../library/functions.html#ascii" title="ascii"><code class="xref py py-func docutils literal notranslate"><span class="pre">ascii()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">'!s'</span></code> applies <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str()</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">'!r'</span></code>
|
||||
applies <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">animals</span> <span class="o">=</span> <span class="s1">'eels'</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'My hovercraft is full of </span><span class="si">{</span><span class="n">animals</span><span class="si">}</span><span class="s1">.'</span><span class="p">)</span>
|
||||
<span class="go">My hovercraft is full of eels.</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'My hovercraft is full of </span><span class="si">{</span><span class="n">animals</span><span class="si">!r}</span><span class="s1">.'</span><span class="p">)</span>
|
||||
<span class="go">My hovercraft is full of 'eels'.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <code class="docutils literal notranslate"><span class="pre">=</span></code> specifier can be used to expand an expression to the text of the
|
||||
expression, an equal sign, then the representation of the evaluated expression:</p>
|
||||
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">bugs</span> <span class="o">=</span> <span class="s1">'roaches'</span>
|
||||
<span class="gp">>>> </span><span class="n">count</span> <span class="o">=</span> <span class="mi">13</span>
|
||||
<span class="gp">>>> </span><span class="n">area</span> <span class="o">=</span> <span class="s1">'living room'</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">'Debugging </span><span class="si">{</span><span class="n">bugs</span><span class="si">=}</span><span class="s1"> </span><span class="si">{</span><span class="n">count</span><span class="si">=}</span><span class="s1"> </span><span class="si">{</span><span class="n">area</span><span class="si">=}</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="go">Debugging bugs='roaches' count=13 area='living room'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>See <a class="reference internal" href="../whatsnew/3.8.html#bpo-36817-whatsnew"><span class="std std-ref">self-documenting expressions</span></a> for more information
|
||||
on the <code class="docutils literal notranslate"><span class="pre">=</span></code> specifier. For a reference on these format specifications, see
|
||||
the reference guide for the <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a>.</p>
|
||||
</section>
|
||||
<section id="the-string-format-method">
|
||||
<span id="tut-string-format"></span><h3><span class="section-number">7.1.2. </span>The String format() Method<a class="headerlink" href="#the-string-format-method" title="Link to this heading">¶</a></h3>
|
||||
<p>Basic usage of the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method looks like this:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'We are the </span><span class="si">{}</span><span class="s1"> who say "</span><span class="si">{}</span><span class="s1">!"'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">'knights'</span><span class="p">,</span> <span class="s1">'Ni'</span><span class="p">))</span>
|
||||
<span class="go">We are the knights who say "Ni!"</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The brackets and characters within them (called format fields) are replaced with
|
||||
the objects passed into the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method. A number in the
|
||||
brackets can be used to refer to the position of the object passed into the
|
||||
<a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{0}</span><span class="s1"> and </span><span class="si">{1}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">))</span>
|
||||
<span class="go">spam and eggs</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{1}</span><span class="s1"> and </span><span class="si">{0}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">'spam'</span><span class="p">,</span> <span class="s1">'eggs'</span><span class="p">))</span>
|
||||
<span class="go">eggs and spam</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If keyword arguments are used in the <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a> method, their values
|
||||
are referred to by using the name of the argument.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'This </span><span class="si">{food}</span><span class="s1"> is </span><span class="si">{adjective}</span><span class="s1">.'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
|
||||
<span class="gp">... </span> <span class="n">food</span><span class="o">=</span><span class="s1">'spam'</span><span class="p">,</span> <span class="n">adjective</span><span class="o">=</span><span class="s1">'absolutely horrible'</span><span class="p">))</span>
|
||||
<span class="go">This spam is absolutely horrible.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Positional and keyword arguments can be arbitrarily combined:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'The story of </span><span class="si">{0}</span><span class="s1">, </span><span class="si">{1}</span><span class="s1">, and </span><span class="si">{other}</span><span class="s1">.'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="s1">'Bill'</span><span class="p">,</span> <span class="s1">'Manfred'</span><span class="p">,</span>
|
||||
<span class="gp">... </span> <span class="n">other</span><span class="o">=</span><span class="s1">'Georg'</span><span class="p">))</span>
|
||||
<span class="go">The story of Bill, Manfred, and Georg.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you have a really long format string that you don’t want to split up, it
|
||||
would be nice if you could reference the variables to be formatted by name
|
||||
instead of by position. This can be done by simply passing the dict and using
|
||||
square brackets <code class="docutils literal notranslate"><span class="pre">'[]'</span></code> to access the keys.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'Sjoerd'</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">'Jack'</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">'Dcab'</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'Jack: </span><span class="si">{0[Jack]:d}</span><span class="s1">; Sjoerd: </span><span class="si">{0[Sjoerd]:d}</span><span class="s1">; '</span>
|
||||
<span class="gp">... </span> <span class="s1">'Dcab: </span><span class="si">{0[Dcab]:d}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">table</span><span class="p">))</span>
|
||||
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This could also be done by passing the <code class="docutils literal notranslate"><span class="pre">table</span></code> dictionary as keyword arguments with the <code class="docutils literal notranslate"><span class="pre">**</span></code>
|
||||
notation.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'Sjoerd'</span><span class="p">:</span> <span class="mi">4127</span><span class="p">,</span> <span class="s1">'Jack'</span><span class="p">:</span> <span class="mi">4098</span><span class="p">,</span> <span class="s1">'Dcab'</span><span class="p">:</span> <span class="mi">8637678</span><span class="p">}</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'Jack: </span><span class="si">{Jack:d}</span><span class="s1">; Sjoerd: </span><span class="si">{Sjoerd:d}</span><span class="s1">; Dcab: </span><span class="si">{Dcab:d}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">))</span>
|
||||
<span class="go">Jack: 4098; Sjoerd: 4127; Dcab: 8637678</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This is particularly useful in combination with the built-in function
|
||||
<a class="reference internal" href="../library/functions.html#vars" title="vars"><code class="xref py py-func docutils literal notranslate"><span class="pre">vars()</span></code></a>, which returns a dictionary containing all local variables:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">table</span> <span class="o">=</span> <span class="p">{</span><span class="n">k</span><span class="p">:</span> <span class="nb">str</span><span class="p">(</span><span class="n">v</span><span class="p">)</span> <span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="ow">in</span> <span class="nb">vars</span><span class="p">()</span><span class="o">.</span><span class="n">items</span><span class="p">()}</span>
|
||||
<span class="gp">>>> </span><span class="n">message</span> <span class="o">=</span> <span class="s2">" "</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="sa">f</span><span class="s1">'</span><span class="si">{</span><span class="n">k</span><span class="si">}</span><span class="s1">: '</span> <span class="o">+</span> <span class="s1">'{'</span> <span class="o">+</span> <span class="n">k</span> <span class="o">+</span><span class="s1">'};'</span> <span class="k">for</span> <span class="n">k</span> <span class="ow">in</span> <span class="n">table</span><span class="o">.</span><span class="n">keys</span><span class="p">()])</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">message</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="o">**</span><span class="n">table</span><span class="p">))</span>
|
||||
<span class="go">__name__: __main__; __doc__: None; __package__: None; __loader__: ...</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>As an example, the following lines produce a tidily aligned
|
||||
set of columns giving integers and their squares and cubes:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{0:2d}</span><span class="s1"> </span><span class="si">{1:3d}</span><span class="s1"> </span><span class="si">{2:4d}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">,</span> <span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">))</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go"> 1 1 1</span>
|
||||
<span class="go"> 2 4 8</span>
|
||||
<span class="go"> 3 9 27</span>
|
||||
<span class="go"> 4 16 64</span>
|
||||
<span class="go"> 5 25 125</span>
|
||||
<span class="go"> 6 36 216</span>
|
||||
<span class="go"> 7 49 343</span>
|
||||
<span class="go"> 8 64 512</span>
|
||||
<span class="go"> 9 81 729</span>
|
||||
<span class="go">10 100 1000</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For a complete overview of string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>, see
|
||||
<a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a>.</p>
|
||||
</section>
|
||||
<section id="manual-string-formatting">
|
||||
<h3><span class="section-number">7.1.3. </span>Manual String Formatting<a class="headerlink" href="#manual-string-formatting" title="Link to this heading">¶</a></h3>
|
||||
<p>Here’s the same table of squares and cubes, formatted manually:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">11</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">2</span><span class="p">),</span> <span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">3</span><span class="p">),</span> <span class="n">end</span><span class="o">=</span><span class="s1">' '</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="c1"># Note use of 'end' on previous line</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="nb">repr</span><span class="p">(</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="o">*</span><span class="n">x</span><span class="p">)</span><span class="o">.</span><span class="n">rjust</span><span class="p">(</span><span class="mi">4</span><span class="p">))</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go"> 1 1 1</span>
|
||||
<span class="go"> 2 4 8</span>
|
||||
<span class="go"> 3 9 27</span>
|
||||
<span class="go"> 4 16 64</span>
|
||||
<span class="go"> 5 25 125</span>
|
||||
<span class="go"> 6 36 216</span>
|
||||
<span class="go"> 7 49 343</span>
|
||||
<span class="go"> 8 64 512</span>
|
||||
<span class="go"> 9 81 729</span>
|
||||
<span class="go">10 100 1000</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>(Note that the one space between each column was added by the
|
||||
way <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> works: it always adds spaces between its arguments.)</p>
|
||||
<p>The <a class="reference internal" href="../library/stdtypes.html#str.rjust" title="str.rjust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.rjust()</span></code></a> method of string objects right-justifies a string in a
|
||||
field of a given width by padding it with spaces on the left. There are
|
||||
similar methods <a class="reference internal" href="../library/stdtypes.html#str.ljust" title="str.ljust"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.ljust()</span></code></a> and <a class="reference internal" href="../library/stdtypes.html#str.center" title="str.center"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.center()</span></code></a>. These methods do
|
||||
not write anything, they just return a new string. If the input string is too
|
||||
long, they don’t truncate it, but return it unchanged; this will mess up your
|
||||
column lay-out but that’s usually better than the alternative, which would be
|
||||
lying about a value. (If you really want truncation you can always add a
|
||||
slice operation, as in <code class="docutils literal notranslate"><span class="pre">x.ljust(n)[:n]</span></code>.)</p>
|
||||
<p>There is another method, <a class="reference internal" href="../library/stdtypes.html#str.zfill" title="str.zfill"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.zfill()</span></code></a>, which pads a numeric string on the
|
||||
left with zeros. It understands about plus and minus signs:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'12'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
|
||||
<span class="go">'00012'</span>
|
||||
<span class="gp">>>> </span><span class="s1">'-3.14'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
|
||||
<span class="go">'-003.14'</span>
|
||||
<span class="gp">>>> </span><span class="s1">'3.14159265359'</span><span class="o">.</span><span class="n">zfill</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span>
|
||||
<span class="go">'3.14159265359'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="old-string-formatting">
|
||||
<h3><span class="section-number">7.1.4. </span>Old string formatting<a class="headerlink" href="#old-string-formatting" title="Link to this heading">¶</a></h3>
|
||||
<p>The % operator (modulo) can also be used for string formatting.
|
||||
Given <code class="docutils literal notranslate"><span class="pre">format</span> <span class="pre">%</span> <span class="pre">values</span></code> (where <em>format</em> is a string),
|
||||
<code class="docutils literal notranslate"><span class="pre">%</span></code> conversion specifications in <em>format</em> are replaced with
|
||||
zero or more elements of <em>values</em>.
|
||||
This operation is commonly known as string
|
||||
interpolation. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">math</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'The value of pi is approximately </span><span class="si">%5.3f</span><span class="s1">.'</span> <span class="o">%</span> <span class="n">math</span><span class="o">.</span><span class="n">pi</span><span class="p">)</span>
|
||||
<span class="go">The value of pi is approximately 3.142.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>More information can be found in the <a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a> section.</p>
|
||||
</section>
|
||||
</section>
|
||||
<section id="reading-and-writing-files">
|
||||
<span id="tut-files"></span><h2><span class="section-number">7.2. </span>Reading and Writing Files<a class="headerlink" href="#reading-and-writing-files" title="Link to this heading">¶</a></h2>
|
||||
<p id="index-1"><a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> returns a <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a>, and is most commonly used with
|
||||
two positional arguments and one keyword argument:
|
||||
<code class="docutils literal notranslate"><span class="pre">open(filename,</span> <span class="pre">mode,</span> <span class="pre">encoding=None)</span></code></p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'workfile'</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">"utf-8"</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The first argument is a string containing the filename. The second argument is
|
||||
another string containing a few characters describing the way in which the file
|
||||
will be used. <em>mode</em> can be <code class="docutils literal notranslate"><span class="pre">'r'</span></code> when the file will only be read, <code class="docutils literal notranslate"><span class="pre">'w'</span></code>
|
||||
for only writing (an existing file with the same name will be erased), and
|
||||
<code class="docutils literal notranslate"><span class="pre">'a'</span></code> opens the file for appending; any data written to the file is
|
||||
automatically added to the end. <code class="docutils literal notranslate"><span class="pre">'r+'</span></code> opens the file for both reading and
|
||||
writing. The <em>mode</em> argument is optional; <code class="docutils literal notranslate"><span class="pre">'r'</span></code> will be assumed if it’s
|
||||
omitted.</p>
|
||||
<p>Normally, files are opened in <em class="dfn">text mode</em>, that means, you read and write
|
||||
strings from and to the file, which are encoded in a specific <em>encoding</em>.
|
||||
If <em>encoding</em> is not specified, the default is platform dependent
|
||||
(see <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>).
|
||||
Because UTF-8 is the modern de-facto standard, <code class="docutils literal notranslate"><span class="pre">encoding="utf-8"</span></code> is
|
||||
recommended unless you know that you need to use a different encoding.
|
||||
Appending a <code class="docutils literal notranslate"><span class="pre">'b'</span></code> to the mode opens the file in <em class="dfn">binary mode</em>.
|
||||
Binary mode data is read and written as <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-class docutils literal notranslate"><span class="pre">bytes</span></code></a> objects.
|
||||
You can not specify <em>encoding</em> when opening file in binary mode.</p>
|
||||
<p>In text mode, the default when reading is to convert platform-specific line
|
||||
endings (<code class="docutils literal notranslate"><span class="pre">\n</span></code> on Unix, <code class="docutils literal notranslate"><span class="pre">\r\n</span></code> on Windows) to just <code class="docutils literal notranslate"><span class="pre">\n</span></code>. When writing in
|
||||
text mode, the default is to convert occurrences of <code class="docutils literal notranslate"><span class="pre">\n</span></code> back to
|
||||
platform-specific line endings. This behind-the-scenes modification
|
||||
to file data is fine for text files, but will corrupt binary data like that in
|
||||
<code class="file docutils literal notranslate"><span class="pre">JPEG</span></code> or <code class="file docutils literal notranslate"><span class="pre">EXE</span></code> files. Be very careful to use binary mode when
|
||||
reading and writing such files.</p>
|
||||
<p>It is good practice to use the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword when dealing
|
||||
with file objects. The advantage is that the file is properly closed
|
||||
after its suite finishes, even if an exception is raised at some
|
||||
point. Using <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> is also much shorter than writing
|
||||
equivalent <a class="reference internal" href="../reference/compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a>-<a class="reference internal" href="../reference/compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> blocks:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'workfile'</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="s2">"utf-8"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">read_data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="c1"># We can check that the file has been automatically closed.</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">closed</span>
|
||||
<span class="go">True</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you’re not using the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> keyword, then you should call
|
||||
<code class="docutils literal notranslate"><span class="pre">f.close()</span></code> to close the file and immediately free up any system
|
||||
resources used by it.</p>
|
||||
<div class="admonition warning">
|
||||
<p class="admonition-title">Warning</p>
|
||||
<p>Calling <code class="docutils literal notranslate"><span class="pre">f.write()</span></code> without using the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> keyword or calling
|
||||
<code class="docutils literal notranslate"><span class="pre">f.close()</span></code> <strong>might</strong> result in the arguments
|
||||
of <code class="docutils literal notranslate"><span class="pre">f.write()</span></code> not being completely written to the disk, even if the
|
||||
program exits successfully.</p>
|
||||
</div>
|
||||
<p>After a file object is closed, either by a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement
|
||||
or by calling <code class="docutils literal notranslate"><span class="pre">f.close()</span></code>, attempts to use the file object will
|
||||
automatically fail.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="gr">ValueError</span>: <span class="n">I/O operation on closed file.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<section id="methods-of-file-objects">
|
||||
<span id="tut-filemethods"></span><h3><span class="section-number">7.2.1. </span>Methods of File Objects<a class="headerlink" href="#methods-of-file-objects" title="Link to this heading">¶</a></h3>
|
||||
<p>The rest of the examples in this section will assume that a file object called
|
||||
<code class="docutils literal notranslate"><span class="pre">f</span></code> has already been created.</p>
|
||||
<p>To read a file’s contents, call <code class="docutils literal notranslate"><span class="pre">f.read(size)</span></code>, which reads some quantity of
|
||||
data and returns it as a string (in text mode) or bytes object (in binary mode).
|
||||
<em>size</em> is an optional numeric argument. When <em>size</em> is omitted or negative, the
|
||||
entire contents of the file will be read and returned; it’s your problem if the
|
||||
file is twice as large as your machine’s memory. Otherwise, at most <em>size</em>
|
||||
characters (in text mode) or <em>size</em> bytes (in binary mode) are read and returned.
|
||||
If the end of the file has been reached, <code class="docutils literal notranslate"><span class="pre">f.read()</span></code> will return an empty
|
||||
string (<code class="docutils literal notranslate"><span class="pre">''</span></code>).</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
<span class="go">'This is the entire file.\n'</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
<span class="go">''</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> reads a single line from the file; a newline character (<code class="docutils literal notranslate"><span class="pre">\n</span></code>)
|
||||
is left at the end of the string, and is only omitted on the last line of the
|
||||
file if the file doesn’t end in a newline. This makes the return value
|
||||
unambiguous; if <code class="docutils literal notranslate"><span class="pre">f.readline()</span></code> returns an empty string, the end of the file
|
||||
has been reached, while a blank line is represented by <code class="docutils literal notranslate"><span class="pre">'\n'</span></code>, a string
|
||||
containing only a single newline.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
|
||||
<span class="go">'This is the first line of the file.\n'</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
|
||||
<span class="go">'Second line of the file\n'</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span>
|
||||
<span class="go">''</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For reading lines from a file, you can loop over the file object. This is memory
|
||||
efficient, fast, and leads to simple code:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">f</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">''</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">This is the first line of the file.</span>
|
||||
<span class="go">Second line of the file</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you want to read all the lines of a file in a list you can also use
|
||||
<code class="docutils literal notranslate"><span class="pre">list(f)</span></code> or <code class="docutils literal notranslate"><span class="pre">f.readlines()</span></code>.</p>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">f.write(string)</span></code> writes the contents of <em>string</em> to the file, returning
|
||||
the number of characters written.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'This is a test</span><span class="se">\n</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="go">15</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Other types of objects need to be converted – either to a string (in text mode)
|
||||
or a bytes object (in binary mode) – before writing them:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">value</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'the answer'</span><span class="p">,</span> <span class="mi">42</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="nb">str</span><span class="p">(</span><span class="n">value</span><span class="p">)</span> <span class="c1"># convert the tuple to string</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">18</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">f.tell()</span></code> returns an integer giving the file object’s current position in the file
|
||||
represented as number of bytes from the beginning of the file when in binary mode and
|
||||
an opaque number when in text mode.</p>
|
||||
<p>To change the file object’s position, use <code class="docutils literal notranslate"><span class="pre">f.seek(offset,</span> <span class="pre">whence)</span></code>. The position is computed
|
||||
from adding <em>offset</em> to a reference point; the reference point is selected by
|
||||
the <em>whence</em> argument. A <em>whence</em> value of 0 measures from the beginning
|
||||
of the file, 1 uses the current file position, and 2 uses the end of the file as
|
||||
the reference point. <em>whence</em> can be omitted and defaults to 0, using the
|
||||
beginning of the file as the reference point.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'workfile'</span><span class="p">,</span> <span class="s1">'rb+'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">'0123456789abcdef'</span><span class="p">)</span>
|
||||
<span class="go">16</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># Go to the 6th byte in the file</span>
|
||||
<span class="go">5</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||||
<span class="go">b'5'</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="o">-</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span> <span class="c1"># Go to the 3rd byte before the end</span>
|
||||
<span class="go">13</span>
|
||||
<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
|
||||
<span class="go">b'd'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>In text files (those opened without a <code class="docutils literal notranslate"><span class="pre">b</span></code> in the mode string), only seeks
|
||||
relative to the beginning of the file are allowed (the exception being seeking
|
||||
to the very file end with <code class="docutils literal notranslate"><span class="pre">seek(0,</span> <span class="pre">2)</span></code>) and the only valid <em>offset</em> values are
|
||||
those returned from the <code class="docutils literal notranslate"><span class="pre">f.tell()</span></code>, or zero. Any other <em>offset</em> value produces
|
||||
undefined behaviour.</p>
|
||||
<p>File objects have some additional methods, such as <a class="reference internal" href="../library/io.html#io.IOBase.isatty" title="io.IOBase.isatty"><code class="xref py py-meth docutils literal notranslate"><span class="pre">isatty()</span></code></a> and
|
||||
<a class="reference internal" href="../library/io.html#io.IOBase.truncate" title="io.IOBase.truncate"><code class="xref py py-meth docutils literal notranslate"><span class="pre">truncate()</span></code></a> which are less frequently used; consult the Library
|
||||
Reference for a complete guide to file objects.</p>
|
||||
</section>
|
||||
<section id="saving-structured-data-with-json">
|
||||
<span id="tut-json"></span><h3><span class="section-number">7.2.2. </span>Saving structured data with <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a><a class="headerlink" href="#saving-structured-data-with-json" title="Link to this heading">¶</a></h3>
|
||||
<p id="index-2">Strings can easily be written to and read from a file. Numbers take a bit more
|
||||
effort, since the <a class="reference internal" href="../library/io.html#io.TextIOBase.read" title="io.TextIOBase.read"><code class="xref py py-meth docutils literal notranslate"><span class="pre">read()</span></code></a> method only returns strings, which will have to
|
||||
be passed to a function like <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-func docutils literal notranslate"><span class="pre">int()</span></code></a>, which takes a string like <code class="docutils literal notranslate"><span class="pre">'123'</span></code>
|
||||
and returns its numeric value 123. When you want to save more complex data
|
||||
types like nested lists and dictionaries, parsing and serializing by hand
|
||||
becomes complicated.</p>
|
||||
<p>Rather than having users constantly writing and debugging code to save
|
||||
complicated data types to files, Python allows you to use the popular data
|
||||
interchange format called <a class="reference external" href="https://json.org">JSON (JavaScript Object Notation)</a>. The standard module called <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> can take Python
|
||||
data hierarchies, and convert them to string representations; this process is
|
||||
called <em class="dfn">serializing</em>. Reconstructing the data from the string representation
|
||||
is called <em class="dfn">deserializing</em>. Between serializing and deserializing, the
|
||||
string representing the object may have been stored in a file or data, or
|
||||
sent over a network connection to some distant machine.</p>
|
||||
<div class="admonition note">
|
||||
<p class="admonition-title">Note</p>
|
||||
<p>The JSON format is commonly used by modern applications to allow for data
|
||||
exchange. Many programmers are already familiar with it, which makes
|
||||
it a good choice for interoperability.</p>
|
||||
</div>
|
||||
<p>If you have an object <code class="docutils literal notranslate"><span class="pre">x</span></code>, you can view its JSON string representation with a
|
||||
simple line of code:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">json</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="s1">'simple'</span><span class="p">,</span> <span class="s1">'list'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">json</span><span class="o">.</span><span class="n">dumps</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
|
||||
<span class="go">'[1, "simple", "list"]'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Another variant of the <a class="reference internal" href="../library/json.html#json.dumps" title="json.dumps"><code class="xref py py-func docutils literal notranslate"><span class="pre">dumps()</span></code></a> function, called <a class="reference internal" href="../library/json.html#json.dump" title="json.dump"><code class="xref py py-func docutils literal notranslate"><span class="pre">dump()</span></code></a>,
|
||||
simply serializes the object to a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a>. So if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a
|
||||
<a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object opened for writing, we can do this:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">json</span><span class="o">.</span><span class="n">dump</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">f</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>To decode the object again, if <code class="docutils literal notranslate"><span class="pre">f</span></code> is a <a class="reference internal" href="../glossary.html#term-binary-file"><span class="xref std std-term">binary file</span></a> or
|
||||
<a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> object which has been opened for reading:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="n">json</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="admonition note">
|
||||
<p class="admonition-title">Note</p>
|
||||
<p>JSON files must be encoded in UTF-8. Use <code class="docutils literal notranslate"><span class="pre">encoding="utf-8"</span></code> when opening
|
||||
JSON file as a <a class="reference internal" href="../glossary.html#term-text-file"><span class="xref std std-term">text file</span></a> for both of reading and writing.</p>
|
||||
</div>
|
||||
<p>This simple serialization technique can handle lists and dictionaries, but
|
||||
serializing arbitrary class instances in JSON requires a bit of extra effort.
|
||||
The reference for the <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> module contains an explanation of this.</p>
|
||||
<div class="admonition seealso">
|
||||
<p class="admonition-title">See also</p>
|
||||
<p><a class="reference internal" href="../library/pickle.html#module-pickle" title="pickle: Convert Python objects to streams of bytes and back."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> - the pickle module</p>
|
||||
<p>Contrary to <a class="reference internal" href="#tut-json"><span class="std std-ref">JSON</span></a>, <em>pickle</em> is a protocol which allows
|
||||
the serialization of arbitrarily complex Python objects. As such, it is
|
||||
specific to Python and cannot be used to communicate with applications
|
||||
written in other languages. It is also insecure by default:
|
||||
deserializing pickle data coming from an untrusted source can execute
|
||||
arbitrary code, if the data was crafted by a skilled attacker.</p>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">7. Input and Output</a><ul>
|
||||
<li><a class="reference internal" href="#fancier-output-formatting">7.1. Fancier Output Formatting</a><ul>
|
||||
<li><a class="reference internal" href="#formatted-string-literals">7.1.1. Formatted String Literals</a></li>
|
||||
<li><a class="reference internal" href="#the-string-format-method">7.1.2. The String format() Method</a></li>
|
||||
<li><a class="reference internal" href="#manual-string-formatting">7.1.3. Manual String Formatting</a></li>
|
||||
<li><a class="reference internal" href="#old-string-formatting">7.1.4. Old string formatting</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#reading-and-writing-files">7.2. Reading and Writing Files</a><ul>
|
||||
<li><a class="reference internal" href="#methods-of-file-objects">7.2.1. Methods of File Objects</a></li>
|
||||
<li><a class="reference internal" href="#saving-structured-data-with-json">7.2.2. Saving structured data with <code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="modules.html"
|
||||
title="previous chapter"><span class="section-number">6. </span>Modules</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="errors.html"
|
||||
title="next chapter"><span class="section-number">8. </span>Errors and Exceptions</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/inputoutput.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="errors.html" title="8. Errors and Exceptions"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="modules.html" title="6. Modules"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">7. </span>Input and Output</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
367
Dependencies/Python/Doc/html/tutorial/interactive.html
vendored
Normal file
367
Dependencies/Python/Doc/html/tutorial/interactive.html
vendored
Normal file
@@ -0,0 +1,367 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="14. Interactive Input Editing and History Substitution" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/interactive.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Some versions of the Python interpreter support editing of the current input line and history substitution, similar to facilities found in the Korn shell and the GNU Bash shell. This is implemented..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>14. Interactive Input Editing and History Substitution — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="15. Floating-Point Arithmetic: Issues and Limitations" href="floatingpoint.html" />
|
||||
<link rel="prev" title="13. What Now?" href="whatnow.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/interactive.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">14. Interactive Input Editing and History Substitution</a><ul>
|
||||
<li><a class="reference internal" href="#tab-completion-and-history-editing">14.1. Tab Completion and History Editing</a></li>
|
||||
<li><a class="reference internal" href="#alternatives-to-the-interactive-interpreter">14.2. Alternatives to the Interactive Interpreter</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="whatnow.html"
|
||||
title="previous chapter"><span class="section-number">13. </span>What Now?</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="floatingpoint.html"
|
||||
title="next chapter"><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/interactive.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="floatingpoint.html" title="15. Floating-Point Arithmetic: Issues and Limitations"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="whatnow.html" title="13. What Now?"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="interactive-input-editing-and-history-substitution">
|
||||
<span id="tut-interacting"></span><h1><span class="section-number">14. </span>Interactive Input Editing and History Substitution<a class="headerlink" href="#interactive-input-editing-and-history-substitution" title="Link to this heading">¶</a></h1>
|
||||
<p>Some versions of the Python interpreter support editing of the current input
|
||||
line and history substitution, similar to facilities found in the Korn shell and
|
||||
the GNU Bash shell. This is implemented using the <a class="reference external" href="https://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> library,
|
||||
which supports various styles of editing. This library has its own
|
||||
documentation which we won’t duplicate here.</p>
|
||||
<section id="tab-completion-and-history-editing">
|
||||
<span id="tut-keybindings"></span><h2><span class="section-number">14.1. </span>Tab Completion and History Editing<a class="headerlink" href="#tab-completion-and-history-editing" title="Link to this heading">¶</a></h2>
|
||||
<p>Completion of variable and module names is
|
||||
<a class="reference internal" href="../library/site.html#rlcompleter-config"><span class="std std-ref">automatically enabled</span></a> at interpreter startup so
|
||||
that the <kbd class="kbd docutils literal notranslate">Tab</kbd> key invokes the completion function; it looks at
|
||||
Python statement names, the current local variables, and the available
|
||||
module names. For dotted expressions such as <code class="docutils literal notranslate"><span class="pre">string.a</span></code>, it will evaluate
|
||||
the expression up to the final <code class="docutils literal notranslate"><span class="pre">'.'</span></code> and then suggest completions from
|
||||
the attributes of the resulting object. Note that this may execute
|
||||
application-defined code if an object with a <a class="reference internal" href="../reference/datamodel.html#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method
|
||||
is part of the expression. The default configuration also saves your
|
||||
history into a file named <code class="file docutils literal notranslate"><span class="pre">.python_history</span></code> in your user directory.
|
||||
The history will be available again during the next interactive interpreter
|
||||
session.</p>
|
||||
</section>
|
||||
<section id="alternatives-to-the-interactive-interpreter">
|
||||
<span id="tut-commentary"></span><h2><span class="section-number">14.2. </span>Alternatives to the Interactive Interpreter<a class="headerlink" href="#alternatives-to-the-interactive-interpreter" title="Link to this heading">¶</a></h2>
|
||||
<p>This facility is an enormous step forward compared to earlier versions of the
|
||||
interpreter; however, some wishes are left: It would be nice if the proper
|
||||
indentation were suggested on continuation lines (the parser knows if an
|
||||
<a class="reference internal" href="../library/token.html#token.INDENT" title="token.INDENT"><code class="xref py py-data docutils literal notranslate"><span class="pre">INDENT</span></code></a> token is required next). The completion mechanism might
|
||||
use the interpreter’s symbol table. A command to check (or even suggest)
|
||||
matching parentheses, quotes, etc., would also be useful.</p>
|
||||
<p>One alternative enhanced interactive interpreter that has been around for quite
|
||||
some time is <a class="reference external" href="https://ipython.org/">IPython</a>, which features tab completion, object exploration and
|
||||
advanced history management. It can also be thoroughly customized and embedded
|
||||
into other applications. Another similar enhanced interactive environment is
|
||||
<a class="reference external" href="https://bpython-interpreter.org/">bpython</a>.</p>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">14. Interactive Input Editing and History Substitution</a><ul>
|
||||
<li><a class="reference internal" href="#tab-completion-and-history-editing">14.1. Tab Completion and History Editing</a></li>
|
||||
<li><a class="reference internal" href="#alternatives-to-the-interactive-interpreter">14.2. Alternatives to the Interactive Interpreter</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="whatnow.html"
|
||||
title="previous chapter"><span class="section-number">13. </span>What Now?</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="floatingpoint.html"
|
||||
title="next chapter"><span class="section-number">15. </span>Floating-Point Arithmetic: Issues and Limitations</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/interactive.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="floatingpoint.html" title="15. Floating-Point Arithmetic: Issues and Limitations"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="whatnow.html" title="13. What Now?"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
471
Dependencies/Python/Doc/html/tutorial/interpreter.html
vendored
Normal file
471
Dependencies/Python/Doc/html/tutorial/interpreter.html
vendored
Normal file
@@ -0,0 +1,471 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="2. Using the Python Interpreter" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/interpreter.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Invoking the Interpreter: The Python interpreter is usually installed as/usr/local/bin/python3.13 on those machines where it is available; putting/usr/local/bin in your Unix shell’s search path mak..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Invoking the Interpreter: The Python interpreter is usually installed as/usr/local/bin/python3.13 on those machines where it is available; putting/usr/local/bin in your Unix shell’s search path mak..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>2. Using the Python Interpreter — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="3. An Informal Introduction to Python" href="introduction.html" />
|
||||
<link rel="prev" title="1. Whetting Your Appetite" href="appetite.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/interpreter.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">2. Using the Python Interpreter</a><ul>
|
||||
<li><a class="reference internal" href="#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
|
||||
<li><a class="reference internal" href="#argument-passing">2.1.1. Argument Passing</a></li>
|
||||
<li><a class="reference internal" href="#interactive-mode">2.1.2. Interactive Mode</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
|
||||
<li><a class="reference internal" href="#source-code-encoding">2.2.1. Source Code Encoding</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="appetite.html"
|
||||
title="previous chapter"><span class="section-number">1. </span>Whetting Your Appetite</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="introduction.html"
|
||||
title="next chapter"><span class="section-number">3. </span>An Informal Introduction to Python</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/interpreter.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="introduction.html" title="3. An Informal Introduction to Python"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appetite.html" title="1. Whetting Your Appetite"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">2. </span>Using the Python Interpreter</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="using-the-python-interpreter">
|
||||
<span id="tut-using"></span><h1><span class="section-number">2. </span>Using the Python Interpreter<a class="headerlink" href="#using-the-python-interpreter" title="Link to this heading">¶</a></h1>
|
||||
<section id="invoking-the-interpreter">
|
||||
<span id="tut-invoking"></span><h2><span class="section-number">2.1. </span>Invoking the Interpreter<a class="headerlink" href="#invoking-the-interpreter" title="Link to this heading">¶</a></h2>
|
||||
<p>The Python interpreter is usually installed as <code class="docutils literal notranslate"><span class="pre">/usr/local/bin/python3.13</span></code>
|
||||
on those machines where it is available; putting <code class="file docutils literal notranslate"><span class="pre">/usr/local/bin</span></code> in your
|
||||
Unix shell’s search path makes it possible to start it by typing the command:</p>
|
||||
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>python3.13
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>to the shell. <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a> Since the choice of the directory where the interpreter lives
|
||||
is an installation option, other places are possible; check with your local
|
||||
Python guru or system administrator. (E.g., <code class="file docutils literal notranslate"><span class="pre">/usr/local/python</span></code> is a
|
||||
popular alternative location.)</p>
|
||||
<p>On Windows machines where you have installed Python from the <a class="reference internal" href="../using/windows.html#windows-store"><span class="std std-ref">Microsoft Store</span></a>, the <code class="docutils literal notranslate"><span class="pre">python3.13</span></code> command will be available. If you have
|
||||
the <a class="reference internal" href="../using/windows.html#launcher"><span class="std std-ref">py.exe launcher</span></a> installed, you can use the <code class="file docutils literal notranslate"><span class="pre">py</span></code>
|
||||
command. See <a class="reference internal" href="../using/windows.html#setting-envvars"><span class="std std-ref">Excursus: Setting environment variables</span></a> for other ways to launch Python.</p>
|
||||
<p>Typing an end-of-file character (<kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">D</kbd> on Unix, <kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">Z</kbd> on
|
||||
Windows) at the primary prompt causes the interpreter to exit with a zero exit
|
||||
status. If that doesn’t work, you can exit the interpreter by typing the
|
||||
following command: <code class="docutils literal notranslate"><span class="pre">quit()</span></code>.</p>
|
||||
<p>The interpreter’s line-editing features include interactive editing, history
|
||||
substitution and code completion on systems that support the <a class="reference external" href="https://tiswww.case.edu/php/chet/readline/rltop.html">GNU Readline</a> library.
|
||||
Perhaps the quickest check to see whether command line editing is supported is
|
||||
typing <kbd class="kbd docutils literal notranslate">Control</kbd>-<kbd class="kbd docutils literal notranslate">P</kbd> to the first Python prompt you get. If it beeps, you
|
||||
have command line editing; see Appendix <a class="reference internal" href="interactive.html#tut-interacting"><span class="std std-ref">Interactive Input Editing and History Substitution</span></a> for an
|
||||
introduction to the keys. If nothing appears to happen, or if <code class="docutils literal notranslate"><span class="pre">^P</span></code> is
|
||||
echoed, command line editing isn’t available; you’ll only be able to use
|
||||
backspace to remove characters from the current line.</p>
|
||||
<p>The interpreter operates somewhat like the Unix shell: when called with standard
|
||||
input connected to a tty device, it reads and executes commands interactively;
|
||||
when called with a file name argument or with a file as standard input, it reads
|
||||
and executes a <em>script</em> from that file.</p>
|
||||
<p>A second way of starting the interpreter is <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>,
|
||||
which executes the statement(s) in <em>command</em>, analogous to the shell’s
|
||||
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> option. Since Python statements often contain spaces or other
|
||||
characters that are special to the shell, it is usually advised to quote
|
||||
<em>command</em> in its entirety.</p>
|
||||
<p>Some Python modules are also useful as scripts. These can be invoked using
|
||||
<code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]</span> <span class="pre">...</span></code>, which executes the source file for <em>module</em> as
|
||||
if you had spelled out its full name on the command line.</p>
|
||||
<p>When a script file is used, it is sometimes useful to be able to run the script
|
||||
and enter interactive mode afterwards. This can be done by passing <a class="reference internal" href="../using/cmdline.html#cmdoption-i"><code class="xref std std-option docutils literal notranslate"><span class="pre">-i</span></code></a>
|
||||
before the script.</p>
|
||||
<p>All command line options are described in <a class="reference internal" href="../using/cmdline.html#using-on-general"><span class="std std-ref">Command line and environment</span></a>.</p>
|
||||
<section id="argument-passing">
|
||||
<span id="tut-argpassing"></span><h3><span class="section-number">2.1.1. </span>Argument Passing<a class="headerlink" href="#argument-passing" title="Link to this heading">¶</a></h3>
|
||||
<p>When known to the interpreter, the script name and additional arguments
|
||||
thereafter are turned into a list of strings and assigned to the <code class="docutils literal notranslate"><span class="pre">argv</span></code>
|
||||
variable in the <code class="docutils literal notranslate"><span class="pre">sys</span></code> module. You can access this list by executing <code class="docutils literal notranslate"><span class="pre">import</span>
|
||||
<span class="pre">sys</span></code>. The length of the list is at least one; when no script and no arguments
|
||||
are given, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is an empty string. When the script name is given as
|
||||
<code class="docutils literal notranslate"><span class="pre">'-'</span></code> (meaning standard input), <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-'</span></code>. When
|
||||
<a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to <code class="docutils literal notranslate"><span class="pre">'-c'</span></code>. When
|
||||
<a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a> <em>module</em> is used, <code class="docutils literal notranslate"><span class="pre">sys.argv[0]</span></code> is set to the full name of the
|
||||
located module. Options found after <a class="reference internal" href="../using/cmdline.html#cmdoption-c"><code class="xref std std-option docutils literal notranslate"><span class="pre">-c</span></code></a> <em>command</em> or <a class="reference internal" href="../using/cmdline.html#cmdoption-m"><code class="xref std std-option docutils literal notranslate"><span class="pre">-m</span></code></a>
|
||||
<em>module</em> are not consumed by the Python interpreter’s option processing but
|
||||
left in <code class="docutils literal notranslate"><span class="pre">sys.argv</span></code> for the command or module to handle.</p>
|
||||
</section>
|
||||
<section id="interactive-mode">
|
||||
<span id="tut-interactive"></span><h3><span class="section-number">2.1.2. </span>Interactive Mode<a class="headerlink" href="#interactive-mode" title="Link to this heading">¶</a></h3>
|
||||
<p>When commands are read from a tty, the interpreter is said to be in <em>interactive
|
||||
mode</em>. In this mode it prompts for the next command with the <em>primary prompt</em>,
|
||||
usually three greater-than signs (<code class="docutils literal notranslate"><span class="pre">>>></span></code>); for continuation lines it prompts
|
||||
with the <em>secondary prompt</em>, by default three dots (<code class="docutils literal notranslate"><span class="pre">...</span></code>). The interpreter
|
||||
prints a welcome message stating its version number and a copyright notice
|
||||
before printing the first prompt:</p>
|
||||
<div class="highlight-shell-session notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python3.13
|
||||
<span class="go">Python 3.13 (default, April 4 2023, 09:25:04)</span>
|
||||
<span class="go">[GCC 10.2.0] on linux</span>
|
||||
<span class="go">Type "help", "copyright", "credits" or "license" for more information.</span>
|
||||
<span class="go">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Continuation lines are needed when entering a multi-line construct. As an
|
||||
example, take a look at this <a class="reference internal" href="../reference/compound_stmts.html#if"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">if</span></code></a> statement:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">the_world_is_flat</span> <span class="o">=</span> <span class="kc">True</span>
|
||||
<span class="gp">>>> </span><span class="k">if</span> <span class="n">the_world_is_flat</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">"Be careful not to fall off!"</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">Be careful not to fall off!</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For more on interactive mode, see <a class="reference internal" href="appendix.html#tut-interac"><span class="std std-ref">Interactive Mode</span></a>.</p>
|
||||
</section>
|
||||
</section>
|
||||
<section id="the-interpreter-and-its-environment">
|
||||
<span id="tut-interp"></span><h2><span class="section-number">2.2. </span>The Interpreter and Its Environment<a class="headerlink" href="#the-interpreter-and-its-environment" title="Link to this heading">¶</a></h2>
|
||||
<section id="source-code-encoding">
|
||||
<span id="tut-source-encoding"></span><h3><span class="section-number">2.2.1. </span>Source Code Encoding<a class="headerlink" href="#source-code-encoding" title="Link to this heading">¶</a></h3>
|
||||
<p>By default, Python source files are treated as encoded in UTF-8. In that
|
||||
encoding, characters of most languages in the world can be used simultaneously
|
||||
in string literals, identifiers and comments — although the standard library
|
||||
only uses ASCII characters for identifiers, a convention that any portable code
|
||||
should follow. To display all these characters properly, your editor must
|
||||
recognize that the file is UTF-8, and it must use a font that supports all the
|
||||
characters in the file.</p>
|
||||
<p>To declare an encoding other than the default one, a special comment line
|
||||
should be added as the <em>first</em> line of the file. The syntax is as follows:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: encoding -*-</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>where <em>encoding</em> is one of the valid <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> supported by Python.</p>
|
||||
<p>For example, to declare that Windows-1252 encoding is to be used, the first
|
||||
line of your source code file should be:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># -*- coding: cp1252 -*-</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>One exception to the <em>first line</em> rule is when the source code starts with a
|
||||
<a class="reference internal" href="appendix.html#tut-scripts"><span class="std std-ref">UNIX “shebang” line</span></a>. In this case, the encoding
|
||||
declaration should be added as the second line of the file. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="ch">#!/usr/bin/env python3</span>
|
||||
<span class="c1"># -*- coding: cp1252 -*-</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p class="rubric">Footnotes</p>
|
||||
<aside class="footnote-list brackets">
|
||||
<aside class="footnote brackets" id="id2" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>On Unix, the Python 3.x interpreter is by default not installed with the
|
||||
executable named <code class="docutils literal notranslate"><span class="pre">python</span></code>, so that it does not conflict with a
|
||||
simultaneously installed Python 2.x executable.</p>
|
||||
</aside>
|
||||
</aside>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">2. Using the Python Interpreter</a><ul>
|
||||
<li><a class="reference internal" href="#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
|
||||
<li><a class="reference internal" href="#argument-passing">2.1.1. Argument Passing</a></li>
|
||||
<li><a class="reference internal" href="#interactive-mode">2.1.2. Interactive Mode</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
|
||||
<li><a class="reference internal" href="#source-code-encoding">2.2.1. Source Code Encoding</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="appetite.html"
|
||||
title="previous chapter"><span class="section-number">1. </span>Whetting Your Appetite</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="introduction.html"
|
||||
title="next chapter"><span class="section-number">3. </span>An Informal Introduction to Python</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/interpreter.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="introduction.html" title="3. An Informal Introduction to Python"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="appetite.html" title="1. Whetting Your Appetite"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">2. </span>Using the Python Interpreter</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
882
Dependencies/Python/Doc/html/tutorial/introduction.html
vendored
Normal file
882
Dependencies/Python/Doc/html/tutorial/introduction.html
vendored
Normal file
@@ -0,0 +1,882 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="3. An Informal Introduction to Python" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/introduction.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and …): to repeat the example, you must type everything after the prompt, when the prompt ap..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="In the following examples, input and output are distinguished by the presence or absence of prompts (>>> and …): to repeat the example, you must type everything after the prompt, when the prompt ap..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>3. An Informal Introduction to Python — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="4. More Control Flow Tools" href="controlflow.html" />
|
||||
<link rel="prev" title="2. Using the Python Interpreter" href="interpreter.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/introduction.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">3. An Informal Introduction to Python</a><ul>
|
||||
<li><a class="reference internal" href="#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
|
||||
<li><a class="reference internal" href="#numbers">3.1.1. Numbers</a></li>
|
||||
<li><a class="reference internal" href="#text">3.1.2. Text</a></li>
|
||||
<li><a class="reference internal" href="#lists">3.1.3. Lists</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="interpreter.html"
|
||||
title="previous chapter"><span class="section-number">2. </span>Using the Python Interpreter</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="controlflow.html"
|
||||
title="next chapter"><span class="section-number">4. </span>More Control Flow Tools</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/introduction.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="controlflow.html" title="4. More Control Flow Tools"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interpreter.html" title="2. Using the Python Interpreter"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>An Informal Introduction to Python</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="an-informal-introduction-to-python">
|
||||
<span id="tut-informal"></span><h1><span class="section-number">3. </span>An Informal Introduction to Python<a class="headerlink" href="#an-informal-introduction-to-python" title="Link to this heading">¶</a></h1>
|
||||
<p>In the following examples, input and output are distinguished by the presence or
|
||||
absence of prompts (<a class="reference internal" href="../glossary.html#term-0"><span class="xref std std-term">>>></span></a> and <a class="reference internal" href="../glossary.html#term-..."><span class="xref std std-term">…</span></a>): to repeat the example, you must type
|
||||
everything after the prompt, when the prompt appears; lines that do not begin
|
||||
with a prompt are output from the interpreter. Note that a secondary prompt on a
|
||||
line by itself in an example means you must type a blank line; this is used to
|
||||
end a multi-line command.</p>
|
||||
<p>You can toggle the display of prompts and output by clicking on <code class="docutils literal notranslate"><span class="pre">>>></span></code>
|
||||
in the upper-right corner of an example box. If you hide the prompts
|
||||
and output for an example, then you can easily copy and paste the input
|
||||
lines into your interpreter.</p>
|
||||
<p id="index-0">Many of the examples in this manual, even those entered at the interactive
|
||||
prompt, include comments. Comments in Python start with the hash character,
|
||||
<code class="docutils literal notranslate"><span class="pre">#</span></code>, and extend to the end of the physical line. A comment may appear at the
|
||||
start of a line or following whitespace or code, but not within a string
|
||||
literal. A hash character within a string literal is just a hash character.
|
||||
Since comments are to clarify code and are not interpreted by Python, they may
|
||||
be omitted when typing in examples.</p>
|
||||
<p>Some examples:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># this is the first comment</span>
|
||||
<span class="n">spam</span> <span class="o">=</span> <span class="mi">1</span> <span class="c1"># and this is the second comment</span>
|
||||
<span class="c1"># ... and now a third!</span>
|
||||
<span class="n">text</span> <span class="o">=</span> <span class="s2">"# This is not a comment because it's inside quotes."</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<section id="using-python-as-a-calculator">
|
||||
<span id="tut-calculator"></span><h2><span class="section-number">3.1. </span>Using Python as a Calculator<a class="headerlink" href="#using-python-as-a-calculator" title="Link to this heading">¶</a></h2>
|
||||
<p>Let’s try some simple Python commands. Start the interpreter and wait for the
|
||||
primary prompt, <code class="docutils literal notranslate"><span class="pre">>>></span></code>. (It shouldn’t take long.)</p>
|
||||
<section id="numbers">
|
||||
<span id="tut-numbers"></span><h3><span class="section-number">3.1.1. </span>Numbers<a class="headerlink" href="#numbers" title="Link to this heading">¶</a></h3>
|
||||
<p>The interpreter acts as a simple calculator: you can type an expression at it
|
||||
and it will write the value. Expression syntax is straightforward: the
|
||||
operators <code class="docutils literal notranslate"><span class="pre">+</span></code>, <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">*</span></code> and <code class="docutils literal notranslate"><span class="pre">/</span></code> can be used to perform
|
||||
arithmetic; parentheses (<code class="docutils literal notranslate"><span class="pre">()</span></code>) can be used for grouping.
|
||||
For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">2</span> <span class="o">+</span> <span class="mi">2</span>
|
||||
<span class="go">4</span>
|
||||
<span class="gp">>>> </span><span class="mi">50</span> <span class="o">-</span> <span class="mi">5</span><span class="o">*</span><span class="mi">6</span>
|
||||
<span class="go">20</span>
|
||||
<span class="gp">>>> </span><span class="p">(</span><span class="mi">50</span> <span class="o">-</span> <span class="mi">5</span><span class="o">*</span><span class="mi">6</span><span class="p">)</span> <span class="o">/</span> <span class="mi">4</span>
|
||||
<span class="go">5.0</span>
|
||||
<span class="gp">>>> </span><span class="mi">8</span> <span class="o">/</span> <span class="mi">5</span> <span class="c1"># division always returns a floating-point number</span>
|
||||
<span class="go">1.6</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The integer numbers (e.g. <code class="docutils literal notranslate"><span class="pre">2</span></code>, <code class="docutils literal notranslate"><span class="pre">4</span></code>, <code class="docutils literal notranslate"><span class="pre">20</span></code>) have type <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a>,
|
||||
the ones with a fractional part (e.g. <code class="docutils literal notranslate"><span class="pre">5.0</span></code>, <code class="docutils literal notranslate"><span class="pre">1.6</span></code>) have type
|
||||
<a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>. We will see more about numeric types later in the tutorial.</p>
|
||||
<p>Division (<code class="docutils literal notranslate"><span class="pre">/</span></code>) always returns a float. To do <a class="reference internal" href="../glossary.html#term-floor-division"><span class="xref std std-term">floor division</span></a> and
|
||||
get an integer result you can use the <code class="docutils literal notranslate"><span class="pre">//</span></code> operator; to calculate
|
||||
the remainder you can use <code class="docutils literal notranslate"><span class="pre">%</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">17</span> <span class="o">/</span> <span class="mi">3</span> <span class="c1"># classic division returns a float</span>
|
||||
<span class="go">5.666666666666667</span>
|
||||
<span class="gp">>>></span>
|
||||
<span class="gp">>>> </span><span class="mi">17</span> <span class="o">//</span> <span class="mi">3</span> <span class="c1"># floor division discards the fractional part</span>
|
||||
<span class="go">5</span>
|
||||
<span class="gp">>>> </span><span class="mi">17</span> <span class="o">%</span> <span class="mi">3</span> <span class="c1"># the % operator returns the remainder of the division</span>
|
||||
<span class="go">2</span>
|
||||
<span class="gp">>>> </span><span class="mi">5</span> <span class="o">*</span> <span class="mi">3</span> <span class="o">+</span> <span class="mi">2</span> <span class="c1"># floored quotient * divisor + remainder</span>
|
||||
<span class="go">17</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>With Python, it is possible to use the <code class="docutils literal notranslate"><span class="pre">**</span></code> operator to calculate powers <a class="footnote-reference brackets" href="#id3" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">5</span> <span class="o">**</span> <span class="mi">2</span> <span class="c1"># 5 squared</span>
|
||||
<span class="go">25</span>
|
||||
<span class="gp">>>> </span><span class="mi">2</span> <span class="o">**</span> <span class="mi">7</span> <span class="c1"># 2 to the power of 7</span>
|
||||
<span class="go">128</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The equal sign (<code class="docutils literal notranslate"><span class="pre">=</span></code>) is used to assign a value to a variable. Afterwards, no
|
||||
result is displayed before the next interactive prompt:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">width</span> <span class="o">=</span> <span class="mi">20</span>
|
||||
<span class="gp">>>> </span><span class="n">height</span> <span class="o">=</span> <span class="mi">5</span> <span class="o">*</span> <span class="mi">9</span>
|
||||
<span class="gp">>>> </span><span class="n">width</span> <span class="o">*</span> <span class="n">height</span>
|
||||
<span class="go">900</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If a variable is not “defined” (assigned a value), trying to use it will
|
||||
give you an error:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">n</span> <span class="c1"># try to access an undefined variable</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="gr">NameError</span>: <span class="n">name 'n' is not defined</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>There is full support for floating point; operators with mixed type operands
|
||||
convert the integer operand to floating point:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="mi">4</span> <span class="o">*</span> <span class="mf">3.75</span> <span class="o">-</span> <span class="mi">1</span>
|
||||
<span class="go">14.0</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>In interactive mode, the last printed expression is assigned to the variable
|
||||
<code class="docutils literal notranslate"><span class="pre">_</span></code>. This means that when you are using Python as a desk calculator, it is
|
||||
somewhat easier to continue calculations, for example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">tax</span> <span class="o">=</span> <span class="mf">12.5</span> <span class="o">/</span> <span class="mi">100</span>
|
||||
<span class="gp">>>> </span><span class="n">price</span> <span class="o">=</span> <span class="mf">100.50</span>
|
||||
<span class="gp">>>> </span><span class="n">price</span> <span class="o">*</span> <span class="n">tax</span>
|
||||
<span class="go">12.5625</span>
|
||||
<span class="gp">>>> </span><span class="n">price</span> <span class="o">+</span> <span class="n">_</span>
|
||||
<span class="go">113.0625</span>
|
||||
<span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="go">113.06</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This variable should be treated as read-only by the user. Don’t explicitly
|
||||
assign a value to it — you would create an independent local variable with the
|
||||
same name masking the built-in variable with its magic behavior.</p>
|
||||
<p>In addition to <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">int</span></code></a> and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>, Python supports other types of
|
||||
numbers, such as <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> and <a class="reference internal" href="../library/fractions.html#fractions.Fraction" title="fractions.Fraction"><code class="xref py py-class docutils literal notranslate"><span class="pre">Fraction</span></code></a>.
|
||||
Python also has built-in support for <a class="reference internal" href="../library/stdtypes.html#typesnumeric"><span class="std std-ref">complex numbers</span></a>,
|
||||
and uses the <code class="docutils literal notranslate"><span class="pre">j</span></code> or <code class="docutils literal notranslate"><span class="pre">J</span></code> suffix to indicate the imaginary part
|
||||
(e.g. <code class="docutils literal notranslate"><span class="pre">3+5j</span></code>).</p>
|
||||
</section>
|
||||
<section id="text">
|
||||
<span id="tut-strings"></span><h3><span class="section-number">3.1.2. </span>Text<a class="headerlink" href="#text" title="Link to this heading">¶</a></h3>
|
||||
<p>Python can manipulate text (represented by type <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">str</span></code></a>, so-called
|
||||
“strings”) as well as numbers. This includes characters “<code class="docutils literal notranslate"><span class="pre">!</span></code>”, words
|
||||
“<code class="docutils literal notranslate"><span class="pre">rabbit</span></code>”, names “<code class="docutils literal notranslate"><span class="pre">Paris</span></code>”, sentences “<code class="docutils literal notranslate"><span class="pre">Got</span> <span class="pre">your</span> <span class="pre">back.</span></code>”, etc.
|
||||
“<code class="docutils literal notranslate"><span class="pre">Yay!</span> <span class="pre">:)</span></code>”. They can be enclosed in single quotes (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) or double
|
||||
quotes (<code class="docutils literal notranslate"><span class="pre">"..."</span></code>) with the same result <a class="footnote-reference brackets" href="#id4" id="id2" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a>.</p>
|
||||
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'spam eggs'</span> <span class="c1"># single quotes</span>
|
||||
<span class="go">'spam eggs'</span>
|
||||
<span class="gp">>>> </span><span class="s2">"Paris rabbit got your back :)! Yay!"</span> <span class="c1"># double quotes</span>
|
||||
<span class="go">'Paris rabbit got your back :)! Yay!'</span>
|
||||
<span class="gp">>>> </span><span class="s1">'1975'</span> <span class="c1"># digits and numerals enclosed in quotes are also strings</span>
|
||||
<span class="go">'1975'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>To quote a quote, we need to “escape” it, by preceding it with <code class="docutils literal notranslate"><span class="pre">\</span></code>.
|
||||
Alternatively, we can use the other type of quotation marks:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'doesn</span><span class="se">\'</span><span class="s1">t'</span> <span class="c1"># use \' to escape the single quote...</span>
|
||||
<span class="go">"doesn't"</span>
|
||||
<span class="gp">>>> </span><span class="s2">"doesn't"</span> <span class="c1"># ...or use double quotes instead</span>
|
||||
<span class="go">"doesn't"</span>
|
||||
<span class="gp">>>> </span><span class="s1">'"Yes," they said.'</span>
|
||||
<span class="go">'"Yes," they said.'</span>
|
||||
<span class="gp">>>> </span><span class="s2">"</span><span class="se">\"</span><span class="s2">Yes,</span><span class="se">\"</span><span class="s2"> they said."</span>
|
||||
<span class="go">'"Yes," they said.'</span>
|
||||
<span class="gp">>>> </span><span class="s1">'"Isn</span><span class="se">\'</span><span class="s1">t," they said.'</span>
|
||||
<span class="go">'"Isn\'t," they said.'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>In the Python shell, the string definition and output string can look
|
||||
different. The <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function produces a more readable output, by
|
||||
omitting the enclosing quotes and by printing escaped and special characters:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'First line.</span><span class="se">\n</span><span class="s1">Second line.'</span> <span class="c1"># \n means newline</span>
|
||||
<span class="gp">>>> </span><span class="n">s</span> <span class="c1"># without print(), special characters are included in the string</span>
|
||||
<span class="go">'First line.\nSecond line.'</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">s</span><span class="p">)</span> <span class="c1"># with print(), special characters are interpreted, so \n produces new line</span>
|
||||
<span class="go">First line.</span>
|
||||
<span class="go">Second line.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you don’t want characters prefaced by <code class="docutils literal notranslate"><span class="pre">\</span></code> to be interpreted as
|
||||
special characters, you can use <em>raw strings</em> by adding an <code class="docutils literal notranslate"><span class="pre">r</span></code> before
|
||||
the first quote:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'C:\some</span><span class="se">\n</span><span class="s1">ame'</span><span class="p">)</span> <span class="c1"># here \n means newline!</span>
|
||||
<span class="go">C:\some</span>
|
||||
<span class="go">ame</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="sa">r</span><span class="s1">'C:\some\name'</span><span class="p">)</span> <span class="c1"># note the r before the quote</span>
|
||||
<span class="go">C:\some\name</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>There is one subtle aspect to raw strings: a raw string may not end in
|
||||
an odd number of <code class="docutils literal notranslate"><span class="pre">\</span></code> characters; see
|
||||
<a class="reference internal" href="../faq/programming.html#faq-programming-raw-string-backslash"><span class="std std-ref">the FAQ entry</span></a> for more information
|
||||
and workarounds.</p>
|
||||
<p>String literals can span multiple lines. One way is using triple-quotes:
|
||||
<code class="docutils literal notranslate"><span class="pre">"""..."""</span></code> or <code class="docutils literal notranslate"><span class="pre">'''...'''</span></code>. End-of-line characters are automatically
|
||||
included in the string, but it’s possible to prevent this by adding a <code class="docutils literal notranslate"><span class="pre">\</span></code> at
|
||||
the end of the line. In the following example, the initial newline is not
|
||||
included:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s2">"""</span><span class="se">\</span>
|
||||
<span class="gp">... </span><span class="s2">Usage: thingy [OPTIONS]</span>
|
||||
<span class="gp">... </span><span class="s2"> -h Display this usage message</span>
|
||||
<span class="gp">... </span><span class="s2"> -H hostname Hostname to connect to</span>
|
||||
<span class="gp">... </span><span class="s2">"""</span><span class="p">)</span>
|
||||
<span class="go">Usage: thingy [OPTIONS]</span>
|
||||
<span class="go"> -h Display this usage message</span>
|
||||
<span class="go"> -H hostname Hostname to connect to</span>
|
||||
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Strings can be concatenated (glued together) with the <code class="docutils literal notranslate"><span class="pre">+</span></code> operator, and
|
||||
repeated with <code class="docutils literal notranslate"><span class="pre">*</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># 3 times 'un', followed by 'ium'</span>
|
||||
<span class="gp">>>> </span><span class="mi">3</span> <span class="o">*</span> <span class="s1">'un'</span> <span class="o">+</span> <span class="s1">'ium'</span>
|
||||
<span class="go">'unununium'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Two or more <em>string literals</em> (i.e. the ones enclosed between quotes) next
|
||||
to each other are automatically concatenated.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'Py'</span> <span class="s1">'thon'</span>
|
||||
<span class="go">'Python'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This feature is particularly useful when you want to break long strings:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">text</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'Put several strings within parentheses '</span>
|
||||
<span class="gp">... </span> <span class="s1">'to have them joined together.'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">text</span>
|
||||
<span class="go">'Put several strings within parentheses to have them joined together.'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This only works with two literals though, not with variables or expressions:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">prefix</span> <span class="o">=</span> <span class="s1">'Py'</span>
|
||||
<span class="gp">>>> </span><span class="n">prefix</span> <span class="s1">'thon'</span> <span class="c1"># can't concatenate a variable and a string literal</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>
|
||||
<span class="w"> </span><span class="n">prefix</span> <span class="s1">'thon'</span>
|
||||
<span class="w"> </span><span class="pm">^^^^^^</span>
|
||||
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
|
||||
<span class="gp">>>> </span><span class="p">(</span><span class="s1">'un'</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)</span> <span class="s1">'ium'</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>
|
||||
<span class="w"> </span><span class="p">(</span><span class="s1">'un'</span> <span class="o">*</span> <span class="mi">3</span><span class="p">)</span> <span class="s1">'ium'</span>
|
||||
<span class="w"> </span><span class="pm">^^^^^</span>
|
||||
<span class="gr">SyntaxError</span>: <span class="n">invalid syntax</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you want to concatenate variables or a variable and a literal, use <code class="docutils literal notranslate"><span class="pre">+</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">prefix</span> <span class="o">+</span> <span class="s1">'thon'</span>
|
||||
<span class="go">'Python'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Strings can be <em>indexed</em> (subscripted), with the first character having index 0.
|
||||
There is no separate character type; a character is simply a string of size
|
||||
one:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span> <span class="o">=</span> <span class="s1">'Python'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># character in position 0</span>
|
||||
<span class="go">'P'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">5</span><span class="p">]</span> <span class="c1"># character in position 5</span>
|
||||
<span class="go">'n'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Indices may also be negative numbers, to start counting from the right:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="c1"># last character</span>
|
||||
<span class="go">'n'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># second-last character</span>
|
||||
<span class="go">'o'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">6</span><span class="p">]</span>
|
||||
<span class="go">'P'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that since -0 is the same as 0, negative indices start from -1.</p>
|
||||
<p>In addition to indexing, <em>slicing</em> is also supported. While indexing is used
|
||||
to obtain individual characters, <em>slicing</em> allows you to obtain a substring:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># characters from position 0 (included) to 2 (excluded)</span>
|
||||
<span class="go">'Py'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="c1"># characters from position 2 (included) to 5 (excluded)</span>
|
||||
<span class="go">'tho'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Slice indices have useful defaults; an omitted first index defaults to zero, an
|
||||
omitted second index defaults to the size of the string being sliced.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="c1"># character from the beginning to position 2 (excluded)</span>
|
||||
<span class="go">'Py'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span> <span class="c1"># characters from position 4 (included) to the end</span>
|
||||
<span class="go">'on'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="o">-</span><span class="mi">2</span><span class="p">:]</span> <span class="c1"># characters from the second-last (included) to the end</span>
|
||||
<span class="go">'on'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note how the start is always included, and the end always excluded. This
|
||||
makes sure that <code class="docutils literal notranslate"><span class="pre">s[:i]</span> <span class="pre">+</span> <span class="pre">s[i:]</span></code> is always equal to <code class="docutils literal notranslate"><span class="pre">s</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span>
|
||||
<span class="go">'Python'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[:</span><span class="mi">4</span><span class="p">]</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:]</span>
|
||||
<span class="go">'Python'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>One way to remember how slices work is to think of the indices as pointing
|
||||
<em>between</em> characters, with the left edge of the first character numbered 0.
|
||||
Then the right edge of the last character of a string of <em>n</em> characters has
|
||||
index <em>n</em>, for example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span> <span class="o">+---+---+---+---+---+---+</span>
|
||||
<span class="o">|</span> <span class="n">P</span> <span class="o">|</span> <span class="n">y</span> <span class="o">|</span> <span class="n">t</span> <span class="o">|</span> <span class="n">h</span> <span class="o">|</span> <span class="n">o</span> <span class="o">|</span> <span class="n">n</span> <span class="o">|</span>
|
||||
<span class="o">+---+---+---+---+---+---+</span>
|
||||
<span class="mi">0</span> <span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span> <span class="mi">5</span> <span class="mi">6</span>
|
||||
<span class="o">-</span><span class="mi">6</span> <span class="o">-</span><span class="mi">5</span> <span class="o">-</span><span class="mi">4</span> <span class="o">-</span><span class="mi">3</span> <span class="o">-</span><span class="mi">2</span> <span class="o">-</span><span class="mi">1</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The first row of numbers gives the position of the indices 0…6 in the string;
|
||||
the second row gives the corresponding negative indices. The slice from <em>i</em> to
|
||||
<em>j</em> consists of all characters between the edges labeled <em>i</em> and <em>j</em>,
|
||||
respectively.</p>
|
||||
<p>For non-negative indices, the length of a slice is the difference of the
|
||||
indices, if both are within bounds. For example, the length of <code class="docutils literal notranslate"><span class="pre">word[1:3]</span></code> is
|
||||
2.</p>
|
||||
<p>Attempting to use an index that is too large will result in an error:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">]</span> <span class="c1"># the word only has 6 characters</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="gr">IndexError</span>: <span class="n">string index out of range</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>However, out of range slice indexes are handled gracefully when used for
|
||||
slicing:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">4</span><span class="p">:</span><span class="mi">42</span><span class="p">]</span>
|
||||
<span class="go">'on'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">42</span><span class="p">:]</span>
|
||||
<span class="go">''</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Python strings cannot be changed — they are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>.
|
||||
Therefore, assigning to an indexed position in the string results in an error:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'J'</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="gr">TypeError</span>: <span class="n">'str' object does not support item assignment</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[</span><span class="mi">2</span><span class="p">:]</span> <span class="o">=</span> <span class="s1">'py'</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="gr">TypeError</span>: <span class="n">'str' object does not support item assignment</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you need a different string, you should create a new one:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'J'</span> <span class="o">+</span> <span class="n">word</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
|
||||
<span class="go">'Jython'</span>
|
||||
<span class="gp">>>> </span><span class="n">word</span><span class="p">[:</span><span class="mi">2</span><span class="p">]</span> <span class="o">+</span> <span class="s1">'py'</span>
|
||||
<span class="go">'Pypy'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> returns the length of a string:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="s1">'supercalifragilisticexpialidocious'</span>
|
||||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">34</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="admonition seealso">
|
||||
<p class="admonition-title">See also</p>
|
||||
<dl class="simple">
|
||||
<dt><a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">Text Sequence Type — str</span></a></dt><dd><p>Strings are examples of <em>sequence types</em>, and support the common
|
||||
operations supported by such types.</p>
|
||||
</dd>
|
||||
<dt><a class="reference internal" href="../library/stdtypes.html#string-methods"><span class="std std-ref">String Methods</span></a></dt><dd><p>Strings support a large number of methods for
|
||||
basic transformations and searching.</p>
|
||||
</dd>
|
||||
<dt><a class="reference internal" href="../reference/lexical_analysis.html#f-strings"><span class="std std-ref">f-strings</span></a></dt><dd><p>String literals that have embedded expressions.</p>
|
||||
</dd>
|
||||
<dt><a class="reference internal" href="../library/string.html#formatstrings"><span class="std std-ref">Format String Syntax</span></a></dt><dd><p>Information about string formatting with <a class="reference internal" href="../library/stdtypes.html#str.format" title="str.format"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.format()</span></code></a>.</p>
|
||||
</dd>
|
||||
<dt><a class="reference internal" href="../library/stdtypes.html#old-string-formatting"><span class="std std-ref">printf-style String Formatting</span></a></dt><dd><p>The old formatting operations invoked when strings are
|
||||
the left operand of the <code class="docutils literal notranslate"><span class="pre">%</span></code> operator are described in more detail here.</p>
|
||||
</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</section>
|
||||
<section id="lists">
|
||||
<span id="tut-lists"></span><h3><span class="section-number">3.1.3. </span>Lists<a class="headerlink" href="#lists" title="Link to this heading">¶</a></h3>
|
||||
<p>Python knows a number of <em>compound</em> data types, used to group together other
|
||||
values. The most versatile is the <em>list</em>, which can be written as a list of
|
||||
comma-separated values (items) between square brackets. Lists might contain
|
||||
items of different types, but usually the items all have the same type.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">16</span><span class="p">,</span> <span class="mi">25</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">squares</span>
|
||||
<span class="go">[1, 4, 9, 16, 25]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Like strings (and all other built-in <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> types), lists can be
|
||||
indexed and sliced:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># indexing returns the item</span>
|
||||
<span class="go">1</span>
|
||||
<span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
|
||||
<span class="go">25</span>
|
||||
<span class="gp">>>> </span><span class="n">squares</span><span class="p">[</span><span class="o">-</span><span class="mi">3</span><span class="p">:]</span> <span class="c1"># slicing returns a new list</span>
|
||||
<span class="go">[9, 16, 25]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Lists also support operations like concatenation:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">squares</span> <span class="o">+</span> <span class="p">[</span><span class="mi">36</span><span class="p">,</span> <span class="mi">49</span><span class="p">,</span> <span class="mi">64</span><span class="p">,</span> <span class="mi">81</span><span class="p">,</span> <span class="mi">100</span><span class="p">]</span>
|
||||
<span class="go">[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Unlike strings, which are <a class="reference internal" href="../glossary.html#term-immutable"><span class="xref std std-term">immutable</span></a>, lists are a <a class="reference internal" href="../glossary.html#term-mutable"><span class="xref std std-term">mutable</span></a>
|
||||
type, i.e. it is possible to change their content:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">cubes</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">27</span><span class="p">,</span> <span class="mi">65</span><span class="p">,</span> <span class="mi">125</span><span class="p">]</span> <span class="c1"># something's wrong here</span>
|
||||
<span class="gp">>>> </span><span class="mi">4</span> <span class="o">**</span> <span class="mi">3</span> <span class="c1"># the cube of 4 is 64, not 65!</span>
|
||||
<span class="go">64</span>
|
||||
<span class="gp">>>> </span><span class="n">cubes</span><span class="p">[</span><span class="mi">3</span><span class="p">]</span> <span class="o">=</span> <span class="mi">64</span> <span class="c1"># replace the wrong value</span>
|
||||
<span class="gp">>>> </span><span class="n">cubes</span>
|
||||
<span class="go">[1, 8, 27, 64, 125]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>You can also add new items at the end of the list, by using
|
||||
the <code class="xref py py-meth docutils literal notranslate"><span class="pre">list.append()</span></code> <em>method</em> (we will see more about methods later):</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">216</span><span class="p">)</span> <span class="c1"># add the cube of 6</span>
|
||||
<span class="gp">>>> </span><span class="n">cubes</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="mi">7</span> <span class="o">**</span> <span class="mi">3</span><span class="p">)</span> <span class="c1"># and the cube of 7</span>
|
||||
<span class="gp">>>> </span><span class="n">cubes</span>
|
||||
<span class="go">[1, 8, 27, 64, 125, 216, 343]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Simple assignment in Python never copies data. When you assign a list
|
||||
to a variable, the variable refers to the <em>existing list</em>.
|
||||
Any changes you make to the list through one variable will be seen
|
||||
through all other variables that refer to it.:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">rgb</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"Red"</span><span class="p">,</span> <span class="s2">"Green"</span><span class="p">,</span> <span class="s2">"Blue"</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">rgba</span> <span class="o">=</span> <span class="n">rgb</span>
|
||||
<span class="gp">>>> </span><span class="nb">id</span><span class="p">(</span><span class="n">rgb</span><span class="p">)</span> <span class="o">==</span> <span class="nb">id</span><span class="p">(</span><span class="n">rgba</span><span class="p">)</span> <span class="c1"># they reference the same object</span>
|
||||
<span class="go">True</span>
|
||||
<span class="gp">>>> </span><span class="n">rgba</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"Alph"</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">rgb</span>
|
||||
<span class="go">["Red", "Green", "Blue", "Alph"]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>All slice operations return a new list containing the requested elements. This
|
||||
means that the following slice returns a
|
||||
<a class="reference internal" href="../library/copy.html#shallow-vs-deep-copy"><span class="std std-ref">shallow copy</span></a> of the list:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">correct_rgba</span> <span class="o">=</span> <span class="n">rgba</span><span class="p">[:]</span>
|
||||
<span class="gp">>>> </span><span class="n">correct_rgba</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Alpha"</span>
|
||||
<span class="gp">>>> </span><span class="n">correct_rgba</span>
|
||||
<span class="go">["Red", "Green", "Blue", "Alpha"]</span>
|
||||
<span class="gp">>>> </span><span class="n">rgba</span>
|
||||
<span class="go">["Red", "Green", "Blue", "Alph"]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Assignment to slices is also possible, and this can even change the size of the
|
||||
list or clear it entirely:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">,</span> <span class="s1">'e'</span><span class="p">,</span> <span class="s1">'f'</span><span class="p">,</span> <span class="s1">'g'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span>
|
||||
<span class="go">['a', 'b', 'c', 'd', 'e', 'f', 'g']</span>
|
||||
<span class="gp">>>> </span><span class="c1"># replace some values</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'C'</span><span class="p">,</span> <span class="s1">'D'</span><span class="p">,</span> <span class="s1">'E'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span>
|
||||
<span class="go">['a', 'b', 'C', 'D', 'E', 'f', 'g']</span>
|
||||
<span class="gp">>>> </span><span class="c1"># now remove them</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span><span class="p">[</span><span class="mi">2</span><span class="p">:</span><span class="mi">5</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span>
|
||||
<span class="go">['a', 'b', 'f', 'g']</span>
|
||||
<span class="gp">>>> </span><span class="c1"># clear the list by replacing all the elements with an empty list</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span><span class="p">[:]</span> <span class="o">=</span> <span class="p">[]</span>
|
||||
<span class="gp">>>> </span><span class="n">letters</span>
|
||||
<span class="go">[]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The built-in function <a class="reference internal" href="../library/functions.html#len" title="len"><code class="xref py py-func docutils literal notranslate"><span class="pre">len()</span></code></a> also applies to lists:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">letters</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">,</span> <span class="s1">'d'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">letters</span><span class="p">)</span>
|
||||
<span class="go">4</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>It is possible to nest lists (create lists containing other lists), for
|
||||
example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">,</span> <span class="s1">'c'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">n</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="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="p">[</span><span class="n">a</span><span class="p">,</span> <span class="n">n</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span>
|
||||
<span class="go">[['a', 'b', 'c'], [1, 2, 3]]</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
|
||||
<span class="go">['a', 'b', 'c']</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span>
|
||||
<span class="go">'b'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
<section id="first-steps-towards-programming">
|
||||
<span id="tut-firststeps"></span><h2><span class="section-number">3.2. </span>First Steps Towards Programming<a class="headerlink" href="#first-steps-towards-programming" title="Link to this heading">¶</a></h2>
|
||||
<p>Of course, we can use Python for more complicated tasks than adding two and two
|
||||
together. For instance, we can write an initial sub-sequence of the
|
||||
<a class="reference external" href="https://en.wikipedia.org/wiki/Fibonacci_sequence">Fibonacci series</a>
|
||||
as follows:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># Fibonacci series:</span>
|
||||
<span class="gp">>>> </span><span class="c1"># the sum of two elements defines the next</span>
|
||||
<span class="gp">>>> </span><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>
|
||||
<span class="gp">>>> </span><span class="k">while</span> <span class="n">a</span> <span class="o"><</span> <span class="mi">10</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <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>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">0</span>
|
||||
<span class="go">1</span>
|
||||
<span class="go">1</span>
|
||||
<span class="go">2</span>
|
||||
<span class="go">3</span>
|
||||
<span class="go">5</span>
|
||||
<span class="go">8</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This example introduces several new features.</p>
|
||||
<ul>
|
||||
<li><p>The first line contains a <em>multiple assignment</em>: the variables <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code>
|
||||
simultaneously get the new values 0 and 1. On the last line this is used again,
|
||||
demonstrating that the expressions on the right-hand side are all evaluated
|
||||
first before any of the assignments take place. The right-hand side expressions
|
||||
are evaluated from the left to the right.</p></li>
|
||||
<li><p>The <a class="reference internal" href="../reference/compound_stmts.html#while"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">while</span></code></a> loop executes as long as the condition (here: <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre"><</span> <span class="pre">10</span></code>)
|
||||
remains true. In Python, like in C, any non-zero integer value is true; zero is
|
||||
false. The condition may also be a string or list value, in fact any sequence;
|
||||
anything with a non-zero length is true, empty sequences are false. The test
|
||||
used in the example is a simple comparison. The standard comparison operators
|
||||
are written the same as in C: <code class="docutils literal notranslate"><span class="pre"><</span></code> (less than), <code class="docutils literal notranslate"><span class="pre">></span></code> (greater than), <code class="docutils literal notranslate"><span class="pre">==</span></code>
|
||||
(equal to), <code class="docutils literal notranslate"><span class="pre"><=</span></code> (less than or equal to), <code class="docutils literal notranslate"><span class="pre">>=</span></code> (greater than or equal to)
|
||||
and <code class="docutils literal notranslate"><span class="pre">!=</span></code> (not equal to).</p></li>
|
||||
<li><p>The <em>body</em> of the loop is <em>indented</em>: indentation is Python’s way of grouping
|
||||
statements. At the interactive prompt, you have to type a tab or space(s) for
|
||||
each indented line. In practice you will prepare more complicated input
|
||||
for Python with a text editor; all decent text editors have an auto-indent
|
||||
facility. When a compound statement is entered interactively, it must be
|
||||
followed by a blank line to indicate completion (since the parser cannot
|
||||
guess when you have typed the last line). Note that each line within a basic
|
||||
block must be indented by the same amount.</p></li>
|
||||
<li><p>The <a class="reference internal" href="../library/functions.html#print" title="print"><code class="xref py py-func docutils literal notranslate"><span class="pre">print()</span></code></a> function writes the value of the argument(s) it is given.
|
||||
It differs from just writing the expression you want to write (as we did
|
||||
earlier in the calculator examples) in the way it handles multiple arguments,
|
||||
floating-point quantities, and strings. Strings are printed without quotes,
|
||||
and a space is inserted between items, so you can format things nicely, like
|
||||
this:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">i</span> <span class="o">=</span> <span class="mi">256</span><span class="o">*</span><span class="mi">256</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s1">'The value of i is'</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span>
|
||||
<span class="go">The value of i is 65536</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The keyword argument <em>end</em> can be used to avoid the newline after the output,
|
||||
or end the output with a different string:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><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>
|
||||
<span class="gp">>>> </span><span class="k">while</span> <span class="n">a</span> <span class="o"><</span> <span class="mi">1000</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <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">','</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <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>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p class="rubric">Footnotes</p>
|
||||
<aside class="footnote-list brackets">
|
||||
<aside class="footnote brackets" id="id3" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>Since <code class="docutils literal notranslate"><span class="pre">**</span></code> has higher precedence than <code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">-3**2</span></code> will be
|
||||
interpreted as <code class="docutils literal notranslate"><span class="pre">-(3**2)</span></code> and thus result in <code class="docutils literal notranslate"><span class="pre">-9</span></code>. To avoid this
|
||||
and get <code class="docutils literal notranslate"><span class="pre">9</span></code>, you can use <code class="docutils literal notranslate"><span class="pre">(-3)**2</span></code>.</p>
|
||||
</aside>
|
||||
<aside class="footnote brackets" id="id4" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id2">2</a><span class="fn-bracket">]</span></span>
|
||||
<p>Unlike other languages, special characters such as <code class="docutils literal notranslate"><span class="pre">\n</span></code> have the
|
||||
same meaning with both single (<code class="docutils literal notranslate"><span class="pre">'...'</span></code>) and double (<code class="docutils literal notranslate"><span class="pre">"..."</span></code>) quotes.
|
||||
The only difference between the two is that within single quotes you don’t
|
||||
need to escape <code class="docutils literal notranslate"><span class="pre">"</span></code> (but you have to escape <code class="docutils literal notranslate"><span class="pre">\'</span></code>) and vice versa.</p>
|
||||
</aside>
|
||||
</aside>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">3. An Informal Introduction to Python</a><ul>
|
||||
<li><a class="reference internal" href="#using-python-as-a-calculator">3.1. Using Python as a Calculator</a><ul>
|
||||
<li><a class="reference internal" href="#numbers">3.1.1. Numbers</a></li>
|
||||
<li><a class="reference internal" href="#text">3.1.2. Text</a></li>
|
||||
<li><a class="reference internal" href="#lists">3.1.3. Lists</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#first-steps-towards-programming">3.2. First Steps Towards Programming</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="interpreter.html"
|
||||
title="previous chapter"><span class="section-number">2. </span>Using the Python Interpreter</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="controlflow.html"
|
||||
title="next chapter"><span class="section-number">4. </span>More Control Flow Tools</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/introduction.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="controlflow.html" title="4. More Control Flow Tools"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interpreter.html" title="2. Using the Python Interpreter"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>An Informal Introduction to Python</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
879
Dependencies/Python/Doc/html/tutorial/modules.html
vendored
Normal file
879
Dependencies/Python/Doc/html/tutorial/modules.html
vendored
Normal file
@@ -0,0 +1,879 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="6. Modules" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/modules.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<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..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<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..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>6. Modules — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="7. Input and Output" href="inputoutput.html" />
|
||||
<link rel="prev" title="5. Data Structures" href="datastructures.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/modules.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">6. Modules</a><ul>
|
||||
<li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
|
||||
<li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
|
||||
<li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
|
||||
<li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
|
||||
<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>
|
||||
<li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
|
||||
<li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
|
||||
<li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
|
||||
<li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="datastructures.html"
|
||||
title="previous chapter"><span class="section-number">5. </span>Data Structures</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="inputoutput.html"
|
||||
title="next chapter"><span class="section-number">7. </span>Input and Output</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/modules.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="inputoutput.html" title="7. Input and Output"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="datastructures.html" title="5. Data Structures"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Modules</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="modules">
|
||||
<span id="tut-modules"></span><h1><span class="section-number">6. </span>Modules<a class="headerlink" href="#modules" title="Link to this heading">¶</a></h1>
|
||||
<p>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 better off using a text editor to prepare the
|
||||
input for the interpreter and running it with that file as input instead. This
|
||||
is known as creating a <em>script</em>. As your program gets longer, you may want to
|
||||
split it into several files for easier maintenance. You may also want to use a
|
||||
handy function that you’ve written in several programs without copying its
|
||||
definition into each program.</p>
|
||||
<p>To support this, Python has a way to put definitions in a file and use them in a
|
||||
script or in an interactive instance of the interpreter. Such a file is called a
|
||||
<em>module</em>; definitions from a module can be <em>imported</em> into other modules or into
|
||||
the <em>main</em> module (the collection of variables that you have access to in a
|
||||
script executed at the top level and in calculator mode).</p>
|
||||
<p>A module is a file containing Python definitions and statements. The file name
|
||||
is the module name with the suffix <code class="file docutils literal notranslate"><span class="pre">.py</span></code> appended. Within a module, the
|
||||
module’s name (as a string) is available as the value of the global variable
|
||||
<code class="docutils literal notranslate"><span class="pre">__name__</span></code>. For instance, use your favorite text editor to create a file
|
||||
called <code class="file docutils literal notranslate"><span class="pre">fibo.py</span></code> in the current directory with the following contents:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Fibonacci numbers module</span>
|
||||
|
||||
<span class="k">def</span><span class="w"> </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>
|
||||
<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>
|
||||
<span class="k">while</span> <span class="n">a</span> <span class="o"><</span> <span class="n">n</span><span class="p">:</span>
|
||||
<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">' '</span><span class="p">)</span>
|
||||
<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>
|
||||
<span class="nb">print</span><span class="p">()</span>
|
||||
|
||||
<span class="k">def</span><span class="w"> </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>
|
||||
<span class="n">result</span> <span class="o">=</span> <span class="p">[]</span>
|
||||
<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>
|
||||
<span class="k">while</span> <span class="n">a</span> <span class="o"><</span> <span class="n">n</span><span class="p">:</span>
|
||||
<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>
|
||||
<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>
|
||||
<span class="k">return</span> <span class="n">result</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Now enter the Python interpreter and import this module with the following
|
||||
command:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">fibo</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
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);
|
||||
it only adds the module name <code class="docutils literal notranslate"><span class="pre">fibo</span></code> there. Using
|
||||
the module name you can access the functions:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987</span>
|
||||
<span class="gp">>>> </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>
|
||||
<span class="go">[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]</span>
|
||||
<span class="gp">>>> </span><span class="n">fibo</span><span class="o">.</span><span class="vm">__name__</span>
|
||||
<span class="go">'fibo'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you intend to use a function often you can assign it to a local name:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
|
||||
<span class="gp">>>> </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<section id="more-on-modules">
|
||||
<span id="tut-moremodules"></span><h2><span class="section-number">6.1. </span>More on Modules<a class="headerlink" href="#more-on-modules" title="Link to this heading">¶</a></h2>
|
||||
<p>A module can contain executable statements as well as function definitions.
|
||||
These statements are intended to initialize the module. They are executed only
|
||||
the <em>first</em> time the module name is encountered in an import statement. <a class="footnote-reference brackets" href="#id3" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>
|
||||
(They are also run if the file is executed as a script.)</p>
|
||||
<p>Each module has its own private namespace, which is used as the global namespace
|
||||
by all functions defined in the module. Thus, the author of a module can
|
||||
use global variables in the module without worrying about accidental clashes
|
||||
with a user’s global variables. On the other hand, if you know what you are
|
||||
doing you can touch a module’s global variables with the same notation used to
|
||||
refer to its functions, <code class="docutils literal notranslate"><span class="pre">modname.itemname</span></code>.</p>
|
||||
<p>Modules can import other modules. It is customary but not required to place all
|
||||
<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
|
||||
matter). The imported module names, if placed at the top level of a module
|
||||
(outside any functions or classes), are added to the module’s global namespace.</p>
|
||||
<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
|
||||
module directly into the importing module’s namespace. For example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">fibo</span><span class="w"> </span><span class="kn">import</span> <span class="n">fib</span><span class="p">,</span> <span class="n">fib2</span>
|
||||
<span class="gp">>>> </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This does not introduce the module name from which the imports are taken in the
|
||||
local namespace (so in the example, <code class="docutils literal notranslate"><span class="pre">fibo</span></code> is not defined).</p>
|
||||
<p>There is even a variant to import all names that a module defines:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">fibo</span><span class="w"> </span><span class="kn">import</span> <span class="o">*</span>
|
||||
<span class="gp">>>> </span><span class="n">fib</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This imports all names except those beginning with an underscore (<code class="docutils literal notranslate"><span class="pre">_</span></code>).
|
||||
In most cases Python programmers do not use this facility since it introduces
|
||||
an unknown set of names into the interpreter, possibly hiding some things
|
||||
you have already defined.</p>
|
||||
<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
|
||||
frowned upon, since it often causes poorly readable code. However, it is okay to
|
||||
use it to save typing in interactive sessions.</p>
|
||||
<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
|
||||
following <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> is bound directly to the imported module.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">fibo</span><span class="w"> </span><span class="k">as</span><span class="w"> </span><span class="nn">fib</span>
|
||||
<span class="gp">>>> </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>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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>
|
||||
will do, with the only difference of it being available as <code class="docutils literal notranslate"><span class="pre">fib</span></code>.</p>
|
||||
<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>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">fibo</span><span class="w"> </span><span class="kn">import</span> <span class="n">fib</span> <span class="k">as</span> <span class="n">fibonacci</span>
|
||||
<span class="gp">>>> </span><span class="n">fibonacci</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34 55 89 144 233 377</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="admonition note">
|
||||
<p class="admonition-title">Note</p>
|
||||
<p>For efficiency reasons, each module is only imported once per interpreter
|
||||
session. Therefore, if you change your modules, you must restart the
|
||||
interpreter – or, if it’s just one module you want to test interactively,
|
||||
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>
|
||||
<span class="pre">importlib.reload(modulename)</span></code>.</p>
|
||||
</div>
|
||||
<section id="executing-modules-as-scripts">
|
||||
<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="Link to this heading">¶</a></h3>
|
||||
<p>When you run a Python module with</p>
|
||||
<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"><</span><span class="n">arguments</span><span class="o">></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>the code in the module will be executed, just as if you imported it, but with
|
||||
the <code class="docutils literal notranslate"><span class="pre">__name__</span></code> set to <code class="docutils literal notranslate"><span class="pre">"__main__"</span></code>. That means that by adding this code at
|
||||
the end of your module:</p>
|
||||
<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">"__main__"</span><span class="p">:</span>
|
||||
<span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
|
||||
<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>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>you can make the file usable as a script as well as an importable module,
|
||||
because the code that parses the command line only runs if the module is
|
||||
executed as the “main” file:</p>
|
||||
<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>
|
||||
<span class="go">0 1 1 2 3 5 8 13 21 34</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If the module is imported, the code is not run:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">fibo</span>
|
||||
<span class="gp">>>></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This is often used either to provide a convenient user interface to a module, or
|
||||
for testing purposes (running the module as a script executes a test suite).</p>
|
||||
</section>
|
||||
<section id="the-module-search-path">
|
||||
<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="Link to this heading">¶</a></h3>
|
||||
<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
|
||||
a built-in module with that name. These module names are listed in
|
||||
<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
|
||||
named <code class="file docutils literal notranslate"><span class="pre">spam.py</span></code> in a list of directories given by the variable
|
||||
<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>
|
||||
<ul class="simple">
|
||||
<li><p>The directory containing the input script (or the current directory when no
|
||||
file is specified).</p></li>
|
||||
<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
|
||||
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>
|
||||
<li><p>The installation-dependent default (by convention including a
|
||||
<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>
|
||||
</ul>
|
||||
<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>
|
||||
<div class="admonition note">
|
||||
<p class="admonition-title">Note</p>
|
||||
<p>On file systems which support symlinks, the directory containing the input
|
||||
script is calculated after the symlink is followed. In other words the
|
||||
directory containing the symlink is <strong>not</strong> added to the module search path.</p>
|
||||
</div>
|
||||
<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
|
||||
directory containing the script being run is placed at the beginning of the
|
||||
search path, ahead of the standard library path. This means that scripts in that
|
||||
directory will be loaded instead of modules of the same name in the library
|
||||
directory. This is an error unless the replacement is intended. See section
|
||||
<a class="reference internal" href="#tut-standardmodules"><span class="std std-ref">Standard Modules</span></a> for more information.</p>
|
||||
</section>
|
||||
<section id="compiled-python-files">
|
||||
<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="Link to this heading">¶</a></h3>
|
||||
<p>To speed up loading modules, Python caches the compiled version of each module
|
||||
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>,
|
||||
where the version encodes the format of the compiled file; it generally contains
|
||||
the Python version number. For example, in CPython release 3.3 the compiled
|
||||
version of spam.py would be cached as <code class="docutils literal notranslate"><span class="pre">__pycache__/spam.cpython-33.pyc</span></code>. This
|
||||
naming convention allows compiled modules from different releases and different
|
||||
versions of Python to coexist.</p>
|
||||
<p>Python checks the modification date of the source against the compiled version
|
||||
to see if it’s out of date and needs to be recompiled. This is a completely
|
||||
automatic process. Also, the compiled modules are platform-independent, so the
|
||||
same library can be shared among systems with different architectures.</p>
|
||||
<p>Python does not check the cache in two circumstances. First, it always
|
||||
recompiles and does not store the result for the module that’s loaded directly
|
||||
from the command line. Second, it does not check the cache if there is no
|
||||
source module. To support a non-source (compiled only) distribution, the
|
||||
compiled module must be in the source directory, and there must not be a source
|
||||
module.</p>
|
||||
<p>Some tips for experts:</p>
|
||||
<ul class="simple">
|
||||
<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
|
||||
to reduce the size of a compiled module. The <code class="docutils literal notranslate"><span class="pre">-O</span></code> switch removes assert
|
||||
statements, the <code class="docutils literal notranslate"><span class="pre">-OO</span></code> switch removes both assert statements and __doc__
|
||||
strings. Since some programs may rely on having these available, you should
|
||||
only use this option if you know what you’re doing. “Optimized” modules have
|
||||
an <code class="docutils literal notranslate"><span class="pre">opt-</span></code> tag and are usually smaller. Future releases may
|
||||
change the effects of optimization.</p></li>
|
||||
<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>
|
||||
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
|
||||
about <code class="docutils literal notranslate"><span class="pre">.pyc</span></code> files is the speed with which they are loaded.</p></li>
|
||||
<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
|
||||
directory.</p></li>
|
||||
<li><p>There is more detail on this process, including a flow chart of the
|
||||
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>
|
||||
</ul>
|
||||
</section>
|
||||
</section>
|
||||
<section id="standard-modules">
|
||||
<span id="tut-standardmodules"></span><h2><span class="section-number">6.2. </span>Standard Modules<a class="headerlink" href="#standard-modules" title="Link to this heading">¶</a></h2>
|
||||
<p id="index-4">Python comes with a library of standard modules, described in a separate
|
||||
document, the Python Library Reference (“Library Reference” hereafter). Some
|
||||
modules are built into the interpreter; these provide access to operations that
|
||||
are not part of the core of the language but are nevertheless built in, either
|
||||
for efficiency or to provide access to operating system primitives such as
|
||||
system calls. The set of such modules is a configuration option which also
|
||||
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
|
||||
provided on Windows systems. One particular module deserves some attention:
|
||||
<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
|
||||
<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
|
||||
prompts:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
|
||||
<span class="gp">>>> </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span>
|
||||
<span class="go">'>>> '</span>
|
||||
<span class="gp">>>> </span><span class="n">sys</span><span class="o">.</span><span class="n">ps2</span>
|
||||
<span class="go">'... '</span>
|
||||
<span class="gp">>>> </span><span class="n">sys</span><span class="o">.</span><span class="n">ps1</span> <span class="o">=</span> <span class="s1">'C> '</span>
|
||||
<span class="go">C> print('Yuck!')</span>
|
||||
<span class="go">Yuck!</span>
|
||||
<span class="go">C></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>These two variables are only defined if the interpreter is in interactive mode.</p>
|
||||
<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
|
||||
search path for modules. It is initialized to a default path taken from the
|
||||
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
|
||||
<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
|
||||
operations:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
|
||||
<span class="gp">>>> </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">'/ufs/guido/lib/python'</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="the-dir-function">
|
||||
<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="Link to this heading">¶</a></h2>
|
||||
<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
|
||||
defines. It returns a sorted list of strings:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">fibo</span><span class="o">,</span><span class="w"> </span><span class="nn">sys</span>
|
||||
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">fibo</span><span class="p">)</span>
|
||||
<span class="go">['__name__', 'fib', 'fib2']</span>
|
||||
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">sys</span><span class="p">)</span>
|
||||
<span class="go">['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',</span>
|
||||
<span class="go"> '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',</span>
|
||||
<span class="go"> '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',</span>
|
||||
<span class="go"> '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',</span>
|
||||
<span class="go"> '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',</span>
|
||||
<span class="go"> 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',</span>
|
||||
<span class="go"> 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',</span>
|
||||
<span class="go"> 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',</span>
|
||||
<span class="go"> 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',</span>
|
||||
<span class="go"> 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',</span>
|
||||
<span class="go"> 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',</span>
|
||||
<span class="go"> 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',</span>
|
||||
<span class="go"> 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',</span>
|
||||
<span class="go"> 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',</span>
|
||||
<span class="go"> 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',</span>
|
||||
<span class="go"> 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',</span>
|
||||
<span class="go"> 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',</span>
|
||||
<span class="go"> 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',</span>
|
||||
<span class="go"> 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',</span>
|
||||
<span class="go"> 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',</span>
|
||||
<span class="go"> 'warnoptions']</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </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>
|
||||
<span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">fibo</span>
|
||||
<span class="gp">>>> </span><span class="n">fib</span> <span class="o">=</span> <span class="n">fibo</span><span class="o">.</span><span class="n">fib</span>
|
||||
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">()</span>
|
||||
<span class="go">['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that it lists all types of names: variables, modules, functions, etc.</p>
|
||||
<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
|
||||
want a list of those, they are defined in the standard module
|
||||
<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>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">builtins</span>
|
||||
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">builtins</span><span class="p">)</span>
|
||||
<span class="go">['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',</span>
|
||||
<span class="go"> 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',</span>
|
||||
<span class="go"> 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',</span>
|
||||
<span class="go"> 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',</span>
|
||||
<span class="go"> 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',</span>
|
||||
<span class="go"> 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',</span>
|
||||
<span class="go"> 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',</span>
|
||||
<span class="go"> 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',</span>
|
||||
<span class="go"> 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',</span>
|
||||
<span class="go"> 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',</span>
|
||||
<span class="go"> 'NotImplementedError', 'OSError', 'OverflowError',</span>
|
||||
<span class="go"> 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',</span>
|
||||
<span class="go"> 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',</span>
|
||||
<span class="go"> 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',</span>
|
||||
<span class="go"> 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',</span>
|
||||
<span class="go"> 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',</span>
|
||||
<span class="go"> 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',</span>
|
||||
<span class="go"> 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',</span>
|
||||
<span class="go"> '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',</span>
|
||||
<span class="go"> 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',</span>
|
||||
<span class="go"> 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',</span>
|
||||
<span class="go"> 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',</span>
|
||||
<span class="go"> 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',</span>
|
||||
<span class="go"> 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',</span>
|
||||
<span class="go"> 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',</span>
|
||||
<span class="go"> 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',</span>
|
||||
<span class="go"> 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',</span>
|
||||
<span class="go"> 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',</span>
|
||||
<span class="go"> 'zip']</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="packages">
|
||||
<span id="tut-packages"></span><h2><span class="section-number">6.4. </span>Packages<a class="headerlink" href="#packages" title="Link to this heading">¶</a></h2>
|
||||
<p>Packages are a way of structuring Python’s module namespace by using “dotted
|
||||
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
|
||||
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
|
||||
authors of different modules from having to worry about each other’s global
|
||||
variable names, the use of dotted module names saves the authors of multi-module
|
||||
packages like NumPy or Pillow from having to worry about
|
||||
each other’s module names.</p>
|
||||
<p>Suppose you want to design a collection of modules (a “package”) for the uniform
|
||||
handling of sound files and sound data. There are many different sound file
|
||||
formats (usually recognized by their extension, for example: <code class="file docutils literal notranslate"><span class="pre">.wav</span></code>,
|
||||
<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
|
||||
collection of modules for the conversion between the various file formats.
|
||||
There are also many different operations you might want to perform on sound data
|
||||
(such as mixing, adding echo, applying an equalizer function, creating an
|
||||
artificial stereo effect), so in addition you will be writing a never-ending
|
||||
stream of modules to perform these operations. Here’s a possible structure for
|
||||
your package (expressed in terms of a hierarchical filesystem):</p>
|
||||
<div class="highlight-text notranslate"><div class="highlight"><pre><span></span>sound/ Top-level package
|
||||
__init__.py Initialize the sound package
|
||||
formats/ Subpackage for file format conversions
|
||||
__init__.py
|
||||
wavread.py
|
||||
wavwrite.py
|
||||
aiffread.py
|
||||
aiffwrite.py
|
||||
auread.py
|
||||
auwrite.py
|
||||
...
|
||||
effects/ Subpackage for sound effects
|
||||
__init__.py
|
||||
echo.py
|
||||
surround.py
|
||||
reverse.py
|
||||
...
|
||||
filters/ Subpackage for filters
|
||||
__init__.py
|
||||
equalizer.py
|
||||
vocoder.py
|
||||
karaoke.py
|
||||
...
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>When importing the package, Python searches through the directories on
|
||||
<code class="docutils literal notranslate"><span class="pre">sys.path</span></code> looking for the package subdirectory.</p>
|
||||
<p>The <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> files are required to make Python treat directories
|
||||
containing the file as packages (unless using a <a class="reference internal" href="../glossary.html#term-namespace-package"><span class="xref std std-term">namespace package</span></a>, a
|
||||
relatively advanced feature). This prevents directories with a common name,
|
||||
such as <code class="docutils literal notranslate"><span class="pre">string</span></code>, from unintentionally hiding valid modules that occur later
|
||||
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
|
||||
an empty file, but it can also execute initialization code for the package or
|
||||
set the <code class="docutils literal notranslate"><span class="pre">__all__</span></code> variable, described later.</p>
|
||||
<p>Users of the package can import individual modules from the package, for
|
||||
example:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">sound.effects.echo</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
its full name.</p>
|
||||
<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>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>An alternative way of importing the submodule is:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">sound.effects</span><span class="w"> </span><span class="kn">import</span> <span class="n">echo</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
package prefix, so it can be used as follows:</p>
|
||||
<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>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Yet another variation is to import the desired function or variable directly:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">sound.effects.echo</span><span class="w"> </span><span class="kn">import</span> <span class="n">echofilter</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
<code class="xref py py-func docutils literal notranslate"><span class="pre">echofilter()</span></code> directly available:</p>
|
||||
<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>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
submodule (or subpackage) of the package, or some other name defined in the
|
||||
package, like a function, class or variable. The <code class="docutils literal notranslate"><span class="pre">import</span></code> statement first
|
||||
tests whether the item is defined in the package; if not, it assumes it is a
|
||||
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>
|
||||
exception is raised.</p>
|
||||
<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
|
||||
except for the last must be a package; the last item can be a module or a
|
||||
package but can’t be a class or function or variable defined in the previous
|
||||
item.</p>
|
||||
<section id="importing-from-a-package">
|
||||
<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="Link to this heading">¶</a></h3>
|
||||
<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,
|
||||
one would hope that this somehow goes out to the filesystem, finds which
|
||||
submodules are present in the package, and imports them all. This could take a
|
||||
long time and importing sub-modules might have unwanted side-effects that should
|
||||
only happen when the sub-module is explicitly imported.</p>
|
||||
<p>The only solution is for the package author to provide an explicit index of the
|
||||
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
|
||||
<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
|
||||
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
|
||||
encountered. It is up to the package author to keep this list up-to-date when a
|
||||
new version of the package is released. Package authors may also decide not to
|
||||
support it, if they don’t see a use for importing * from their package. For
|
||||
example, the file <code class="file docutils literal notranslate"><span class="pre">sound/effects/__init__.py</span></code> could contain the following
|
||||
code:</p>
|
||||
<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">"echo"</span><span class="p">,</span> <span class="s2">"surround"</span><span class="p">,</span> <span class="s2">"reverse"</span><span class="p">]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
named submodules of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">sound.effects</span></code> package.</p>
|
||||
<p>Be aware that submodules might become shadowed by locally defined names. For
|
||||
example, if you added a <code class="docutils literal notranslate"><span class="pre">reverse</span></code> function to the
|
||||
<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>
|
||||
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
|
||||
<code class="docutils literal notranslate"><span class="pre">reverse</span></code> submodule, because it is shadowed by the locally defined
|
||||
<code class="docutils literal notranslate"><span class="pre">reverse</span></code> function:</p>
|
||||
<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">"echo"</span><span class="p">,</span> <span class="c1"># refers to the 'echo.py' file</span>
|
||||
<span class="s2">"surround"</span><span class="p">,</span> <span class="c1"># refers to the 'surround.py' file</span>
|
||||
<span class="s2">"reverse"</span><span class="p">,</span> <span class="c1"># !!! refers to the 'reverse' function now !!!</span>
|
||||
<span class="p">]</span>
|
||||
|
||||
<span class="k">def</span><span class="w"> </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"># <-- this name shadows the 'reverse.py' submodule</span>
|
||||
<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 'from sound.effects import *'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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>
|
||||
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
|
||||
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
|
||||
been imported (possibly running any initialization code in <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>)
|
||||
and then imports whatever names are defined in the package. This includes any
|
||||
names defined (and submodules explicitly loaded) by <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code>. It
|
||||
also includes any submodules of the package that were explicitly loaded by
|
||||
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>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">sound.effects.echo</span>
|
||||
<span class="kn">import</span><span class="w"> </span><span class="nn">sound.effects.surround</span>
|
||||
<span class="kn">from</span><span class="w"> </span><span class="nn">sound.effects</span><span class="w"> </span><span class="kn">import</span> <span class="o">*</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<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
|
||||
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
|
||||
when the <code class="docutils literal notranslate"><span class="pre">from...import</span></code> statement is executed. (This also works when
|
||||
<code class="docutils literal notranslate"><span class="pre">__all__</span></code> is defined.)</p>
|
||||
<p>Although certain modules are designed to export only names that follow certain
|
||||
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
|
||||
production code.</p>
|
||||
<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>
|
||||
<span class="pre">specific_submodule</span></code>! In fact, this is the recommended notation unless the
|
||||
importing module needs to use submodules with the same name from different
|
||||
packages.</p>
|
||||
</section>
|
||||
<section id="intra-package-references">
|
||||
<span id="id2"></span><h3><span class="section-number">6.4.2. </span>Intra-package References<a class="headerlink" href="#intra-package-references" title="Link to this heading">¶</a></h3>
|
||||
<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
|
||||
in the example), you can use absolute imports to refer to submodules of siblings
|
||||
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
|
||||
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>
|
||||
<span class="pre">sound.effects</span> <span class="pre">import</span> <span class="pre">echo</span></code>.</p>
|
||||
<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
|
||||
of import statement. These imports use leading dots to indicate the current and
|
||||
parent packages involved in the relative import. From the <code class="xref py py-mod docutils literal notranslate"><span class="pre">surround</span></code>
|
||||
module for example, you might use:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span><span class="w"> </span><span class="nn">.</span><span class="w"> </span><span class="kn">import</span> <span class="n">echo</span>
|
||||
<span class="kn">from</span><span class="w"> </span><span class="nn">..</span><span class="w"> </span><span class="kn">import</span> <span class="n">formats</span>
|
||||
<span class="kn">from</span><span class="w"> </span><span class="nn">..filters</span><span class="w"> </span><span class="kn">import</span> <span class="n">equalizer</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Note that relative imports are based on the name of the current module. Since
|
||||
the name of the main module is always <code class="docutils literal notranslate"><span class="pre">"__main__"</span></code>, modules intended for use
|
||||
as the main module of a Python application must always use absolute imports.</p>
|
||||
</section>
|
||||
<section id="packages-in-multiple-directories">
|
||||
<h3><span class="section-number">6.4.3. </span>Packages in Multiple Directories<a class="headerlink" href="#packages-in-multiple-directories" title="Link to this heading">¶</a></h3>
|
||||
<p>Packages support one more special attribute, <a class="reference internal" href="../reference/datamodel.html#module.__path__" title="module.__path__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code></a>. This is
|
||||
initialized to be a <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> of strings containing the name of the
|
||||
directory holding the
|
||||
package’s <code class="file docutils literal notranslate"><span class="pre">__init__.py</span></code> before the code in that file is executed. This
|
||||
variable can be modified; doing so affects future searches for modules and
|
||||
subpackages contained in the package.</p>
|
||||
<p>While this feature is not often needed, it can be used to extend the set of
|
||||
modules found in a package.</p>
|
||||
<p class="rubric">Footnotes</p>
|
||||
<aside class="footnote-list brackets">
|
||||
<aside class="footnote brackets" id="id3" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>In fact function definitions are also ‘statements’ that are ‘executed’; the
|
||||
execution of a module-level function definition adds the function name to
|
||||
the module’s global namespace.</p>
|
||||
</aside>
|
||||
</aside>
|
||||
</section>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">6. Modules</a><ul>
|
||||
<li><a class="reference internal" href="#more-on-modules">6.1. More on Modules</a><ul>
|
||||
<li><a class="reference internal" href="#executing-modules-as-scripts">6.1.1. Executing modules as scripts</a></li>
|
||||
<li><a class="reference internal" href="#the-module-search-path">6.1.2. The Module Search Path</a></li>
|
||||
<li><a class="reference internal" href="#compiled-python-files">6.1.3. “Compiled” Python files</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><a class="reference internal" href="#standard-modules">6.2. Standard Modules</a></li>
|
||||
<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>
|
||||
<li><a class="reference internal" href="#packages">6.4. Packages</a><ul>
|
||||
<li><a class="reference internal" href="#importing-from-a-package">6.4.1. Importing * From a Package</a></li>
|
||||
<li><a class="reference internal" href="#intra-package-references">6.4.2. Intra-package References</a></li>
|
||||
<li><a class="reference internal" href="#packages-in-multiple-directories">6.4.3. Packages in Multiple Directories</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="datastructures.html"
|
||||
title="previous chapter"><span class="section-number">5. </span>Data Structures</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="inputoutput.html"
|
||||
title="next chapter"><span class="section-number">7. </span>Input and Output</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/modules.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="inputoutput.html" title="7. Input and Output"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="datastructures.html" title="5. Data Structures"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">6. </span>Modules</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
657
Dependencies/Python/Doc/html/tutorial/stdlib.html
vendored
Normal file
657
Dependencies/Python/Doc/html/tutorial/stdlib.html
vendored
Normal file
@@ -0,0 +1,657 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="10. Brief Tour of the Standard Library" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/stdlib.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Operating System Interface: The os module provides dozens of functions for interacting with the operating system: Be sure to use the import os style instead of from os import *. This will keep os.o..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Operating System Interface: The os module provides dozens of functions for interacting with the operating system: Be sure to use the import os style instead of from os import *. This will keep os.o..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>10. Brief Tour of the Standard Library — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
|
||||
<link rel="prev" title="9. Classes" href="classes.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">10. Brief Tour of the Standard Library</a><ul>
|
||||
<li><a class="reference internal" href="#operating-system-interface">10.1. Operating System Interface</a></li>
|
||||
<li><a class="reference internal" href="#file-wildcards">10.2. File Wildcards</a></li>
|
||||
<li><a class="reference internal" href="#command-line-arguments">10.3. Command Line Arguments</a></li>
|
||||
<li><a class="reference internal" href="#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
|
||||
<li><a class="reference internal" href="#string-pattern-matching">10.5. String Pattern Matching</a></li>
|
||||
<li><a class="reference internal" href="#mathematics">10.6. Mathematics</a></li>
|
||||
<li><a class="reference internal" href="#internet-access">10.7. Internet Access</a></li>
|
||||
<li><a class="reference internal" href="#dates-and-times">10.8. Dates and Times</a></li>
|
||||
<li><a class="reference internal" href="#data-compression">10.9. Data Compression</a></li>
|
||||
<li><a class="reference internal" href="#performance-measurement">10.10. Performance Measurement</a></li>
|
||||
<li><a class="reference internal" href="#quality-control">10.11. Quality Control</a></li>
|
||||
<li><a class="reference internal" href="#batteries-included">10.12. Batteries Included</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="classes.html"
|
||||
title="previous chapter"><span class="section-number">9. </span>Classes</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="stdlib2.html"
|
||||
title="next chapter"><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="classes.html" title="9. Classes"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">10. </span>Brief Tour of the Standard Library</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="brief-tour-of-the-standard-library">
|
||||
<span id="tut-brieftour"></span><h1><span class="section-number">10. </span>Brief Tour of the Standard Library<a class="headerlink" href="#brief-tour-of-the-standard-library" title="Link to this heading">¶</a></h1>
|
||||
<section id="operating-system-interface">
|
||||
<span id="tut-os-interface"></span><h2><span class="section-number">10.1. </span>Operating System Interface<a class="headerlink" href="#operating-system-interface" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a> module provides dozens of functions for interacting with the
|
||||
operating system:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">os</span>
|
||||
<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">getcwd</span><span class="p">()</span> <span class="c1"># Return the current working directory</span>
|
||||
<span class="go">'C:\\Python313'</span>
|
||||
<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">chdir</span><span class="p">(</span><span class="s1">'/server/accesslogs'</span><span class="p">)</span> <span class="c1"># Change current working directory</span>
|
||||
<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">system</span><span class="p">(</span><span class="s1">'mkdir today'</span><span class="p">)</span> <span class="c1"># Run the command mkdir in the system shell</span>
|
||||
<span class="go">0</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Be sure to use the <code class="docutils literal notranslate"><span class="pre">import</span> <span class="pre">os</span></code> style instead of <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">os</span> <span class="pre">import</span> <span class="pre">*</span></code>. This
|
||||
will keep <a class="reference internal" href="../library/os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a> from shadowing the built-in <a class="reference internal" href="../library/functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a> function which
|
||||
operates much differently.</p>
|
||||
<p id="index-0">The built-in <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> and <a class="reference internal" href="../library/functions.html#help" title="help"><code class="xref py py-func docutils literal notranslate"><span class="pre">help()</span></code></a> functions are useful as interactive
|
||||
aids for working with large modules like <a class="reference internal" href="../library/os.html#module-os" title="os: Miscellaneous operating system interfaces."><code class="xref py py-mod docutils literal notranslate"><span class="pre">os</span></code></a>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">os</span>
|
||||
<span class="gp">>>> </span><span class="nb">dir</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
|
||||
<span class="go"><returns a list of all module functions></span>
|
||||
<span class="gp">>>> </span><span class="n">help</span><span class="p">(</span><span class="n">os</span><span class="p">)</span>
|
||||
<span class="go"><returns an extensive manual page created from the module's docstrings></span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>For daily file and directory management tasks, the <a class="reference internal" href="../library/shutil.html#module-shutil" title="shutil: High-level file operations, including copying."><code class="xref py py-mod docutils literal notranslate"><span class="pre">shutil</span></code></a> module provides
|
||||
a higher level interface that is easier to use:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">shutil</span>
|
||||
<span class="gp">>>> </span><span class="n">shutil</span><span class="o">.</span><span class="n">copyfile</span><span class="p">(</span><span class="s1">'data.db'</span><span class="p">,</span> <span class="s1">'archive.db'</span><span class="p">)</span>
|
||||
<span class="go">'archive.db'</span>
|
||||
<span class="gp">>>> </span><span class="n">shutil</span><span class="o">.</span><span class="n">move</span><span class="p">(</span><span class="s1">'/build/executables'</span><span class="p">,</span> <span class="s1">'installdir'</span><span class="p">)</span>
|
||||
<span class="go">'installdir'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="file-wildcards">
|
||||
<span id="tut-file-wildcards"></span><h2><span class="section-number">10.2. </span>File Wildcards<a class="headerlink" href="#file-wildcards" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/glob.html#module-glob" title="glob: Unix shell style pathname pattern expansion."><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code></a> module provides a function for making file lists from directory
|
||||
wildcard searches:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">glob</span>
|
||||
<span class="gp">>>> </span><span class="n">glob</span><span class="o">.</span><span class="n">glob</span><span class="p">(</span><span class="s1">'*.py'</span><span class="p">)</span>
|
||||
<span class="go">['primes.py', 'random.py', 'quote.py']</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="command-line-arguments">
|
||||
<span id="tut-command-line-arguments"></span><h2><span class="section-number">10.3. </span>Command Line Arguments<a class="headerlink" href="#command-line-arguments" title="Link to this heading">¶</a></h2>
|
||||
<p>Common utility scripts often need to process command line arguments. These
|
||||
arguments are stored in the <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> module’s <em>argv</em> attribute as a list. For
|
||||
instance, let’s take the following <code class="file docutils literal notranslate"><span class="pre">demo.py</span></code> file:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># File demo.py</span>
|
||||
<span class="kn">import</span><span class="w"> </span><span class="nn">sys</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Here is the output from running <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">demo.py</span> <span class="pre">one</span> <span class="pre">two</span> <span class="pre">three</span></code> at the command
|
||||
line:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="p">[</span><span class="s1">'demo.py'</span><span class="p">,</span> <span class="s1">'one'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">,</span> <span class="s1">'three'</span><span class="p">]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/argparse.html#module-argparse" title="argparse: Command-line option and argument parsing library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">argparse</span></code></a> module provides a more sophisticated mechanism to process
|
||||
command line arguments. The following script extracts one or more filenames
|
||||
and an optional number of lines to be displayed:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">argparse</span>
|
||||
|
||||
<span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
|
||||
<span class="n">prog</span><span class="o">=</span><span class="s1">'top'</span><span class="p">,</span>
|
||||
<span class="n">description</span><span class="o">=</span><span class="s1">'Show top lines from each file'</span><span class="p">)</span>
|
||||
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">'filenames'</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s1">'+'</span><span class="p">)</span>
|
||||
<span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s1">'-l'</span><span class="p">,</span> <span class="s1">'--lines'</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span>
|
||||
<span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">args</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>When run at the command line with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">top.py</span> <span class="pre">--lines=5</span> <span class="pre">alpha.txt</span>
|
||||
<span class="pre">beta.txt</span></code>, the script sets <code class="docutils literal notranslate"><span class="pre">args.lines</span></code> to <code class="docutils literal notranslate"><span class="pre">5</span></code> and <code class="docutils literal notranslate"><span class="pre">args.filenames</span></code>
|
||||
to <code class="docutils literal notranslate"><span class="pre">['alpha.txt',</span> <span class="pre">'beta.txt']</span></code>.</p>
|
||||
</section>
|
||||
<section id="error-output-redirection-and-program-termination">
|
||||
<span id="tut-stderr"></span><h2><span class="section-number">10.4. </span>Error Output Redirection and Program Termination<a class="headerlink" href="#error-output-redirection-and-program-termination" title="Link to this heading">¶</a></h2>
|
||||
<p>The <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> module also has attributes for <em>stdin</em>, <em>stdout</em>, and <em>stderr</em>.
|
||||
The latter is useful for emitting warnings and error messages to make them
|
||||
visible even when <em>stdout</em> has been redirected:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">sys</span><span class="o">.</span><span class="n">stderr</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s1">'Warning, log file not found starting a new one</span><span class="se">\n</span><span class="s1">'</span><span class="p">)</span>
|
||||
<span class="go">Warning, log file not found starting a new one</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The most direct way to terminate a script is to use <code class="docutils literal notranslate"><span class="pre">sys.exit()</span></code>.</p>
|
||||
</section>
|
||||
<section id="string-pattern-matching">
|
||||
<span id="tut-string-pattern-matching"></span><h2><span class="section-number">10.5. </span>String Pattern Matching<a class="headerlink" href="#string-pattern-matching" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/re.html#module-re" title="re: Regular expression operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">re</span></code></a> module provides regular expression tools for advanced string
|
||||
processing. For complex matching and manipulation, regular expressions offer
|
||||
succinct, optimized solutions:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">re</span>
|
||||
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">findall</span><span class="p">(</span><span class="sa">r</span><span class="s1">'\bf[a-z]*'</span><span class="p">,</span> <span class="s1">'which foot or hand fell fastest'</span><span class="p">)</span>
|
||||
<span class="go">['foot', 'fell', 'fastest']</span>
|
||||
<span class="gp">>>> </span><span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="sa">r</span><span class="s1">'(\b[a-z]+) \1'</span><span class="p">,</span> <span class="sa">r</span><span class="s1">'\1'</span><span class="p">,</span> <span class="s1">'cat in the the hat'</span><span class="p">)</span>
|
||||
<span class="go">'cat in the hat'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>When only simple capabilities are needed, string methods are preferred because
|
||||
they are easier to read and debug:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="s1">'tea for too'</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s1">'too'</span><span class="p">,</span> <span class="s1">'two'</span><span class="p">)</span>
|
||||
<span class="go">'tea for two'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="mathematics">
|
||||
<span id="tut-mathematics"></span><h2><span class="section-number">10.6. </span>Mathematics<a class="headerlink" href="#mathematics" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/math.html#module-math" title="math: Mathematical functions (sin() etc.)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">math</span></code></a> module gives access to the underlying C library functions for
|
||||
floating-point math:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">math</span>
|
||||
<span class="gp">>>> </span><span class="n">math</span><span class="o">.</span><span class="n">cos</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">pi</span> <span class="o">/</span> <span class="mi">4</span><span class="p">)</span>
|
||||
<span class="go">0.70710678118654757</span>
|
||||
<span class="gp">>>> </span><span class="n">math</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="mi">1024</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="go">10.0</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/random.html#module-random" title="random: Generate pseudo-random numbers with various common distributions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">random</span></code></a> module provides tools for making random selections:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">random</span>
|
||||
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">choice</span><span class="p">([</span><span class="s1">'apple'</span><span class="p">,</span> <span class="s1">'pear'</span><span class="p">,</span> <span class="s1">'banana'</span><span class="p">])</span>
|
||||
<span class="go">'apple'</span>
|
||||
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">sample</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">100</span><span class="p">),</span> <span class="mi">10</span><span class="p">)</span> <span class="c1"># sampling without replacement</span>
|
||||
<span class="go">[30, 83, 16, 4, 8, 81, 41, 50, 18, 33]</span>
|
||||
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">random</span><span class="p">()</span> <span class="c1"># random float from the interval [0.0, 1.0)</span>
|
||||
<span class="go">0.17970987693706186</span>
|
||||
<span class="gp">>>> </span><span class="n">random</span><span class="o">.</span><span class="n">randrange</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span> <span class="c1"># random integer chosen from range(6)</span>
|
||||
<span class="go">4</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/statistics.html#module-statistics" title="statistics: Mathematical statistics functions"><code class="xref py py-mod docutils literal notranslate"><span class="pre">statistics</span></code></a> module calculates basic statistical properties
|
||||
(the mean, median, variance, etc.) of numeric data:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">statistics</span>
|
||||
<span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mf">2.75</span><span class="p">,</span> <span class="mf">1.75</span><span class="p">,</span> <span class="mf">1.25</span><span class="p">,</span> <span class="mf">0.25</span><span class="p">,</span> <span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.25</span><span class="p">,</span> <span class="mf">3.5</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">statistics</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
|
||||
<span class="go">1.6071428571428572</span>
|
||||
<span class="gp">>>> </span><span class="n">statistics</span><span class="o">.</span><span class="n">median</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
|
||||
<span class="go">1.25</span>
|
||||
<span class="gp">>>> </span><span class="n">statistics</span><span class="o">.</span><span class="n">variance</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
|
||||
<span class="go">1.3720238095238095</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The SciPy project <<a class="reference external" href="https://scipy.org">https://scipy.org</a>> has many other modules for numerical
|
||||
computations.</p>
|
||||
</section>
|
||||
<section id="internet-access">
|
||||
<span id="tut-internet-access"></span><h2><span class="section-number">10.7. </span>Internet Access<a class="headerlink" href="#internet-access" title="Link to this heading">¶</a></h2>
|
||||
<p>There are a number of modules for accessing the internet and processing internet
|
||||
protocols. Two of the simplest are <a class="reference internal" href="../library/urllib.request.html#module-urllib.request" title="urllib.request: Extensible library for opening URLs."><code class="xref py py-mod docutils literal notranslate"><span class="pre">urllib.request</span></code></a> for retrieving data
|
||||
from URLs and <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> for sending mail:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">urllib.request</span><span class="w"> </span><span class="kn">import</span> <span class="n">urlopen</span>
|
||||
<span class="gp">>>> </span><span class="k">with</span> <span class="n">urlopen</span><span class="p">(</span><span class="s1">'http://worldtimeapi.org/api/timezone/etc/UTC.txt'</span><span class="p">)</span> <span class="k">as</span> <span class="n">response</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">response</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="n">line</span> <span class="o">=</span> <span class="n">line</span><span class="o">.</span><span class="n">decode</span><span class="p">()</span> <span class="c1"># Convert bytes to a str</span>
|
||||
<span class="gp">... </span> <span class="k">if</span> <span class="n">line</span><span class="o">.</span><span class="n">startswith</span><span class="p">(</span><span class="s1">'datetime'</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="n">line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">())</span> <span class="c1"># Remove trailing newline</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="go">datetime: 2022-01-01T01:36:47.689215+00:00</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">smtplib</span>
|
||||
<span class="gp">>>> </span><span class="n">server</span> <span class="o">=</span> <span class="n">smtplib</span><span class="o">.</span><span class="n">SMTP</span><span class="p">(</span><span class="s1">'localhost'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">server</span><span class="o">.</span><span class="n">sendmail</span><span class="p">(</span><span class="s1">'soothsayer@example.org'</span><span class="p">,</span> <span class="s1">'jcaesar@example.org'</span><span class="p">,</span>
|
||||
<span class="gp">... </span><span class="sd">"""To: jcaesar@example.org</span>
|
||||
<span class="gp">... </span><span class="sd">From: soothsayer@example.org</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">... </span><span class="sd">Beware the Ides of March.</span>
|
||||
<span class="gp">... </span><span class="sd">"""</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">server</span><span class="o">.</span><span class="n">quit</span><span class="p">()</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>(Note that the second example needs a mailserver running on localhost.)</p>
|
||||
</section>
|
||||
<section id="dates-and-times">
|
||||
<span id="tut-dates-and-times"></span><h2><span class="section-number">10.8. </span>Dates and Times<a class="headerlink" href="#dates-and-times" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/datetime.html#module-datetime" title="datetime: Basic date and time types."><code class="xref py py-mod docutils literal notranslate"><span class="pre">datetime</span></code></a> module supplies classes for manipulating dates and times in
|
||||
both simple and complex ways. While date and time arithmetic is supported, the
|
||||
focus of the implementation is on efficient member extraction for output
|
||||
formatting and manipulation. The module also supports objects that are timezone
|
||||
aware.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="c1"># dates are easily constructed and formatted</span>
|
||||
<span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">datetime</span><span class="w"> </span><span class="kn">import</span> <span class="n">date</span>
|
||||
<span class="gp">>>> </span><span class="n">now</span> <span class="o">=</span> <span class="n">date</span><span class="o">.</span><span class="n">today</span><span class="p">()</span>
|
||||
<span class="gp">>>> </span><span class="n">now</span>
|
||||
<span class="go">datetime.date(2003, 12, 2)</span>
|
||||
<span class="gp">>>> </span><span class="n">now</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s2">"%m-</span><span class="si">%d</span><span class="s2">-%y. </span><span class="si">%d</span><span class="s2"> %b %Y is a %A on the </span><span class="si">%d</span><span class="s2"> day of %B."</span><span class="p">)</span>
|
||||
<span class="go">'12-02-03. 02 Dec 2003 is a Tuesday on the 02 day of December.'</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="c1"># dates support calendar arithmetic</span>
|
||||
<span class="gp">>>> </span><span class="n">birthday</span> <span class="o">=</span> <span class="n">date</span><span class="p">(</span><span class="mi">1964</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">31</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">age</span> <span class="o">=</span> <span class="n">now</span> <span class="o">-</span> <span class="n">birthday</span>
|
||||
<span class="gp">>>> </span><span class="n">age</span><span class="o">.</span><span class="n">days</span>
|
||||
<span class="go">14368</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="data-compression">
|
||||
<span id="tut-data-compression"></span><h2><span class="section-number">10.9. </span>Data Compression<a class="headerlink" href="#data-compression" title="Link to this heading">¶</a></h2>
|
||||
<p>Common data archiving and compression formats are directly supported by modules
|
||||
including: <a class="reference internal" href="../library/zlib.html#module-zlib" title="zlib: Low-level interface to compression and decompression routines compatible with gzip."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zlib</span></code></a>, <a class="reference internal" href="../library/gzip.html#module-gzip" title="gzip: Interfaces for gzip compression and decompression using file objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gzip</span></code></a>, <a class="reference internal" href="../library/bz2.html#module-bz2" title="bz2: Interfaces for bzip2 compression and decompression."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bz2</span></code></a>, <a class="reference internal" href="../library/lzma.html#module-lzma" title="lzma: A Python wrapper for the liblzma compression library."><code class="xref py py-mod docutils literal notranslate"><span class="pre">lzma</span></code></a>, <a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> and
|
||||
<a class="reference internal" href="../library/tarfile.html#module-tarfile" title="tarfile: Read and write tar-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">tarfile</span></code></a>.</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">zlib</span>
|
||||
<span class="gp">>>> </span><span class="n">s</span> <span class="o">=</span> <span class="sa">b</span><span class="s1">'witch which has which witches wrist watch'</span>
|
||||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">41</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">zlib</span><span class="o">.</span><span class="n">compress</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="nb">len</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
|
||||
<span class="go">37</span>
|
||||
<span class="gp">>>> </span><span class="n">zlib</span><span class="o">.</span><span class="n">decompress</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
|
||||
<span class="go">b'witch which has which witches wrist watch'</span>
|
||||
<span class="gp">>>> </span><span class="n">zlib</span><span class="o">.</span><span class="n">crc32</span><span class="p">(</span><span class="n">s</span><span class="p">)</span>
|
||||
<span class="go">226805979</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="performance-measurement">
|
||||
<span id="tut-performance-measurement"></span><h2><span class="section-number">10.10. </span>Performance Measurement<a class="headerlink" href="#performance-measurement" title="Link to this heading">¶</a></h2>
|
||||
<p>Some Python users develop a deep interest in knowing the relative performance of
|
||||
different approaches to the same problem. Python provides a measurement tool
|
||||
that answers those questions immediately.</p>
|
||||
<p>For example, it may be tempting to use the tuple packing and unpacking feature
|
||||
instead of the traditional approach to swapping arguments. The <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>
|
||||
module quickly demonstrates a modest performance advantage:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">timeit</span><span class="w"> </span><span class="kn">import</span> <span class="n">Timer</span>
|
||||
<span class="gp">>>> </span><span class="n">Timer</span><span class="p">(</span><span class="s1">'t=a; a=b; b=t'</span><span class="p">,</span> <span class="s1">'a=1; b=2'</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
|
||||
<span class="go">0.57535828626024577</span>
|
||||
<span class="gp">>>> </span><span class="n">Timer</span><span class="p">(</span><span class="s1">'a,b = b,a'</span><span class="p">,</span> <span class="s1">'a=1; b=2'</span><span class="p">)</span><span class="o">.</span><span class="n">timeit</span><span class="p">()</span>
|
||||
<span class="go">0.54962537085770791</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>In contrast to <a class="reference internal" href="../library/timeit.html#module-timeit" title="timeit: Measure the execution time of small code snippets."><code class="xref py py-mod docutils literal notranslate"><span class="pre">timeit</span></code></a>’s fine level of granularity, the <a class="reference internal" href="../library/profile.html#module-profile" title="profile: Python source profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">profile</span></code></a> and
|
||||
<a class="reference internal" href="../library/profile.html#module-pstats" title="pstats: Statistics object for use with the profiler."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pstats</span></code></a> modules provide tools for identifying time critical sections in
|
||||
larger blocks of code.</p>
|
||||
</section>
|
||||
<section id="quality-control">
|
||||
<span id="tut-quality-control"></span><h2><span class="section-number">10.11. </span>Quality Control<a class="headerlink" href="#quality-control" title="Link to this heading">¶</a></h2>
|
||||
<p>One approach for developing high quality software is to write tests for each
|
||||
function as it is developed and to run those tests frequently during the
|
||||
development process.</p>
|
||||
<p>The <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module provides a tool for scanning a module and validating
|
||||
tests embedded in a program’s docstrings. Test construction is as simple as
|
||||
cutting-and-pasting a typical call along with its results into the docstring.
|
||||
This improves the documentation by providing the user with an example and it
|
||||
allows the doctest module to make sure the code remains true to the
|
||||
documentation:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span><span class="w"> </span><span class="nf">average</span><span class="p">(</span><span class="n">values</span><span class="p">):</span>
|
||||
<span class="w"> </span><span class="sd">"""Computes the arithmetic mean of a list of numbers.</span>
|
||||
|
||||
<span class="sd"> >>> print(average([20, 30, 70]))</span>
|
||||
<span class="sd"> 40.0</span>
|
||||
<span class="sd"> """</span>
|
||||
<span class="k">return</span> <span class="nb">sum</span><span class="p">(</span><span class="n">values</span><span class="p">)</span> <span class="o">/</span> <span class="nb">len</span><span class="p">(</span><span class="n">values</span><span class="p">)</span>
|
||||
|
||||
<span class="kn">import</span><span class="w"> </span><span class="nn">doctest</span>
|
||||
<span class="n">doctest</span><span class="o">.</span><span class="n">testmod</span><span class="p">()</span> <span class="c1"># automatically validate the embedded tests</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/unittest.html#module-unittest" title="unittest: Unit testing framework for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">unittest</span></code></a> module is not as effortless as the <a class="reference internal" href="../library/doctest.html#module-doctest" title="doctest: Test pieces of code within docstrings."><code class="xref py py-mod docutils literal notranslate"><span class="pre">doctest</span></code></a> module,
|
||||
but it allows a more comprehensive set of tests to be maintained in a separate
|
||||
file:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">unittest</span>
|
||||
|
||||
<span class="k">class</span><span class="w"> </span><span class="nc">TestStatisticalFunctions</span><span class="p">(</span><span class="n">unittest</span><span class="o">.</span><span class="n">TestCase</span><span class="p">):</span>
|
||||
|
||||
<span class="k">def</span><span class="w"> </span><span class="nf">test_average</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||||
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">]),</span> <span class="mf">40.0</span><span class="p">)</span>
|
||||
<span class="bp">self</span><span class="o">.</span><span class="n">assertEqual</span><span class="p">(</span><span class="nb">round</span><span class="p">(</span><span class="n">average</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">]),</span> <span class="mi">1</span><span class="p">),</span> <span class="mf">4.3</span><span class="p">)</span>
|
||||
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">ZeroDivisionError</span><span class="p">):</span>
|
||||
<span class="n">average</span><span class="p">([])</span>
|
||||
<span class="k">with</span> <span class="bp">self</span><span class="o">.</span><span class="n">assertRaises</span><span class="p">(</span><span class="ne">TypeError</span><span class="p">):</span>
|
||||
<span class="n">average</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">70</span><span class="p">)</span>
|
||||
|
||||
<span class="n">unittest</span><span class="o">.</span><span class="n">main</span><span class="p">()</span> <span class="c1"># Calling from the command line invokes all tests</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="batteries-included">
|
||||
<span id="tut-batteries-included"></span><h2><span class="section-number">10.12. </span>Batteries Included<a class="headerlink" href="#batteries-included" title="Link to this heading">¶</a></h2>
|
||||
<p>Python has a “batteries included” philosophy. This is best seen through the
|
||||
sophisticated and robust capabilities of its larger packages. For example:</p>
|
||||
<ul class="simple">
|
||||
<li><p>The <a class="reference internal" href="../library/xmlrpc.client.html#module-xmlrpc.client" title="xmlrpc.client: XML-RPC client access."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.client</span></code></a> and <a class="reference internal" href="../library/xmlrpc.server.html#module-xmlrpc.server" title="xmlrpc.server: Basic XML-RPC server implementations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xmlrpc.server</span></code></a> modules make implementing
|
||||
remote procedure calls into an almost trivial task. Despite the modules’
|
||||
names, no direct knowledge or handling of XML is needed.</p></li>
|
||||
<li><p>The <a class="reference internal" href="../library/email.html#module-email" title="email: Package supporting the parsing, manipulating, and generating email messages."><code class="xref py py-mod docutils literal notranslate"><span class="pre">email</span></code></a> package is a library for managing email messages, including
|
||||
MIME and other <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2822.html"><strong>RFC 2822</strong></a>-based message documents. Unlike <a class="reference internal" href="../library/smtplib.html#module-smtplib" title="smtplib: SMTP protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">smtplib</span></code></a> and
|
||||
<a class="reference internal" href="../library/poplib.html#module-poplib" title="poplib: POP3 protocol client (requires sockets)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">poplib</span></code></a> which actually send and receive messages, the email package has
|
||||
a complete toolset for building or decoding complex message structures
|
||||
(including attachments) and for implementing internet encoding and header
|
||||
protocols.</p></li>
|
||||
<li><p>The <a class="reference internal" href="../library/json.html#module-json" title="json: Encode and decode the JSON format."><code class="xref py py-mod docutils literal notranslate"><span class="pre">json</span></code></a> package provides robust support for parsing this
|
||||
popular data interchange format. The <a class="reference internal" href="../library/csv.html#module-csv" title="csv: Write and read tabular data to and from delimited files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">csv</span></code></a> module supports
|
||||
direct reading and writing of files in Comma-Separated Value format,
|
||||
commonly supported by databases and spreadsheets. XML processing is
|
||||
supported by the <a class="reference internal" href="../library/xml.etree.elementtree.html#module-xml.etree.ElementTree" title="xml.etree.ElementTree: Implementation of the ElementTree API."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.etree.ElementTree</span></code></a>, <a class="reference internal" href="../library/xml.dom.html#module-xml.dom" title="xml.dom: Document Object Model API for Python."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.dom</span></code></a> and
|
||||
<a class="reference internal" href="../library/xml.sax.html#module-xml.sax" title="xml.sax: Package containing SAX2 base classes and convenience functions."><code class="xref py py-mod docutils literal notranslate"><span class="pre">xml.sax</span></code></a> packages. Together, these modules and packages
|
||||
greatly simplify data interchange between Python applications and
|
||||
other tools.</p></li>
|
||||
<li><p>The <a class="reference internal" href="../library/sqlite3.html#module-sqlite3" title="sqlite3: A DB-API 2.0 implementation using SQLite 3.x."><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> module is a wrapper for the SQLite database
|
||||
library, providing a persistent database that can be updated and
|
||||
accessed using slightly nonstandard SQL syntax.</p></li>
|
||||
<li><p>Internationalization is supported by a number of modules including
|
||||
<a class="reference internal" href="../library/gettext.html#module-gettext" title="gettext: Multilingual internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gettext</span></code></a>, <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a>, and the <a class="reference internal" href="../library/codecs.html#module-codecs" title="codecs: Encode and decode data and streams."><code class="xref py py-mod docutils literal notranslate"><span class="pre">codecs</span></code></a> package.</p></li>
|
||||
</ul>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">10. Brief Tour of the Standard Library</a><ul>
|
||||
<li><a class="reference internal" href="#operating-system-interface">10.1. Operating System Interface</a></li>
|
||||
<li><a class="reference internal" href="#file-wildcards">10.2. File Wildcards</a></li>
|
||||
<li><a class="reference internal" href="#command-line-arguments">10.3. Command Line Arguments</a></li>
|
||||
<li><a class="reference internal" href="#error-output-redirection-and-program-termination">10.4. Error Output Redirection and Program Termination</a></li>
|
||||
<li><a class="reference internal" href="#string-pattern-matching">10.5. String Pattern Matching</a></li>
|
||||
<li><a class="reference internal" href="#mathematics">10.6. Mathematics</a></li>
|
||||
<li><a class="reference internal" href="#internet-access">10.7. Internet Access</a></li>
|
||||
<li><a class="reference internal" href="#dates-and-times">10.8. Dates and Times</a></li>
|
||||
<li><a class="reference internal" href="#data-compression">10.9. Data Compression</a></li>
|
||||
<li><a class="reference internal" href="#performance-measurement">10.10. Performance Measurement</a></li>
|
||||
<li><a class="reference internal" href="#quality-control">10.11. Quality Control</a></li>
|
||||
<li><a class="reference internal" href="#batteries-included">10.12. Batteries Included</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="classes.html"
|
||||
title="previous chapter"><span class="section-number">9. </span>Classes</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="stdlib2.html"
|
||||
title="next chapter"><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="classes.html" title="9. Classes"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">10. </span>Brief Tour of the Standard Library</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
706
Dependencies/Python/Doc/html/tutorial/stdlib2.html
vendored
Normal file
706
Dependencies/Python/Doc/html/tutorial/stdlib2.html
vendored
Normal file
@@ -0,0 +1,706 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="11. Brief Tour of the Standard Library — Part II" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/stdlib2.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. Output Formatting: The reprlib module provides a version of r..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="This second tour covers more advanced modules that support professional programming needs. These modules rarely occur in small scripts. Output Formatting: The reprlib module provides a version of r..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>11. Brief Tour of the Standard Library — Part II — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="12. Virtual Environments and Packages" href="venv.html" />
|
||||
<link rel="prev" title="10. Brief Tour of the Standard Library" href="stdlib.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/stdlib2.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
|
||||
<li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
|
||||
<li><a class="reference internal" href="#templating">11.2. Templating</a></li>
|
||||
<li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
|
||||
<li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
|
||||
<li><a class="reference internal" href="#logging">11.5. Logging</a></li>
|
||||
<li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
|
||||
<li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
|
||||
<li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating-Point Arithmetic</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="stdlib.html"
|
||||
title="previous chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="venv.html"
|
||||
title="next chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib2.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="venv.html" title="12. Virtual Environments and Packages"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib.html" title="10. Brief Tour of the Standard Library"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="brief-tour-of-the-standard-library-part-ii">
|
||||
<span id="tut-brieftourtwo"></span><h1><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II<a class="headerlink" href="#brief-tour-of-the-standard-library-part-ii" title="Link to this heading">¶</a></h1>
|
||||
<p>This second tour covers more advanced modules that support professional
|
||||
programming needs. These modules rarely occur in small scripts.</p>
|
||||
<section id="output-formatting">
|
||||
<span id="tut-output-formatting"></span><h2><span class="section-number">11.1. </span>Output Formatting<a class="headerlink" href="#output-formatting" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/reprlib.html#module-reprlib" title="reprlib: Alternate repr() implementation with size limits."><code class="xref py py-mod docutils literal notranslate"><span class="pre">reprlib</span></code></a> module provides a version of <a class="reference internal" href="../library/functions.html#repr" title="repr"><code class="xref py py-func docutils literal notranslate"><span class="pre">repr()</span></code></a> customized for
|
||||
abbreviated displays of large or deeply nested containers:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">reprlib</span>
|
||||
<span class="gp">>>> </span><span class="n">reprlib</span><span class="o">.</span><span class="n">repr</span><span class="p">(</span><span class="nb">set</span><span class="p">(</span><span class="s1">'supercalifragilisticexpialidocious'</span><span class="p">))</span>
|
||||
<span class="go">"{'a', 'c', 'd', 'e', 'f', 'g', ...}"</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/pprint.html#module-pprint" title="pprint: Data pretty printer."><code class="xref py py-mod docutils literal notranslate"><span class="pre">pprint</span></code></a> module offers more sophisticated control over printing both
|
||||
built-in and user defined objects in a way that is readable by the interpreter.
|
||||
When the result is longer than one line, the “pretty printer” adds line breaks
|
||||
and indentation to more clearly reveal data structure:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">pprint</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="p">[[[[</span><span class="s1">'black'</span><span class="p">,</span> <span class="s1">'cyan'</span><span class="p">],</span> <span class="s1">'white'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'green'</span><span class="p">,</span> <span class="s1">'red'</span><span class="p">]],</span> <span class="p">[[</span><span class="s1">'magenta'</span><span class="p">,</span>
|
||||
<span class="gp">... </span> <span class="s1">'yellow'</span><span class="p">],</span> <span class="s1">'blue'</span><span class="p">]]]</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">pprint</span><span class="o">.</span><span class="n">pprint</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">30</span><span class="p">)</span>
|
||||
<span class="go">[[[['black', 'cyan'],</span>
|
||||
<span class="go"> 'white',</span>
|
||||
<span class="go"> ['green', 'red']],</span>
|
||||
<span class="go"> [['magenta', 'yellow'],</span>
|
||||
<span class="go"> 'blue']]]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/textwrap.html#module-textwrap" title="textwrap: Text wrapping and filling"><code class="xref py py-mod docutils literal notranslate"><span class="pre">textwrap</span></code></a> module formats paragraphs of text to fit a given screen
|
||||
width:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">textwrap</span>
|
||||
<span class="gp">>>> </span><span class="n">doc</span> <span class="o">=</span> <span class="s2">"""The wrap() method is just like fill() except that it returns</span>
|
||||
<span class="gp">... </span><span class="s2">a list of strings instead of one big string with newlines to separate</span>
|
||||
<span class="gp">... </span><span class="s2">the wrapped lines."""</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="n">textwrap</span><span class="o">.</span><span class="n">fill</span><span class="p">(</span><span class="n">doc</span><span class="p">,</span> <span class="n">width</span><span class="o">=</span><span class="mi">40</span><span class="p">))</span>
|
||||
<span class="go">The wrap() method is just like fill()</span>
|
||||
<span class="go">except that it returns a list of strings</span>
|
||||
<span class="go">instead of one big string with newlines</span>
|
||||
<span class="go">to separate the wrapped lines.</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/locale.html#module-locale" title="locale: Internationalization services."><code class="xref py py-mod docutils literal notranslate"><span class="pre">locale</span></code></a> module accesses a database of culture specific data formats.
|
||||
The grouping attribute of locale’s format function provides a direct way of
|
||||
formatting numbers with group separators:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">locale</span>
|
||||
<span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">setlocale</span><span class="p">(</span><span class="n">locale</span><span class="o">.</span><span class="n">LC_ALL</span><span class="p">,</span> <span class="s1">'English_United States.1252'</span><span class="p">)</span>
|
||||
<span class="go">'English_United States.1252'</span>
|
||||
<span class="gp">>>> </span><span class="n">conv</span> <span class="o">=</span> <span class="n">locale</span><span class="o">.</span><span class="n">localeconv</span><span class="p">()</span> <span class="c1"># get a mapping of conventions</span>
|
||||
<span class="gp">>>> </span><span class="n">x</span> <span class="o">=</span> <span class="mf">1234567.8</span>
|
||||
<span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">"</span><span class="si">%d</span><span class="s2">"</span><span class="p">,</span> <span class="n">x</span><span class="p">,</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
|
||||
<span class="go">'1,234,567'</span>
|
||||
<span class="gp">>>> </span><span class="n">locale</span><span class="o">.</span><span class="n">format_string</span><span class="p">(</span><span class="s2">"</span><span class="si">%s%.*f</span><span class="s2">"</span><span class="p">,</span> <span class="p">(</span><span class="n">conv</span><span class="p">[</span><span class="s1">'currency_symbol'</span><span class="p">],</span>
|
||||
<span class="gp">... </span> <span class="n">conv</span><span class="p">[</span><span class="s1">'frac_digits'</span><span class="p">],</span> <span class="n">x</span><span class="p">),</span> <span class="n">grouping</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
|
||||
<span class="go">'$1,234,567.80'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="templating">
|
||||
<span id="tut-templating"></span><h2><span class="section-number">11.2. </span>Templating<a class="headerlink" href="#templating" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/string.html#module-string" title="string: Common string operations."><code class="xref py py-mod docutils literal notranslate"><span class="pre">string</span></code></a> module includes a versatile <a class="reference internal" href="../library/string.html#string.Template" title="string.Template"><code class="xref py py-class docutils literal notranslate"><span class="pre">Template</span></code></a> class
|
||||
with a simplified syntax suitable for editing by end-users. This allows users
|
||||
to customize their applications without having to alter the application.</p>
|
||||
<p>The format uses placeholder names formed by <code class="docutils literal notranslate"><span class="pre">$</span></code> with valid Python identifiers
|
||||
(alphanumeric characters and underscores). Surrounding the placeholder with
|
||||
braces allows it to be followed by more alphanumeric letters with no intervening
|
||||
spaces. Writing <code class="docutils literal notranslate"><span class="pre">$$</span></code> creates a single escaped <code class="docutils literal notranslate"><span class="pre">$</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">string</span><span class="w"> </span><span class="kn">import</span> <span class="n">Template</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">'$</span><span class="si">{village}</span><span class="s1">folk send $$10 to $cause.'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">village</span><span class="o">=</span><span class="s1">'Nottingham'</span><span class="p">,</span> <span class="n">cause</span><span class="o">=</span><span class="s1">'the ditch fund'</span><span class="p">)</span>
|
||||
<span class="go">'Nottinghamfolk send $10 to the ditch fund.'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/string.html#string.Template.substitute" title="string.Template.substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">substitute()</span></code></a> method raises a <a class="reference internal" href="../library/exceptions.html#KeyError" title="KeyError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">KeyError</span></code></a> when a
|
||||
placeholder is not supplied in a dictionary or a keyword argument. For
|
||||
mail-merge style applications, user supplied data may be incomplete and the
|
||||
<a class="reference internal" href="../library/string.html#string.Template.safe_substitute" title="string.Template.safe_substitute"><code class="xref py py-meth docutils literal notranslate"><span class="pre">safe_substitute()</span></code></a> method may be more appropriate —
|
||||
it will leave placeholders unchanged if data is missing:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s1">'Return the $item to $owner.'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">item</span><span class="o">=</span><span class="s1">'unladen swallow'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
<span class="w"> </span><span class="c">...</span>
|
||||
<span class="gr">KeyError</span>: <span class="n">'owner'</span>
|
||||
<span class="gp">>>> </span><span class="n">t</span><span class="o">.</span><span class="n">safe_substitute</span><span class="p">(</span><span class="n">d</span><span class="p">)</span>
|
||||
<span class="go">'Return the unladen swallow to $owner.'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Template subclasses can specify a custom delimiter. For example, a batch
|
||||
renaming utility for a photo browser may elect to use percent signs for
|
||||
placeholders such as the current date, image sequence number, or file format:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">time</span><span class="o">,</span><span class="w"> </span><span class="nn">os.path</span>
|
||||
<span class="gp">>>> </span><span class="n">photofiles</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'img_1074.jpg'</span><span class="p">,</span> <span class="s1">'img_1076.jpg'</span><span class="p">,</span> <span class="s1">'img_1077.jpg'</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">BatchRename</span><span class="p">(</span><span class="n">Template</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="n">delimiter</span> <span class="o">=</span> <span class="s1">'%'</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">fmt</span> <span class="o">=</span> <span class="nb">input</span><span class="p">(</span><span class="s1">'Enter rename style (</span><span class="si">%d</span><span class="s1">-date %n-seqnum </span><span class="si">%f</span><span class="s1">-format): '</span><span class="p">)</span>
|
||||
<span class="go">Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="n">t</span> <span class="o">=</span> <span class="n">BatchRename</span><span class="p">(</span><span class="n">fmt</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="n">date</span> <span class="o">=</span> <span class="n">time</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s1">'</span><span class="si">%d</span><span class="s1">%b%y'</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">filename</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">photofiles</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="n">base</span><span class="p">,</span> <span class="n">ext</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">splitext</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="n">newname</span> <span class="o">=</span> <span class="n">t</span><span class="o">.</span><span class="n">substitute</span><span class="p">(</span><span class="n">d</span><span class="o">=</span><span class="n">date</span><span class="p">,</span> <span class="n">n</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">f</span><span class="o">=</span><span class="n">ext</span><span class="p">)</span>
|
||||
<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'</span><span class="si">{0}</span><span class="s1"> --> </span><span class="si">{1}</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">newname</span><span class="p">))</span>
|
||||
|
||||
<span class="go">img_1074.jpg --> Ashley_0.jpg</span>
|
||||
<span class="go">img_1076.jpg --> Ashley_1.jpg</span>
|
||||
<span class="go">img_1077.jpg --> Ashley_2.jpg</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>Another application for templating is separating program logic from the details
|
||||
of multiple output formats. This makes it possible to substitute custom
|
||||
templates for XML files, plain text reports, and HTML web reports.</p>
|
||||
</section>
|
||||
<section id="working-with-binary-data-record-layouts">
|
||||
<span id="tut-binary-formats"></span><h2><span class="section-number">11.3. </span>Working with Binary Data Record Layouts<a class="headerlink" href="#working-with-binary-data-record-layouts" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/struct.html#module-struct" title="struct: Interpret bytes as packed binary data."><code class="xref py py-mod docutils literal notranslate"><span class="pre">struct</span></code></a> module provides <a class="reference internal" href="../library/struct.html#struct.pack" title="struct.pack"><code class="xref py py-func docutils literal notranslate"><span class="pre">pack()</span></code></a> and
|
||||
<a class="reference internal" href="../library/struct.html#struct.unpack" title="struct.unpack"><code class="xref py py-func docutils literal notranslate"><span class="pre">unpack()</span></code></a> functions for working with variable length binary
|
||||
record formats. The following example shows
|
||||
how to loop through header information in a ZIP file without using the
|
||||
<a class="reference internal" href="../library/zipfile.html#module-zipfile" title="zipfile: Read and write ZIP-format archive files."><code class="xref py py-mod docutils literal notranslate"><span class="pre">zipfile</span></code></a> module. Pack codes <code class="docutils literal notranslate"><span class="pre">"H"</span></code> and <code class="docutils literal notranslate"><span class="pre">"I"</span></code> represent two and four
|
||||
byte unsigned numbers respectively. The <code class="docutils literal notranslate"><span class="pre">"<"</span></code> indicates that they are
|
||||
standard size and in little-endian byte order:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">struct</span>
|
||||
|
||||
<span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="s1">'myfile.zip'</span><span class="p">,</span> <span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
|
||||
<span class="n">data</span> <span class="o">=</span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>
|
||||
|
||||
<span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
|
||||
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">):</span> <span class="c1"># show the first 3 file headers</span>
|
||||
<span class="n">start</span> <span class="o">+=</span> <span class="mi">14</span>
|
||||
<span class="n">fields</span> <span class="o">=</span> <span class="n">struct</span><span class="o">.</span><span class="n">unpack</span><span class="p">(</span><span class="s1">'<IIIHH'</span><span class="p">,</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="mi">16</span><span class="p">])</span>
|
||||
<span class="n">crc32</span><span class="p">,</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">,</span> <span class="n">filenamesize</span><span class="p">,</span> <span class="n">extra_size</span> <span class="o">=</span> <span class="n">fields</span>
|
||||
|
||||
<span class="n">start</span> <span class="o">+=</span> <span class="mi">16</span>
|
||||
<span class="n">filename</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">filenamesize</span><span class="p">]</span>
|
||||
<span class="n">start</span> <span class="o">+=</span> <span class="n">filenamesize</span>
|
||||
<span class="n">extra</span> <span class="o">=</span> <span class="n">data</span><span class="p">[</span><span class="n">start</span><span class="p">:</span><span class="n">start</span><span class="o">+</span><span class="n">extra_size</span><span class="p">]</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="nb">hex</span><span class="p">(</span><span class="n">crc32</span><span class="p">),</span> <span class="n">comp_size</span><span class="p">,</span> <span class="n">uncomp_size</span><span class="p">)</span>
|
||||
|
||||
<span class="n">start</span> <span class="o">+=</span> <span class="n">extra_size</span> <span class="o">+</span> <span class="n">comp_size</span> <span class="c1"># skip to the next header</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="multi-threading">
|
||||
<span id="tut-multi-threading"></span><h2><span class="section-number">11.4. </span>Multi-threading<a class="headerlink" href="#multi-threading" title="Link to this heading">¶</a></h2>
|
||||
<p>Threading is a technique for decoupling tasks which are not sequentially
|
||||
dependent. Threads can be used to improve the responsiveness of applications
|
||||
that accept user input while other tasks run in the background. A related use
|
||||
case is running I/O in parallel with computations in another thread.</p>
|
||||
<p>The following code shows how the high level <a class="reference internal" href="../library/threading.html#module-threading" title="threading: Thread-based parallelism."><code class="xref py py-mod docutils literal notranslate"><span class="pre">threading</span></code></a> module can run
|
||||
tasks in background while the main program continues to run:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">threading</span><span class="o">,</span><span class="w"> </span><span class="nn">zipfile</span>
|
||||
|
||||
<span class="k">class</span><span class="w"> </span><span class="nc">AsyncZip</span><span class="p">(</span><span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="p">):</span>
|
||||
<span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">infile</span><span class="p">,</span> <span class="n">outfile</span><span class="p">):</span>
|
||||
<span class="n">threading</span><span class="o">.</span><span class="n">Thread</span><span class="o">.</span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span>
|
||||
<span class="bp">self</span><span class="o">.</span><span class="n">infile</span> <span class="o">=</span> <span class="n">infile</span>
|
||||
<span class="bp">self</span><span class="o">.</span><span class="n">outfile</span> <span class="o">=</span> <span class="n">outfile</span>
|
||||
|
||||
<span class="k">def</span><span class="w"> </span><span class="nf">run</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||||
<span class="n">f</span> <span class="o">=</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZipFile</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">outfile</span><span class="p">,</span> <span class="s1">'w'</span><span class="p">,</span> <span class="n">zipfile</span><span class="o">.</span><span class="n">ZIP_DEFLATED</span><span class="p">)</span>
|
||||
<span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
|
||||
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s1">'Finished background zip of:'</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">infile</span><span class="p">)</span>
|
||||
|
||||
<span class="n">background</span> <span class="o">=</span> <span class="n">AsyncZip</span><span class="p">(</span><span class="s1">'mydata.txt'</span><span class="p">,</span> <span class="s1">'myarchive.zip'</span><span class="p">)</span>
|
||||
<span class="n">background</span><span class="o">.</span><span class="n">start</span><span class="p">()</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s1">'The main program continues to run in foreground.'</span><span class="p">)</span>
|
||||
|
||||
<span class="n">background</span><span class="o">.</span><span class="n">join</span><span class="p">()</span> <span class="c1"># Wait for the background task to finish</span>
|
||||
<span class="nb">print</span><span class="p">(</span><span class="s1">'Main program waited until background was done.'</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The principal challenge of multi-threaded applications is coordinating threads
|
||||
that share data or other resources. To that end, the threading module provides
|
||||
a number of synchronization primitives including locks, events, condition
|
||||
variables, and semaphores.</p>
|
||||
<p>While those tools are powerful, minor design errors can result in problems that
|
||||
are difficult to reproduce. So, the preferred approach to task coordination is
|
||||
to concentrate all access to a resource in a single thread and then use the
|
||||
<a class="reference internal" href="../library/queue.html#module-queue" title="queue: A synchronized queue class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">queue</span></code></a> module to feed that thread with requests from other threads.
|
||||
Applications using <a class="reference internal" href="../library/queue.html#queue.Queue" title="queue.Queue"><code class="xref py py-class docutils literal notranslate"><span class="pre">Queue</span></code></a> objects for inter-thread communication and
|
||||
coordination are easier to design, more readable, and more reliable.</p>
|
||||
</section>
|
||||
<section id="logging">
|
||||
<span id="tut-logging"></span><h2><span class="section-number">11.5. </span>Logging<a class="headerlink" href="#logging" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/logging.html#module-logging" title="logging: Flexible event logging system for applications."><code class="xref py py-mod docutils literal notranslate"><span class="pre">logging</span></code></a> module offers a full featured and flexible logging system.
|
||||
At its simplest, log messages are sent to a file or to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code>:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span><span class="w"> </span><span class="nn">logging</span>
|
||||
<span class="n">logging</span><span class="o">.</span><span class="n">debug</span><span class="p">(</span><span class="s1">'Debugging information'</span><span class="p">)</span>
|
||||
<span class="n">logging</span><span class="o">.</span><span class="n">info</span><span class="p">(</span><span class="s1">'Informational message'</span><span class="p">)</span>
|
||||
<span class="n">logging</span><span class="o">.</span><span class="n">warning</span><span class="p">(</span><span class="s1">'Warning:config file </span><span class="si">%s</span><span class="s1"> not found'</span><span class="p">,</span> <span class="s1">'server.conf'</span><span class="p">)</span>
|
||||
<span class="n">logging</span><span class="o">.</span><span class="n">error</span><span class="p">(</span><span class="s1">'Error occurred'</span><span class="p">)</span>
|
||||
<span class="n">logging</span><span class="o">.</span><span class="n">critical</span><span class="p">(</span><span class="s1">'Critical error -- shutting down'</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This produces the following output:</p>
|
||||
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span>WARNING:root:Warning:config file server.conf not found
|
||||
ERROR:root:Error occurred
|
||||
CRITICAL:root:Critical error -- shutting down
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>By default, informational and debugging messages are suppressed and the output
|
||||
is sent to standard error. Other output options include routing messages
|
||||
through email, datagrams, sockets, or to an HTTP Server. New filters can select
|
||||
different routing based on message priority: <a class="reference internal" href="../library/logging.html#logging.DEBUG" title="logging.DEBUG"><code class="xref py py-const docutils literal notranslate"><span class="pre">DEBUG</span></code></a>,
|
||||
<a class="reference internal" href="../library/logging.html#logging.INFO" title="logging.INFO"><code class="xref py py-const docutils literal notranslate"><span class="pre">INFO</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.WARNING" title="logging.WARNING"><code class="xref py py-const docutils literal notranslate"><span class="pre">WARNING</span></code></a>, <a class="reference internal" href="../library/logging.html#logging.ERROR" title="logging.ERROR"><code class="xref py py-const docutils literal notranslate"><span class="pre">ERROR</span></code></a>,
|
||||
and <a class="reference internal" href="../library/logging.html#logging.CRITICAL" title="logging.CRITICAL"><code class="xref py py-const docutils literal notranslate"><span class="pre">CRITICAL</span></code></a>.</p>
|
||||
<p>The logging system can be configured directly from Python or can be loaded from
|
||||
a user editable configuration file for customized logging without altering the
|
||||
application.</p>
|
||||
</section>
|
||||
<section id="weak-references">
|
||||
<span id="tut-weak-references"></span><h2><span class="section-number">11.6. </span>Weak References<a class="headerlink" href="#weak-references" title="Link to this heading">¶</a></h2>
|
||||
<p>Python does automatic memory management (reference counting for most objects and
|
||||
<a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">garbage collection</span></a> to eliminate cycles). The memory is freed shortly
|
||||
after the last reference to it has been eliminated.</p>
|
||||
<p>This approach works fine for most applications but occasionally there is a need
|
||||
to track objects only as long as they are being used by something else.
|
||||
Unfortunately, just tracking them creates a reference that makes them permanent.
|
||||
The <a class="reference internal" href="../library/weakref.html#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code class="xref py py-mod docutils literal notranslate"><span class="pre">weakref</span></code></a> module provides tools for tracking objects without creating a
|
||||
reference. When the object is no longer needed, it is automatically removed
|
||||
from a weakref table and a callback is triggered for weakref objects. Typical
|
||||
applications include caching objects that are expensive to create:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">weakref</span><span class="o">,</span><span class="w"> </span><span class="nn">gc</span>
|
||||
<span class="gp">>>> </span><span class="k">class</span><span class="w"> </span><span class="nc">A</span><span class="p">:</span>
|
||||
<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="bp">self</span><span class="o">.</span><span class="n">value</span> <span class="o">=</span> <span class="n">value</span>
|
||||
<span class="gp">... </span> <span class="k">def</span><span class="w"> </span><span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
|
||||
<span class="gp">... </span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
|
||||
<span class="gp">...</span>
|
||||
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">A</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span> <span class="c1"># create a reference</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">weakref</span><span class="o">.</span><span class="n">WeakValueDictionary</span><span class="p">()</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="o">=</span> <span class="n">a</span> <span class="c1"># does not create a reference</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># fetch the object if it is still alive</span>
|
||||
<span class="go">10</span>
|
||||
<span class="gp">>>> </span><span class="k">del</span> <span class="n">a</span> <span class="c1"># remove the one reference</span>
|
||||
<span class="gp">>>> </span><span class="n">gc</span><span class="o">.</span><span class="n">collect</span><span class="p">()</span> <span class="c1"># run garbage collection right away</span>
|
||||
<span class="go">0</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># entry was automatically removed</span>
|
||||
<span class="gt">Traceback (most recent call last):</span>
|
||||
File <span class="nb">"<stdin>"</span>, line <span class="m">1</span>, in <span class="n"><module></span>
|
||||
<span class="w"> </span><span class="n">d</span><span class="p">[</span><span class="s1">'primary'</span><span class="p">]</span> <span class="c1"># entry was automatically removed</span>
|
||||
File <span class="nb">"C:/python313/lib/weakref.py"</span>, line <span class="m">46</span>, in <span class="n">__getitem__</span>
|
||||
<span class="w"> </span><span class="n">o</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">data</span><span class="p">[</span><span class="n">key</span><span class="p">]()</span>
|
||||
<span class="gr">KeyError</span>: <span class="n">'primary'</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="tools-for-working-with-lists">
|
||||
<span id="tut-list-tools"></span><h2><span class="section-number">11.7. </span>Tools for Working with Lists<a class="headerlink" href="#tools-for-working-with-lists" title="Link to this heading">¶</a></h2>
|
||||
<p>Many data structure needs can be met with the built-in list type. However,
|
||||
sometimes there is a need for alternative implementations with different
|
||||
performance trade-offs.</p>
|
||||
<p>The <a class="reference internal" href="../library/array.html#module-array" title="array: Space efficient arrays of uniformly typed numeric values."><code class="xref py py-mod docutils literal notranslate"><span class="pre">array</span></code></a> module provides an <a class="reference internal" href="../library/array.html#array.array" title="array.array"><code class="xref py py-class docutils literal notranslate"><span class="pre">array</span></code></a> object that is like
|
||||
a list that stores only homogeneous data and stores it more compactly. The
|
||||
following example shows an array of numbers stored as two byte unsigned binary
|
||||
numbers (typecode <code class="docutils literal notranslate"><span class="pre">"H"</span></code>) rather than the usual 16 bytes per entry for regular
|
||||
lists of Python int objects:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">array</span><span class="w"> </span><span class="kn">import</span> <span class="n">array</span>
|
||||
<span class="gp">>>> </span><span class="n">a</span> <span class="o">=</span> <span class="n">array</span><span class="p">(</span><span class="s1">'H'</span><span class="p">,</span> <span class="p">[</span><span class="mi">4000</span><span class="p">,</span> <span class="mi">10</span><span class="p">,</span> <span class="mi">700</span><span class="p">,</span> <span class="mi">22222</span><span class="p">])</span>
|
||||
<span class="gp">>>> </span><span class="nb">sum</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
|
||||
<span class="go">26932</span>
|
||||
<span class="gp">>>> </span><span class="n">a</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">3</span><span class="p">]</span>
|
||||
<span class="go">array('H', [10, 700])</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/collections.html#module-collections" title="collections: Container datatypes"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections</span></code></a> module provides a <a class="reference internal" href="../library/collections.html#collections.deque" title="collections.deque"><code class="xref py py-class docutils literal notranslate"><span class="pre">deque</span></code></a> object
|
||||
that is like a list with faster appends and pops from the left side but slower
|
||||
lookups in the middle. These objects are well suited for implementing queues
|
||||
and breadth first tree searches:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">collections</span><span class="w"> </span><span class="kn">import</span> <span class="n">deque</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="s2">"task1"</span><span class="p">,</span> <span class="s2">"task2"</span><span class="p">,</span> <span class="s2">"task3"</span><span class="p">])</span>
|
||||
<span class="gp">>>> </span><span class="n">d</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s2">"task4"</span><span class="p">)</span>
|
||||
<span class="gp">>>> </span><span class="nb">print</span><span class="p">(</span><span class="s2">"Handling"</span><span class="p">,</span> <span class="n">d</span><span class="o">.</span><span class="n">popleft</span><span class="p">())</span>
|
||||
<span class="go">Handling task1</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">unsearched</span> <span class="o">=</span> <span class="n">deque</span><span class="p">([</span><span class="n">starting_node</span><span class="p">])</span>
|
||||
<span class="k">def</span><span class="w"> </span><span class="nf">breadth_first_search</span><span class="p">(</span><span class="n">unsearched</span><span class="p">):</span>
|
||||
<span class="n">node</span> <span class="o">=</span> <span class="n">unsearched</span><span class="o">.</span><span class="n">popleft</span><span class="p">()</span>
|
||||
<span class="k">for</span> <span class="n">m</span> <span class="ow">in</span> <span class="n">gen_moves</span><span class="p">(</span><span class="n">node</span><span class="p">):</span>
|
||||
<span class="k">if</span> <span class="n">is_goal</span><span class="p">(</span><span class="n">m</span><span class="p">):</span>
|
||||
<span class="k">return</span> <span class="n">m</span>
|
||||
<span class="n">unsearched</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">m</span><span class="p">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>In addition to alternative list implementations, the library also offers other
|
||||
tools such as the <a class="reference internal" href="../library/bisect.html#module-bisect" title="bisect: Array bisection algorithms for binary searching."><code class="xref py py-mod docutils literal notranslate"><span class="pre">bisect</span></code></a> module with functions for manipulating sorted
|
||||
lists:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">bisect</span>
|
||||
<span class="gp">>>> </span><span class="n">scores</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">100</span><span class="p">,</span> <span class="s1">'perl'</span><span class="p">),</span> <span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="s1">'tcl'</span><span class="p">),</span> <span class="p">(</span><span class="mi">400</span><span class="p">,</span> <span class="s1">'lua'</span><span class="p">),</span> <span class="p">(</span><span class="mi">500</span><span class="p">,</span> <span class="s1">'python'</span><span class="p">)]</span>
|
||||
<span class="gp">>>> </span><span class="n">bisect</span><span class="o">.</span><span class="n">insort</span><span class="p">(</span><span class="n">scores</span><span class="p">,</span> <span class="p">(</span><span class="mi">300</span><span class="p">,</span> <span class="s1">'ruby'</span><span class="p">))</span>
|
||||
<span class="gp">>>> </span><span class="n">scores</span>
|
||||
<span class="go">[(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/heapq.html#module-heapq" title="heapq: Heap queue algorithm (a.k.a. priority queue)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">heapq</span></code></a> module provides functions for implementing heaps based on
|
||||
regular lists. The lowest valued entry is always kept at position zero. This
|
||||
is useful for applications which repeatedly access the smallest element but do
|
||||
not want to run a full list sort:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">heapq</span><span class="w"> </span><span class="kn">import</span> <span class="n">heapify</span><span class="p">,</span> <span class="n">heappop</span><span class="p">,</span> <span class="n">heappush</span>
|
||||
<span class="gp">>>> </span><span class="n">data</span> <span class="o">=</span> <span class="p">[</span><span class="mi">1</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">9</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="mi">6</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">]</span>
|
||||
<span class="gp">>>> </span><span class="n">heapify</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="c1"># rearrange the list into heap order</span>
|
||||
<span class="gp">>>> </span><span class="n">heappush</span><span class="p">(</span><span class="n">data</span><span class="p">,</span> <span class="o">-</span><span class="mi">5</span><span class="p">)</span> <span class="c1"># add a new entry</span>
|
||||
<span class="gp">>>> </span><span class="p">[</span><span class="n">heappop</span><span class="p">(</span><span class="n">data</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">3</span><span class="p">)]</span> <span class="c1"># fetch the three smallest entries</span>
|
||||
<span class="go">[-5, 0, 1]</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
<section id="decimal-floating-point-arithmetic">
|
||||
<span id="tut-decimal-fp"></span><h2><span class="section-number">11.8. </span>Decimal Floating-Point Arithmetic<a class="headerlink" href="#decimal-floating-point-arithmetic" title="Link to this heading">¶</a></h2>
|
||||
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module offers a <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> datatype for
|
||||
decimal floating-point arithmetic. Compared to the built-in <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code></a>
|
||||
implementation of binary floating point, the class is especially helpful for</p>
|
||||
<ul class="simple">
|
||||
<li><p>financial applications and other uses which require exact decimal
|
||||
representation,</p></li>
|
||||
<li><p>control over precision,</p></li>
|
||||
<li><p>control over rounding to meet legal or regulatory requirements,</p></li>
|
||||
<li><p>tracking of significant decimal places, or</p></li>
|
||||
<li><p>applications where the user expects the results to match calculations done by
|
||||
hand.</p></li>
|
||||
</ul>
|
||||
<p>For example, calculating a 5% tax on a 70 cent phone charge gives different
|
||||
results in decimal floating point and binary floating point. The difference
|
||||
becomes significant if the results are rounded to the nearest cent:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">from</span><span class="w"> </span><span class="nn">decimal</span><span class="w"> </span><span class="kn">import</span> <span class="o">*</span>
|
||||
<span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'0.70'</span><span class="p">)</span> <span class="o">*</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.05'</span><span class="p">),</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="go">Decimal('0.74')</span>
|
||||
<span class="gp">>>> </span><span class="nb">round</span><span class="p">(</span><span class="mf">.70</span> <span class="o">*</span> <span class="mf">1.05</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
|
||||
<span class="go">0.73</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> result keeps a trailing zero, automatically
|
||||
inferring four place significance from multiplicands with two place
|
||||
significance. Decimal reproduces mathematics as done by hand and avoids
|
||||
issues that can arise when binary floating point cannot exactly represent
|
||||
decimal quantities.</p>
|
||||
<p>Exact representation enables the <a class="reference internal" href="../library/decimal.html#decimal.Decimal" title="decimal.Decimal"><code class="xref py py-class docutils literal notranslate"><span class="pre">Decimal</span></code></a> class to perform
|
||||
modulo calculations and equality tests that are unsuitable for binary floating
|
||||
point:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.00'</span><span class="p">)</span> <span class="o">%</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'.10'</span><span class="p">)</span>
|
||||
<span class="go">Decimal('0.00')</span>
|
||||
<span class="gp">>>> </span><span class="mf">1.00</span> <span class="o">%</span> <span class="mf">0.10</span>
|
||||
<span class="go">0.09999999999999995</span>
|
||||
|
||||
<span class="gp">>>> </span><span class="nb">sum</span><span class="p">([</span><span class="n">Decimal</span><span class="p">(</span><span class="s1">'0.1'</span><span class="p">)]</span><span class="o">*</span><span class="mi">10</span><span class="p">)</span> <span class="o">==</span> <span class="n">Decimal</span><span class="p">(</span><span class="s1">'1.0'</span><span class="p">)</span>
|
||||
<span class="go">True</span>
|
||||
<span class="gp">>>> </span><span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">+</span> <span class="mf">0.1</span> <span class="o">==</span> <span class="mf">1.0</span>
|
||||
<span class="go">False</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <a class="reference internal" href="../library/decimal.html#module-decimal" title="decimal: Implementation of the General Decimal Arithmetic Specification."><code class="xref py py-mod docutils literal notranslate"><span class="pre">decimal</span></code></a> module provides arithmetic with as much precision as needed:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">getcontext</span><span class="p">()</span><span class="o">.</span><span class="n">prec</span> <span class="o">=</span> <span class="mi">36</span>
|
||||
<span class="gp">>>> </span><span class="n">Decimal</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">/</span> <span class="n">Decimal</span><span class="p">(</span><span class="mi">7</span><span class="p">)</span>
|
||||
<span class="go">Decimal('0.142857142857142857142857142857142857')</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">11. Brief Tour of the Standard Library — Part II</a><ul>
|
||||
<li><a class="reference internal" href="#output-formatting">11.1. Output Formatting</a></li>
|
||||
<li><a class="reference internal" href="#templating">11.2. Templating</a></li>
|
||||
<li><a class="reference internal" href="#working-with-binary-data-record-layouts">11.3. Working with Binary Data Record Layouts</a></li>
|
||||
<li><a class="reference internal" href="#multi-threading">11.4. Multi-threading</a></li>
|
||||
<li><a class="reference internal" href="#logging">11.5. Logging</a></li>
|
||||
<li><a class="reference internal" href="#weak-references">11.6. Weak References</a></li>
|
||||
<li><a class="reference internal" href="#tools-for-working-with-lists">11.7. Tools for Working with Lists</a></li>
|
||||
<li><a class="reference internal" href="#decimal-floating-point-arithmetic">11.8. Decimal Floating-Point Arithmetic</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="stdlib.html"
|
||||
title="previous chapter"><span class="section-number">10. </span>Brief Tour of the Standard Library</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="venv.html"
|
||||
title="next chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/stdlib2.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="venv.html" title="12. Virtual Environments and Packages"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib.html" title="10. Brief Tour of the Standard Library"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
508
Dependencies/Python/Doc/html/tutorial/venv.html
vendored
Normal file
508
Dependencies/Python/Doc/html/tutorial/venv.html
vendored
Normal file
@@ -0,0 +1,508 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="12. Virtual Environments and Packages" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/venv.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Introduction: Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because the ..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Introduction: Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because the ..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>12. Virtual Environments and Packages — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="13. What Now?" href="whatnow.html" />
|
||||
<link rel="prev" title="11. Brief Tour of the Standard Library — Part II" href="stdlib2.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/venv.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">12. Virtual Environments and Packages</a><ul>
|
||||
<li><a class="reference internal" href="#introduction">12.1. Introduction</a></li>
|
||||
<li><a class="reference internal" href="#creating-virtual-environments">12.2. Creating Virtual Environments</a></li>
|
||||
<li><a class="reference internal" href="#managing-packages-with-pip">12.3. Managing Packages with pip</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="stdlib2.html"
|
||||
title="previous chapter"><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="whatnow.html"
|
||||
title="next chapter"><span class="section-number">13. </span>What Now?</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/venv.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="whatnow.html" title="13. What Now?"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">12. </span>Virtual Environments and Packages</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="virtual-environments-and-packages">
|
||||
<span id="tut-venv"></span><h1><span class="section-number">12. </span>Virtual Environments and Packages<a class="headerlink" href="#virtual-environments-and-packages" title="Link to this heading">¶</a></h1>
|
||||
<section id="introduction">
|
||||
<h2><span class="section-number">12.1. </span>Introduction<a class="headerlink" href="#introduction" title="Link to this heading">¶</a></h2>
|
||||
<p>Python applications will often use packages and modules that don’t
|
||||
come as part of the standard library. Applications will sometimes
|
||||
need a specific version of a library, because the application may
|
||||
require that a particular bug has been fixed or the application may be
|
||||
written using an obsolete version of the library’s interface.</p>
|
||||
<p>This means it may not be possible for one Python installation to meet
|
||||
the requirements of every application. If application A needs version
|
||||
1.0 of a particular module but application B needs version 2.0, then
|
||||
the requirements are in conflict and installing either version 1.0 or 2.0
|
||||
will leave one application unable to run.</p>
|
||||
<p>The solution for this problem is to create a <a class="reference internal" href="../glossary.html#term-virtual-environment"><span class="xref std std-term">virtual environment</span></a>, a
|
||||
self-contained directory tree that contains a Python installation for a
|
||||
particular version of Python, plus a number of additional packages.</p>
|
||||
<p>Different applications can then use different virtual environments.
|
||||
To resolve the earlier example of conflicting requirements,
|
||||
application A can have its own virtual environment with version 1.0
|
||||
installed while application B has another virtual environment with version 2.0.
|
||||
If application B requires a library be upgraded to version 3.0, this will
|
||||
not affect application A’s environment.</p>
|
||||
</section>
|
||||
<section id="creating-virtual-environments">
|
||||
<h2><span class="section-number">12.2. </span>Creating Virtual Environments<a class="headerlink" href="#creating-virtual-environments" title="Link to this heading">¶</a></h2>
|
||||
<p>The module used to create and manage virtual environments is called
|
||||
<a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a>. <a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a> will install the Python version from which
|
||||
the command was run (as reported by the <a class="reference internal" href="../using/cmdline.html#cmdoption-version"><code class="xref std std-option docutils literal notranslate"><span class="pre">--version</span></code></a> option).
|
||||
For instance, executing the command with <code class="docutils literal notranslate"><span class="pre">python3.12</span></code> will install
|
||||
version 3.12.</p>
|
||||
<p>To create a virtual environment, decide upon a directory where you want to
|
||||
place it, and run the <a class="reference internal" href="../library/venv.html#module-venv" title="venv: Creation of virtual environments."><code class="xref py py-mod docutils literal notranslate"><span class="pre">venv</span></code></a> module as a script with the directory path:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">python</span> <span class="o">-</span><span class="n">m</span> <span class="n">venv</span> <span class="n">tutorial</span><span class="o">-</span><span class="n">env</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>This will create the <code class="docutils literal notranslate"><span class="pre">tutorial-env</span></code> directory if it doesn’t exist,
|
||||
and also create directories inside it containing a copy of the Python
|
||||
interpreter and various supporting files.</p>
|
||||
<p>A common directory location for a virtual environment is <code class="docutils literal notranslate"><span class="pre">.venv</span></code>.
|
||||
This name keeps the directory typically hidden in your shell and thus
|
||||
out of the way while giving it a name that explains why the directory
|
||||
exists. It also prevents clashing with <code class="docutils literal notranslate"><span class="pre">.env</span></code> environment variable
|
||||
definition files that some tooling supports.</p>
|
||||
<p>Once you’ve created a virtual environment, you may activate it.</p>
|
||||
<p>On Windows, run:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">tutorial</span><span class="o">-</span><span class="n">env</span>\<span class="n">Scripts</span>\<span class="n">activate</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>On Unix or MacOS, run:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">source</span> <span class="n">tutorial</span><span class="o">-</span><span class="n">env</span><span class="o">/</span><span class="nb">bin</span><span class="o">/</span><span class="n">activate</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>(This script is written for the bash shell. If you use the
|
||||
<strong class="program">csh</strong> or <strong class="program">fish</strong> shells, there are alternate
|
||||
<code class="docutils literal notranslate"><span class="pre">activate.csh</span></code> and <code class="docutils literal notranslate"><span class="pre">activate.fish</span></code> scripts you should use
|
||||
instead.)</p>
|
||||
<p>Activating the virtual environment will change your shell’s prompt to show what
|
||||
virtual environment you’re using, and modify the environment so that running
|
||||
<code class="docutils literal notranslate"><span class="pre">python</span></code> will get you that particular version and installation of Python.
|
||||
For example:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span>$<span class="w"> </span><span class="nb">source</span><span class="w"> </span>~/envs/tutorial-env/bin/activate
|
||||
<span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python
|
||||
Python<span class="w"> </span><span class="m">3</span>.5.1<span class="w"> </span><span class="o">(</span>default,<span class="w"> </span>May<span class="w"> </span><span class="m">6</span><span class="w"> </span><span class="m">2016</span>,<span class="w"> </span><span class="m">10</span>:59:36<span class="o">)</span>
|
||||
<span class="w"> </span>...
|
||||
>>><span class="w"> </span>import<span class="w"> </span>sys
|
||||
>>><span class="w"> </span>sys.path
|
||||
<span class="o">[</span><span class="s1">''</span>,<span class="w"> </span><span class="s1">'/usr/local/lib/python35.zip'</span>,<span class="w"> </span>...,
|
||||
<span class="s1">'~/envs/tutorial-env/lib/python3.5/site-packages'</span><span class="o">]</span>
|
||||
>>>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>To deactivate a virtual environment, type:</p>
|
||||
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">deactivate</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>into the terminal.</p>
|
||||
</section>
|
||||
<section id="managing-packages-with-pip">
|
||||
<h2><span class="section-number">12.3. </span>Managing Packages with pip<a class="headerlink" href="#managing-packages-with-pip" title="Link to this heading">¶</a></h2>
|
||||
<p>You can install, upgrade, and remove packages using a program called
|
||||
<strong class="program">pip</strong>. By default <code class="docutils literal notranslate"><span class="pre">pip</span></code> will install packages from the <a class="reference external" href="https://pypi.org">Python
|
||||
Package Index</a>. You can browse the Python
|
||||
Package Index by going to it in your web browser.</p>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">pip</span></code> has a number of subcommands: “install”, “uninstall”,
|
||||
“freeze”, etc. (Consult the <a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a> guide for
|
||||
complete documentation for <code class="docutils literal notranslate"><span class="pre">pip</span></code>.)</p>
|
||||
<p>You can install the latest version of a package by specifying a package’s name:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span>novas
|
||||
Collecting<span class="w"> </span>novas
|
||||
<span class="w"> </span>Downloading<span class="w"> </span>novas-3.1.1.3.tar.gz<span class="w"> </span><span class="o">(</span>136kB<span class="o">)</span>
|
||||
Installing<span class="w"> </span>collected<span class="w"> </span>packages:<span class="w"> </span>novas
|
||||
<span class="w"> </span>Running<span class="w"> </span>setup.py<span class="w"> </span>install<span class="w"> </span><span class="k">for</span><span class="w"> </span>novas
|
||||
Successfully<span class="w"> </span>installed<span class="w"> </span>novas-3.1.1.3
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>You can also install a specific version of a package by giving the
|
||||
package name followed by <code class="docutils literal notranslate"><span class="pre">==</span></code> and the version number:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span><span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.6.0
|
||||
Collecting<span class="w"> </span><span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.6.0
|
||||
<span class="w"> </span>Using<span class="w"> </span>cached<span class="w"> </span>requests-2.6.0-py2.py3-none-any.whl
|
||||
Installing<span class="w"> </span>collected<span class="w"> </span>packages:<span class="w"> </span>requests
|
||||
Successfully<span class="w"> </span>installed<span class="w"> </span>requests-2.6.0
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>If you re-run this command, <code class="docutils literal notranslate"><span class="pre">pip</span></code> will notice that the requested
|
||||
version is already installed and do nothing. You can supply a
|
||||
different version number to get that version, or you can run <code class="docutils literal notranslate"><span class="pre">python</span>
|
||||
<span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">install</span> <span class="pre">--upgrade</span></code> to upgrade the package to the latest version:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span>--upgrade<span class="w"> </span>requests
|
||||
Collecting<span class="w"> </span>requests
|
||||
Installing<span class="w"> </span>collected<span class="w"> </span>packages:<span class="w"> </span>requests
|
||||
<span class="w"> </span>Found<span class="w"> </span>existing<span class="w"> </span>installation:<span class="w"> </span>requests<span class="w"> </span><span class="m">2</span>.6.0
|
||||
<span class="w"> </span>Uninstalling<span class="w"> </span>requests-2.6.0:
|
||||
<span class="w"> </span>Successfully<span class="w"> </span>uninstalled<span class="w"> </span>requests-2.6.0
|
||||
Successfully<span class="w"> </span>installed<span class="w"> </span>requests-2.7.0
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">uninstall</span></code> followed by one or more package names will
|
||||
remove the packages from the virtual environment.</p>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">show</span></code> will display information about a particular package:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>show<span class="w"> </span>requests
|
||||
---
|
||||
Metadata-Version:<span class="w"> </span><span class="m">2</span>.0
|
||||
Name:<span class="w"> </span>requests
|
||||
Version:<span class="w"> </span><span class="m">2</span>.7.0
|
||||
Summary:<span class="w"> </span>Python<span class="w"> </span>HTTP<span class="w"> </span><span class="k">for</span><span class="w"> </span>Humans.
|
||||
Home-page:<span class="w"> </span>http://python-requests.org
|
||||
Author:<span class="w"> </span>Kenneth<span class="w"> </span>Reitz
|
||||
Author-email:<span class="w"> </span>me@kennethreitz.com
|
||||
License:<span class="w"> </span>Apache<span class="w"> </span><span class="m">2</span>.0
|
||||
Location:<span class="w"> </span>/Users/akuchling/envs/tutorial-env/lib/python3.4/site-packages
|
||||
Requires:
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">list</span></code> will display all of the packages installed in
|
||||
the virtual environment:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>list
|
||||
novas<span class="w"> </span><span class="o">(</span><span class="m">3</span>.1.1.3<span class="o">)</span>
|
||||
numpy<span class="w"> </span><span class="o">(</span><span class="m">1</span>.9.2<span class="o">)</span>
|
||||
pip<span class="w"> </span><span class="o">(</span><span class="m">7</span>.0.3<span class="o">)</span>
|
||||
requests<span class="w"> </span><span class="o">(</span><span class="m">2</span>.7.0<span class="o">)</span>
|
||||
setuptools<span class="w"> </span><span class="o">(</span><span class="m">16</span>.0<span class="o">)</span>
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">freeze</span></code> will produce a similar list of the installed packages,
|
||||
but the output uses the format that <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">pip</span> <span class="pre">install</span></code> expects.
|
||||
A common convention is to put this list in a <code class="docutils literal notranslate"><span class="pre">requirements.txt</span></code> file:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>freeze<span class="w"> </span>><span class="w"> </span>requirements.txt
|
||||
<span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>cat<span class="w"> </span>requirements.txt
|
||||
<span class="nv">novas</span><span class="o">==</span><span class="m">3</span>.1.1.3
|
||||
<span class="nv">numpy</span><span class="o">==</span><span class="m">1</span>.9.2
|
||||
<span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.7.0
|
||||
</pre></div>
|
||||
</div>
|
||||
<p>The <code class="docutils literal notranslate"><span class="pre">requirements.txt</span></code> can then be committed to version control and
|
||||
shipped as part of an application. Users can then install all the
|
||||
necessary packages with <code class="docutils literal notranslate"><span class="pre">install</span> <span class="pre">-r</span></code>:</p>
|
||||
<div class="highlight-bash notranslate"><div class="highlight"><pre><span></span><span class="o">(</span>tutorial-env<span class="o">)</span><span class="w"> </span>$<span class="w"> </span>python<span class="w"> </span>-m<span class="w"> </span>pip<span class="w"> </span>install<span class="w"> </span>-r<span class="w"> </span>requirements.txt
|
||||
Collecting<span class="w"> </span><span class="nv">novas</span><span class="o">==</span><span class="m">3</span>.1.1.3<span class="w"> </span><span class="o">(</span>from<span class="w"> </span>-r<span class="w"> </span>requirements.txt<span class="w"> </span><span class="o">(</span>line<span class="w"> </span><span class="m">1</span><span class="o">))</span>
|
||||
<span class="w"> </span>...
|
||||
Collecting<span class="w"> </span><span class="nv">numpy</span><span class="o">==</span><span class="m">1</span>.9.2<span class="w"> </span><span class="o">(</span>from<span class="w"> </span>-r<span class="w"> </span>requirements.txt<span class="w"> </span><span class="o">(</span>line<span class="w"> </span><span class="m">2</span><span class="o">))</span>
|
||||
<span class="w"> </span>...
|
||||
Collecting<span class="w"> </span><span class="nv">requests</span><span class="o">==</span><span class="m">2</span>.7.0<span class="w"> </span><span class="o">(</span>from<span class="w"> </span>-r<span class="w"> </span>requirements.txt<span class="w"> </span><span class="o">(</span>line<span class="w"> </span><span class="m">3</span><span class="o">))</span>
|
||||
<span class="w"> </span>...
|
||||
Installing<span class="w"> </span>collected<span class="w"> </span>packages:<span class="w"> </span>novas,<span class="w"> </span>numpy,<span class="w"> </span>requests
|
||||
<span class="w"> </span>Running<span class="w"> </span>setup.py<span class="w"> </span>install<span class="w"> </span><span class="k">for</span><span class="w"> </span>novas
|
||||
Successfully<span class="w"> </span>installed<span class="w"> </span>novas-3.1.1.3<span class="w"> </span>numpy-1.9.2<span class="w"> </span>requests-2.7.0
|
||||
</pre></div>
|
||||
</div>
|
||||
<p><code class="docutils literal notranslate"><span class="pre">pip</span></code> has many more options. Consult the <a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a>
|
||||
guide for complete documentation for <code class="docutils literal notranslate"><span class="pre">pip</span></code>. When you’ve written
|
||||
a package and want to make it available on the Python Package Index,
|
||||
consult the <a class="reference external" href="https://packaging.python.org/en/latest/tutorials/packaging-projects/">Python packaging user guide</a>.</p>
|
||||
</section>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h3><a href="../contents.html">Table of Contents</a></h3>
|
||||
<ul>
|
||||
<li><a class="reference internal" href="#">12. Virtual Environments and Packages</a><ul>
|
||||
<li><a class="reference internal" href="#introduction">12.1. Introduction</a></li>
|
||||
<li><a class="reference internal" href="#creating-virtual-environments">12.2. Creating Virtual Environments</a></li>
|
||||
<li><a class="reference internal" href="#managing-packages-with-pip">12.3. Managing Packages with pip</a></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
</div>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="stdlib2.html"
|
||||
title="previous chapter"><span class="section-number">11. </span>Brief Tour of the Standard Library — Part II</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="whatnow.html"
|
||||
title="next chapter"><span class="section-number">13. </span>What Now?</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/venv.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="whatnow.html" title="13. What Now?"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="stdlib2.html" title="11. Brief Tour of the Standard Library — Part II"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">12. </span>Virtual Environments and Packages</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
371
Dependencies/Python/Doc/html/tutorial/whatnow.html
vendored
Normal file
371
Dependencies/Python/Doc/html/tutorial/whatnow.html
vendored
Normal file
@@ -0,0 +1,371 @@
|
||||
<!DOCTYPE html>
|
||||
|
||||
<html lang="en" data-content_root="../">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta property="og:title" content="13. What Now?" />
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:url" content="https://docs.python.org/3/tutorial/whatnow.html" />
|
||||
<meta property="og:site_name" content="Python documentation" />
|
||||
<meta property="og:description" content="Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world problems. Where should you go to learn more? This tutori..." />
|
||||
<meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
|
||||
<meta property="og:image:alt" content="Python documentation" />
|
||||
<meta name="description" content="Reading this tutorial has probably reinforced your interest in using Python — you should be eager to apply Python to solving your real-world problems. Where should you go to learn more? This tutori..." />
|
||||
<meta property="og:image:width" content="200">
|
||||
<meta property="og:image:height" content="200">
|
||||
<meta name="theme-color" content="#3776ab">
|
||||
|
||||
<title>13. What Now? — Python 3.13.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />
|
||||
<link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=23252803" />
|
||||
<link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />
|
||||
|
||||
<script src="../_static/documentation_options.js?v=5d57ca2d"></script>
|
||||
<script src="../_static/doctools.js?v=9bcbadda"></script>
|
||||
<script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
|
||||
|
||||
<script src="../_static/sidebar.js"></script>
|
||||
|
||||
<link rel="search" type="application/opensearchdescription+xml"
|
||||
title="Search within Python 3.13.3 documentation"
|
||||
href="../_static/opensearch.xml"/>
|
||||
<link rel="author" title="About these documents" href="../about.html" />
|
||||
<link rel="index" title="Index" href="../genindex.html" />
|
||||
<link rel="search" title="Search" href="../search.html" />
|
||||
<link rel="copyright" title="Copyright" href="../copyright.html" />
|
||||
<link rel="next" title="14. Interactive Input Editing and History Substitution" href="interactive.html" />
|
||||
<link rel="prev" title="12. Virtual Environments and Packages" href="venv.html" />
|
||||
|
||||
<link rel="canonical" href="https://docs.python.org/3/tutorial/whatnow.html">
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
<style>
|
||||
@media only screen {
|
||||
table.full-width-table {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
|
||||
<link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
|
||||
<script type="text/javascript" src="../_static/copybutton.js"></script>
|
||||
<script type="text/javascript" src="../_static/menu.js"></script>
|
||||
<script type="text/javascript" src="../_static/search-focus.js"></script>
|
||||
<script type="text/javascript" src="../_static/themetoggle.js"></script>
|
||||
<script type="text/javascript" src="../_static/rtd_switcher.js"></script>
|
||||
<meta name="readthedocs-addons-api-version" content="1">
|
||||
|
||||
</head>
|
||||
<body>
|
||||
<div class="mobile-nav">
|
||||
<input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
|
||||
aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
|
||||
<nav class="nav-content" role="navigation">
|
||||
<label for="menuToggler" class="toggler__label">
|
||||
<span></span>
|
||||
</label>
|
||||
<span class="nav-items-wrapper">
|
||||
<a href="https://www.python.org/" class="nav-logo">
|
||||
<img src="../_static/py.svg" alt="Python logo"/>
|
||||
</a>
|
||||
<span class="version_switcher_placeholder"></span>
|
||||
<form role="search" class="search" action="../search.html" method="get">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
|
||||
<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>
|
||||
</svg>
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
|
||||
<input type="submit" value="Go"/>
|
||||
</form>
|
||||
</span>
|
||||
</nav>
|
||||
<div class="menu-wrapper">
|
||||
<nav class="menu" role="navigation" aria-label="main navigation">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label>
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="venv.html"
|
||||
title="previous chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="interactive.html"
|
||||
title="next chapter"><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/whatnow.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
accesskey="I">index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
|
||||
accesskey="N">next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="venv.html" title="12. Virtual Environments and Packages"
|
||||
accesskey="P">previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">13. </span>What Now?</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="document">
|
||||
<div class="documentwrapper">
|
||||
<div class="bodywrapper">
|
||||
<div class="body" role="main">
|
||||
|
||||
<section id="what-now">
|
||||
<span id="tut-whatnow"></span><h1><span class="section-number">13. </span>What Now?<a class="headerlink" href="#what-now" title="Link to this heading">¶</a></h1>
|
||||
<p>Reading this tutorial has probably reinforced your interest in using Python —
|
||||
you should be eager to apply Python to solving your real-world problems. Where
|
||||
should you go to learn more?</p>
|
||||
<p>This tutorial is part of Python’s documentation set. Some other documents in
|
||||
the set are:</p>
|
||||
<ul>
|
||||
<li><p><a class="reference internal" href="../library/index.html#library-index"><span class="std std-ref">The Python Standard Library</span></a>:</p>
|
||||
<p>You should browse through this manual, which gives complete (though terse)
|
||||
reference material about types, functions, and the modules in the standard
|
||||
library. The standard Python distribution includes a <em>lot</em> of additional code.
|
||||
There are modules to read Unix mailboxes, retrieve documents via HTTP, generate
|
||||
random numbers, parse command-line options, compress data,
|
||||
and many other tasks. Skimming through the Library Reference will give you an
|
||||
idea of what’s available.</p>
|
||||
</li>
|
||||
<li><p><a class="reference internal" href="../installing/index.html#installing-index"><span class="std std-ref">Installing Python Modules</span></a> explains how to install additional modules written
|
||||
by other Python users.</p></li>
|
||||
<li><p><a class="reference internal" href="../reference/index.html#reference-index"><span class="std std-ref">The Python Language Reference</span></a>: A detailed explanation of Python’s syntax and
|
||||
semantics. It’s heavy reading, but is useful as a complete guide to the
|
||||
language itself.</p></li>
|
||||
</ul>
|
||||
<p>More Python resources:</p>
|
||||
<ul class="simple">
|
||||
<li><p><a class="reference external" href="https://www.python.org">https://www.python.org</a>: The major Python web site. It contains code,
|
||||
documentation, and pointers to Python-related pages around the web.</p></li>
|
||||
<li><p><a class="reference external" href="https://docs.python.org">https://docs.python.org</a>: Fast access to Python’s documentation.</p></li>
|
||||
<li><p><a class="reference external" href="https://pypi.org">https://pypi.org</a>: The Python Package Index, previously also nicknamed
|
||||
the Cheese Shop <a class="footnote-reference brackets" href="#id2" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a>, is an index of user-created Python modules that are available
|
||||
for download. Once you begin releasing code, you can register it here so that
|
||||
others can find it.</p></li>
|
||||
<li><p><a class="reference external" href="https://code.activestate.com/recipes/langs/python/">https://code.activestate.com/recipes/langs/python/</a>: The Python Cookbook is a
|
||||
sizable collection of code examples, larger modules, and useful scripts.
|
||||
Particularly notable contributions are collected in a book also titled Python
|
||||
Cookbook (O’Reilly & Associates, ISBN 0-596-00797-3.)</p></li>
|
||||
<li><p><a class="reference external" href="https://pyvideo.org">https://pyvideo.org</a> collects links to Python-related videos from
|
||||
conferences and user-group meetings.</p></li>
|
||||
<li><p><a class="reference external" href="https://scipy.org">https://scipy.org</a>: The Scientific Python project includes modules for fast
|
||||
array computations and manipulations plus a host of packages for such
|
||||
things as linear algebra, Fourier transforms, non-linear solvers,
|
||||
random number distributions, statistical analysis and the like.</p></li>
|
||||
</ul>
|
||||
<p>For Python-related questions and problem reports, you can post to the newsgroup
|
||||
<em class="newsgroup">comp.lang.python</em>, or send them to the mailing list at
|
||||
<a class="reference external" href="mailto:python-list%40python.org">python-list<span>@</span>python<span>.</span>org</a>. The newsgroup and mailing list are gatewayed, so
|
||||
messages posted to one will automatically be forwarded to the other. There are
|
||||
hundreds of postings a day, asking (and
|
||||
answering) questions, suggesting new features, and announcing new modules.
|
||||
Mailing list archives are available at <a class="reference external" href="https://mail.python.org/pipermail/">https://mail.python.org/pipermail/</a>.</p>
|
||||
<p>Before posting, be sure to check the list of
|
||||
<a class="reference internal" href="../faq/index.html#faq-index"><span class="std std-ref">Frequently Asked Questions</span></a> (also called the FAQ). The
|
||||
FAQ answers many of the questions that come up again and again, and may
|
||||
already contain the solution for your problem.</p>
|
||||
<p class="rubric">Footnotes</p>
|
||||
<aside class="footnote-list brackets">
|
||||
<aside class="footnote brackets" id="id2" role="doc-footnote">
|
||||
<span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
|
||||
<p>“Cheese Shop” is a Monty Python’s sketch: a customer enters a cheese shop,
|
||||
but whatever cheese he asks for, the clerk says it’s missing.</p>
|
||||
</aside>
|
||||
</aside>
|
||||
</section>
|
||||
|
||||
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="sphinxsidebar" role="navigation" aria-label="Main">
|
||||
<div class="sphinxsidebarwrapper">
|
||||
<div>
|
||||
<h4>Previous topic</h4>
|
||||
<p class="topless"><a href="venv.html"
|
||||
title="previous chapter"><span class="section-number">12. </span>Virtual Environments and Packages</a></p>
|
||||
</div>
|
||||
<div>
|
||||
<h4>Next topic</h4>
|
||||
<p class="topless"><a href="interactive.html"
|
||||
title="next chapter"><span class="section-number">14. </span>Interactive Input Editing and History Substitution</a></p>
|
||||
</div>
|
||||
<div role="note" aria-label="source link">
|
||||
<h3>This Page</h3>
|
||||
<ul class="this-page-menu">
|
||||
<li><a href="../bugs.html">Report a Bug</a></li>
|
||||
<li>
|
||||
<a href="https://github.com/python/cpython/blob/main/Doc/tutorial/whatnow.rst"
|
||||
rel="nofollow">Show Source
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div id="sidebarbutton" title="Collapse sidebar">
|
||||
<span>«</span>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div class="clearer"></div>
|
||||
</div>
|
||||
<div class="related" role="navigation" aria-label="Related">
|
||||
<h3>Navigation</h3>
|
||||
<ul>
|
||||
<li class="right" style="margin-right: 10px">
|
||||
<a href="../genindex.html" title="General Index"
|
||||
>index</a></li>
|
||||
<li class="right" >
|
||||
<a href="../py-modindex.html" title="Python Module Index"
|
||||
>modules</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="interactive.html" title="14. Interactive Input Editing and History Substitution"
|
||||
>next</a> |</li>
|
||||
<li class="right" >
|
||||
<a href="venv.html" title="12. Virtual Environments and Packages"
|
||||
>previous</a> |</li>
|
||||
|
||||
<li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
|
||||
<li><a href="https://www.python.org/">Python</a> »</li>
|
||||
<li class="switchers">
|
||||
<div class="language_switcher_placeholder"></div>
|
||||
<div class="version_switcher_placeholder"></div>
|
||||
</li>
|
||||
<li>
|
||||
|
||||
</li>
|
||||
<li id="cpython-language-and-version">
|
||||
<a href="../index.html">3.13.3 Documentation</a> »
|
||||
</li>
|
||||
|
||||
<li class="nav-item nav-item-1"><a href="index.html" >The Python Tutorial</a> »</li>
|
||||
<li class="nav-item nav-item-this"><a href=""><span class="section-number">13. </span>What Now?</a></li>
|
||||
<li class="right">
|
||||
|
||||
|
||||
<div class="inline-search" role="search">
|
||||
<form class="inline-search" action="../search.html" method="get">
|
||||
<input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
|
||||
<input type="submit" value="Go" />
|
||||
</form>
|
||||
</div>
|
||||
|
|
||||
</li>
|
||||
<li class="right">
|
||||
<label class="theme-selector-label">
|
||||
Theme
|
||||
<select class="theme-selector" oninput="activateTheme(this.value)">
|
||||
<option value="auto" selected>Auto</option>
|
||||
<option value="light">Light</option>
|
||||
<option value="dark">Dark</option>
|
||||
</select>
|
||||
</label> |</li>
|
||||
|
||||
</ul>
|
||||
</div>
|
||||
<div class="footer">
|
||||
©
|
||||
<a href="../copyright.html">
|
||||
|
||||
Copyright
|
||||
|
||||
</a>
|
||||
2001-2025, Python Software Foundation.
|
||||
<br />
|
||||
This page is licensed under the Python Software Foundation License Version 2.
|
||||
<br />
|
||||
Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
|
||||
<br />
|
||||
|
||||
See <a href="/license.html">History and License</a> for more information.<br />
|
||||
|
||||
|
||||
<br />
|
||||
|
||||
The Python Software Foundation is a non-profit corporation.
|
||||
<a href="https://www.python.org/psf/donations/">Please donate.</a>
|
||||
<br />
|
||||
<br />
|
||||
Last updated on Apr 08, 2025 (14:33 UTC).
|
||||
|
||||
<a href="/bugs.html">Found a bug</a>?
|
||||
|
||||
<br />
|
||||
|
||||
Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user