CINXE.COM

3. Data model — Python 3.13.0 documentation

<!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. Data model" /> <meta property="og:type" content="website" /> <meta property="og:url" content="https://docs.python.org/3/reference/datamodel.html" /> <meta property="og:site_name" content="Python documentation" /> <meta property="og:description" content="Objects, values and types: Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von ..." /> <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="Objects, values and types: Objects are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von ..." /> <meta property="og:image:width" content="200" /> <meta property="og:image:height" content="200" /> <meta name="theme-color" content="#3776ab" /> <title>3. Data model &#8212; Python 3.13.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" /> <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=41b4f12d" /> <link rel="stylesheet" type="text/css" href="../_static/sidebar-wrap.css?v=65806c5a" /> <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" /> <script src="../_static/documentation_options.js?v=6aaf4047"></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.0 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. Execution model" href="executionmodel.html" /> <link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" /> <script defer data-domain="docs.python.org" src="https://plausible.io/js/script.js"></script> <link rel="canonical" href="https://docs.python.org/3/reference/datamodel.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. Data model</a><ul> <li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li> <li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a><ul> <li><a class="reference internal" href="#none">3.2.1. None</a></li> <li><a class="reference internal" href="#notimplemented">3.2.2. NotImplemented</a></li> <li><a class="reference internal" href="#ellipsis">3.2.3. Ellipsis</a></li> <li><a class="reference internal" href="#numbers-number">3.2.4. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a><ul> <li><a class="reference internal" href="#numbers-integral">3.2.4.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a></li> <li><a class="reference internal" href="#numbers-real-float">3.2.4.2. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code> (<code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code>)</a></li> <li><a class="reference internal" href="#numbers-complex-complex">3.2.4.3. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code> (<code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code>)</a></li> </ul> </li> <li><a class="reference internal" href="#sequences">3.2.5. Sequences</a><ul> <li><a class="reference internal" href="#immutable-sequences">3.2.5.1. Immutable sequences</a></li> <li><a class="reference internal" href="#mutable-sequences">3.2.5.2. Mutable sequences</a></li> </ul> </li> <li><a class="reference internal" href="#set-types">3.2.6. Set types</a></li> <li><a class="reference internal" href="#mappings">3.2.7. Mappings</a><ul> <li><a class="reference internal" href="#dictionaries">3.2.7.1. Dictionaries</a></li> </ul> </li> <li><a class="reference internal" href="#callable-types">3.2.8. Callable types</a><ul> <li><a class="reference internal" href="#user-defined-functions">3.2.8.1. User-defined functions</a><ul> <li><a class="reference internal" href="#special-read-only-attributes">3.2.8.1.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#function.__globals__"><code class="docutils literal notranslate"><span class="pre">__globals__</span></code></a></li> <li><a class="reference internal" href="#function.__closure__"><code class="docutils literal notranslate"><span class="pre">__closure__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-writable-attributes">3.2.8.1.2. Special writable attributes</a><ul> <li><a class="reference internal" href="#function.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#function.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#function.__qualname__"><code class="docutils literal notranslate"><span class="pre">__qualname__</span></code></a></li> <li><a class="reference internal" href="#function.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> <li><a class="reference internal" href="#function.__defaults__"><code class="docutils literal notranslate"><span class="pre">__defaults__</span></code></a></li> <li><a class="reference internal" href="#function.__code__"><code class="docutils literal notranslate"><span class="pre">__code__</span></code></a></li> <li><a class="reference internal" href="#function.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> <li><a class="reference internal" href="#function.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> <li><a class="reference internal" href="#function.__kwdefaults__"><code class="docutils literal notranslate"><span class="pre">__kwdefaults__</span></code></a></li> <li><a class="reference internal" href="#function.__type_params__"><code class="docutils literal notranslate"><span class="pre">__type_params__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#instance-methods">3.2.8.2. Instance methods</a><ul> <li><a class="reference internal" href="#method.__self__"><code class="docutils literal notranslate"><span class="pre">__self__</span></code></a></li> <li><a class="reference internal" href="#method.__func__"><code class="docutils literal notranslate"><span class="pre">__func__</span></code></a></li> <li><a class="reference internal" href="#method.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#method.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#method.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#generator-functions">3.2.8.3. Generator functions</a></li> <li><a class="reference internal" href="#coroutine-functions">3.2.8.4. Coroutine functions</a></li> <li><a class="reference internal" href="#asynchronous-generator-functions">3.2.8.5. Asynchronous generator functions</a></li> <li><a class="reference internal" href="#built-in-functions">3.2.8.6. Built-in functions</a></li> <li><a class="reference internal" href="#built-in-methods">3.2.8.7. Built-in methods</a></li> <li><a class="reference internal" href="#classes">3.2.8.8. Classes</a></li> <li><a class="reference internal" href="#class-instances">3.2.8.9. Class Instances</a></li> </ul> </li> <li><a class="reference internal" href="#modules">3.2.9. Modules</a><ul> <li><a class="reference internal" href="#import-related-attributes-on-module-objects">3.2.9.1. Import-related attributes on module objects</a><ul> <li><a class="reference internal" href="#module.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#module.__spec__"><code class="docutils literal notranslate"><span class="pre">__spec__</span></code></a></li> <li><a class="reference internal" href="#module.__package__"><code class="docutils literal notranslate"><span class="pre">__package__</span></code></a></li> <li><a class="reference internal" href="#module.__loader__"><code class="docutils literal notranslate"><span class="pre">__loader__</span></code></a></li> <li><a class="reference internal" href="#module.__path__"><code class="docutils literal notranslate"><span class="pre">__path__</span></code></a></li> <li><a class="reference internal" href="#module.__file__"><code class="docutils literal notranslate"><span class="pre">__file__</span></code></a></li> <li><a class="reference internal" href="#module.__cached__"><code class="docutils literal notranslate"><span class="pre">__cached__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#other-writable-attributes-on-module-objects">3.2.9.2. Other writable attributes on module objects</a><ul> <li><a class="reference internal" href="#module.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#module.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#module-dictionaries">3.2.9.3. Module dictionaries</a><ul> <li><a class="reference internal" href="#module.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#custom-classes">3.2.10. Custom classes</a><ul> <li><a class="reference internal" href="#special-attributes">3.2.10.1. Special attributes</a><ul> <li><a class="reference internal" href="#type.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#type.__qualname__"><code class="docutils literal notranslate"><span class="pre">__qualname__</span></code></a></li> <li><a class="reference internal" href="#type.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> <li><a class="reference internal" href="#type.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> <li><a class="reference internal" href="#type.__bases__"><code class="docutils literal notranslate"><span class="pre">__bases__</span></code></a></li> <li><a class="reference internal" href="#type.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#type.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> <li><a class="reference internal" href="#type.__type_params__"><code class="docutils literal notranslate"><span class="pre">__type_params__</span></code></a></li> <li><a class="reference internal" href="#type.__static_attributes__"><code class="docutils literal notranslate"><span class="pre">__static_attributes__</span></code></a></li> <li><a class="reference internal" href="#type.__firstlineno__"><code class="docutils literal notranslate"><span class="pre">__firstlineno__</span></code></a></li> <li><a class="reference internal" href="#type.__mro__"><code class="docutils literal notranslate"><span class="pre">__mro__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-methods">3.2.10.2. Special methods</a><ul> <li><a class="reference internal" href="#type.mro"><code class="docutils literal notranslate"><span class="pre">mro()</span></code></a></li> <li><a class="reference internal" href="#type.__subclasses__"><code class="docutils literal notranslate"><span class="pre">__subclasses__()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#id4">3.2.11. Class instances</a><ul> <li><a class="reference internal" href="#id5">3.2.11.1. Special attributes</a><ul> <li><a class="reference internal" href="#object.__class__"><code class="docutils literal notranslate"><span class="pre">__class__</span></code></a></li> <li><a class="reference internal" href="#object.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#i-o-objects-also-known-as-file-objects">3.2.12. I/O objects (also known as file objects)</a></li> <li><a class="reference internal" href="#internal-types">3.2.13. Internal types</a><ul> <li><a class="reference internal" href="#code-objects">3.2.13.1. Code objects</a><ul> <li><a class="reference internal" href="#index-60">3.2.13.1.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#codeobject.co_name"><code class="docutils literal notranslate"><span class="pre">co_name</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_qualname"><code class="docutils literal notranslate"><span class="pre">co_qualname</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_argcount"><code class="docutils literal notranslate"><span class="pre">co_argcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_posonlyargcount"><code class="docutils literal notranslate"><span class="pre">co_posonlyargcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_kwonlyargcount"><code class="docutils literal notranslate"><span class="pre">co_kwonlyargcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_nlocals"><code class="docutils literal notranslate"><span class="pre">co_nlocals</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_varnames"><code class="docutils literal notranslate"><span class="pre">co_varnames</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_cellvars"><code class="docutils literal notranslate"><span class="pre">co_cellvars</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_freevars"><code class="docutils literal notranslate"><span class="pre">co_freevars</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_code"><code class="docutils literal notranslate"><span class="pre">co_code</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_consts"><code class="docutils literal notranslate"><span class="pre">co_consts</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_names"><code class="docutils literal notranslate"><span class="pre">co_names</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_filename"><code class="docutils literal notranslate"><span class="pre">co_filename</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_firstlineno"><code class="docutils literal notranslate"><span class="pre">co_firstlineno</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_lnotab"><code class="docutils literal notranslate"><span class="pre">co_lnotab</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_stacksize"><code class="docutils literal notranslate"><span class="pre">co_stacksize</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_flags"><code class="docutils literal notranslate"><span class="pre">co_flags</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#methods-on-code-objects">3.2.13.1.2. Methods on code objects</a><ul> <li><a class="reference internal" href="#codeobject.co_positions"><code class="docutils literal notranslate"><span class="pre">co_positions()</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_lines"><code class="docutils literal notranslate"><span class="pre">co_lines()</span></code></a></li> <li><a class="reference internal" href="#codeobject.replace"><code class="docutils literal notranslate"><span class="pre">replace()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#frame-objects">3.2.13.2. Frame objects</a><ul> <li><a class="reference internal" href="#index-66">3.2.13.2.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#frame.f_back"><code class="docutils literal notranslate"><span class="pre">f_back</span></code></a></li> <li><a class="reference internal" href="#frame.f_code"><code class="docutils literal notranslate"><span class="pre">f_code</span></code></a></li> <li><a class="reference internal" href="#frame.f_locals"><code class="docutils literal notranslate"><span class="pre">f_locals</span></code></a></li> <li><a class="reference internal" href="#frame.f_globals"><code class="docutils literal notranslate"><span class="pre">f_globals</span></code></a></li> <li><a class="reference internal" href="#frame.f_builtins"><code class="docutils literal notranslate"><span class="pre">f_builtins</span></code></a></li> <li><a class="reference internal" href="#frame.f_lasti"><code class="docutils literal notranslate"><span class="pre">f_lasti</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#index-67">3.2.13.2.2. Special writable attributes</a><ul> <li><a class="reference internal" href="#frame.f_trace"><code class="docutils literal notranslate"><span class="pre">f_trace</span></code></a></li> <li><a class="reference internal" href="#frame.f_trace_lines"><code class="docutils literal notranslate"><span class="pre">f_trace_lines</span></code></a></li> <li><a class="reference internal" href="#frame.f_trace_opcodes"><code class="docutils literal notranslate"><span class="pre">f_trace_opcodes</span></code></a></li> <li><a class="reference internal" href="#frame.f_lineno"><code class="docutils literal notranslate"><span class="pre">f_lineno</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#frame-object-methods">3.2.13.2.3. Frame object methods</a><ul> <li><a class="reference internal" href="#frame.clear"><code class="docutils literal notranslate"><span class="pre">clear()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#traceback-objects">3.2.13.3. Traceback objects</a><ul> <li><a class="reference internal" href="#traceback.tb_frame"><code class="docutils literal notranslate"><span class="pre">tb_frame</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_lineno"><code class="docutils literal notranslate"><span class="pre">tb_lineno</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_lasti"><code class="docutils literal notranslate"><span class="pre">tb_lasti</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_next"><code class="docutils literal notranslate"><span class="pre">tb_next</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#slice-objects">3.2.13.4. Slice objects</a><ul> <li><a class="reference internal" href="#slice.indices"><code class="docutils literal notranslate"><span class="pre">indices()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#static-method-objects">3.2.13.5. Static method objects</a></li> <li><a class="reference internal" href="#class-method-objects">3.2.13.6. Class method objects</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul> <li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a><ul> <li><a class="reference internal" href="#object.__new__"><code class="docutils literal notranslate"><span class="pre">__new__()</span></code></a></li> <li><a class="reference internal" href="#object.__init__"><code class="docutils literal notranslate"><span class="pre">__init__()</span></code></a></li> <li><a class="reference internal" href="#object.__del__"><code class="docutils literal notranslate"><span class="pre">__del__()</span></code></a></li> <li><a class="reference internal" href="#object.__repr__"><code class="docutils literal notranslate"><span class="pre">__repr__()</span></code></a></li> <li><a class="reference internal" href="#object.__str__"><code class="docutils literal notranslate"><span class="pre">__str__()</span></code></a></li> <li><a class="reference internal" href="#object.__bytes__"><code class="docutils literal notranslate"><span class="pre">__bytes__()</span></code></a></li> <li><a class="reference internal" href="#object.__format__"><code class="docutils literal notranslate"><span class="pre">__format__()</span></code></a></li> <li><a class="reference internal" href="#object.__lt__"><code class="docutils literal notranslate"><span class="pre">__lt__()</span></code></a></li> <li><a class="reference internal" href="#object.__le__"><code class="docutils literal notranslate"><span class="pre">__le__()</span></code></a></li> <li><a class="reference internal" href="#object.__eq__"><code class="docutils literal notranslate"><span class="pre">__eq__()</span></code></a></li> <li><a class="reference internal" href="#object.__ne__"><code class="docutils literal notranslate"><span class="pre">__ne__()</span></code></a></li> <li><a class="reference internal" href="#object.__gt__"><code class="docutils literal notranslate"><span class="pre">__gt__()</span></code></a></li> <li><a class="reference internal" href="#object.__ge__"><code class="docutils literal notranslate"><span class="pre">__ge__()</span></code></a></li> <li><a class="reference internal" href="#object.__hash__"><code class="docutils literal notranslate"><span class="pre">__hash__()</span></code></a></li> <li><a class="reference internal" href="#object.__bool__"><code class="docutils literal notranslate"><span class="pre">__bool__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul> <li><a class="reference internal" href="#object.__getattr__"><code class="docutils literal notranslate"><span class="pre">__getattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__getattribute__"><code class="docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a></li> <li><a class="reference internal" href="#object.__setattr__"><code class="docutils literal notranslate"><span class="pre">__setattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__delattr__"><code class="docutils literal notranslate"><span class="pre">__delattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__dir__"><code class="docutils literal notranslate"><span class="pre">__dir__()</span></code></a></li> <li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. Customizing module attribute access</a></li> <li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. Implementing Descriptors</a><ul> <li><a class="reference internal" href="#object.__get__"><code class="docutils literal notranslate"><span class="pre">__get__()</span></code></a></li> <li><a class="reference internal" href="#object.__set__"><code class="docutils literal notranslate"><span class="pre">__set__()</span></code></a></li> <li><a class="reference internal" href="#object.__delete__"><code class="docutils literal notranslate"><span class="pre">__delete__()</span></code></a></li> <li><a class="reference internal" href="#object.__objclass__"><code class="docutils literal notranslate"><span class="pre">__objclass__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. Invoking Descriptors</a></li> <li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a><ul> <li><a class="reference internal" href="#object.__slots__"><code class="docutils literal notranslate"><span class="pre">__slots__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul> <li><a class="reference internal" href="#object.__init_subclass__"><code class="docutils literal notranslate"><span class="pre">__init_subclass__()</span></code></a></li> <li><a class="reference internal" href="#object.__set_name__"><code class="docutils literal notranslate"><span class="pre">__set_name__()</span></code></a></li> <li><a class="reference internal" href="#metaclasses">3.3.3.1. Metaclasses</a></li> <li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. Resolving MRO entries</a><ul> <li><a class="reference internal" href="#object.__mro_entries__"><code class="docutils literal notranslate"><span class="pre">__mro_entries__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. Determining the appropriate metaclass</a></li> <li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. Preparing the class namespace</a></li> <li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. Executing the class body</a></li> <li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. Creating the class object</a></li> <li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. Uses for metaclasses</a></li> </ul> </li> <li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a><ul> <li><a class="reference internal" href="#type.__instancecheck__"><code class="docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a></li> <li><a class="reference internal" href="#type.__subclasscheck__"><code class="docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-generic-types">3.3.5. Emulating generic types</a><ul> <li><a class="reference internal" href="#object.__class_getitem__"><code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a></li> <li><a class="reference internal" href="#the-purpose-of-class-getitem">3.3.5.1. The purpose of <em>__class_getitem__</em></a></li> <li><a class="reference internal" href="#class-getitem-versus-getitem">3.3.5.2. <em>__class_getitem__</em> versus <em>__getitem__</em></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-callable-objects">3.3.6. Emulating callable objects</a><ul> <li><a class="reference internal" href="#object.__call__"><code class="docutils literal notranslate"><span class="pre">__call__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-container-types">3.3.7. Emulating container types</a><ul> <li><a class="reference internal" href="#object.__len__"><code class="docutils literal notranslate"><span class="pre">__len__()</span></code></a></li> <li><a class="reference internal" href="#object.__length_hint__"><code class="docutils literal notranslate"><span class="pre">__length_hint__()</span></code></a></li> <li><a class="reference internal" href="#object.__getitem__"><code class="docutils literal notranslate"><span class="pre">__getitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__setitem__"><code class="docutils literal notranslate"><span class="pre">__setitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__delitem__"><code class="docutils literal notranslate"><span class="pre">__delitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__missing__"><code class="docutils literal notranslate"><span class="pre">__missing__()</span></code></a></li> <li><a class="reference internal" href="#object.__iter__"><code class="docutils literal notranslate"><span class="pre">__iter__()</span></code></a></li> <li><a class="reference internal" href="#object.__reversed__"><code class="docutils literal notranslate"><span class="pre">__reversed__()</span></code></a></li> <li><a class="reference internal" href="#object.__contains__"><code class="docutils literal notranslate"><span class="pre">__contains__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-numeric-types">3.3.8. Emulating numeric types</a><ul> <li><a class="reference internal" href="#object.__add__"><code class="docutils literal notranslate"><span class="pre">__add__()</span></code></a></li> <li><a class="reference internal" href="#object.__sub__"><code class="docutils literal notranslate"><span class="pre">__sub__()</span></code></a></li> <li><a class="reference internal" href="#object.__mul__"><code class="docutils literal notranslate"><span class="pre">__mul__()</span></code></a></li> <li><a class="reference internal" href="#object.__matmul__"><code class="docutils literal notranslate"><span class="pre">__matmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__truediv__"><code class="docutils literal notranslate"><span class="pre">__truediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__floordiv__"><code class="docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__mod__"><code class="docutils literal notranslate"><span class="pre">__mod__()</span></code></a></li> <li><a class="reference internal" href="#object.__divmod__"><code class="docutils literal notranslate"><span class="pre">__divmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__pow__"><code class="docutils literal notranslate"><span class="pre">__pow__()</span></code></a></li> <li><a class="reference internal" href="#object.__lshift__"><code class="docutils literal notranslate"><span class="pre">__lshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rshift__"><code class="docutils literal notranslate"><span class="pre">__rshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__and__"><code class="docutils literal notranslate"><span class="pre">__and__()</span></code></a></li> <li><a class="reference internal" href="#object.__xor__"><code class="docutils literal notranslate"><span class="pre">__xor__()</span></code></a></li> <li><a class="reference internal" href="#object.__or__"><code class="docutils literal notranslate"><span class="pre">__or__()</span></code></a></li> <li><a class="reference internal" href="#object.__radd__"><code class="docutils literal notranslate"><span class="pre">__radd__()</span></code></a></li> <li><a class="reference internal" href="#object.__rsub__"><code class="docutils literal notranslate"><span class="pre">__rsub__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmul__"><code class="docutils literal notranslate"><span class="pre">__rmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmatmul__"><code class="docutils literal notranslate"><span class="pre">__rmatmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__rtruediv__"><code class="docutils literal notranslate"><span class="pre">__rtruediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__rfloordiv__"><code class="docutils literal notranslate"><span class="pre">__rfloordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmod__"><code class="docutils literal notranslate"><span class="pre">__rmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__rdivmod__"><code class="docutils literal notranslate"><span class="pre">__rdivmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__rpow__"><code class="docutils literal notranslate"><span class="pre">__rpow__()</span></code></a></li> <li><a class="reference internal" href="#object.__rlshift__"><code class="docutils literal notranslate"><span class="pre">__rlshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rrshift__"><code class="docutils literal notranslate"><span class="pre">__rrshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rand__"><code class="docutils literal notranslate"><span class="pre">__rand__()</span></code></a></li> <li><a class="reference internal" href="#object.__rxor__"><code class="docutils literal notranslate"><span class="pre">__rxor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ror__"><code class="docutils literal notranslate"><span class="pre">__ror__()</span></code></a></li> <li><a class="reference internal" href="#object.__iadd__"><code class="docutils literal notranslate"><span class="pre">__iadd__()</span></code></a></li> <li><a class="reference internal" href="#object.__isub__"><code class="docutils literal notranslate"><span class="pre">__isub__()</span></code></a></li> <li><a class="reference internal" href="#object.__imul__"><code class="docutils literal notranslate"><span class="pre">__imul__()</span></code></a></li> <li><a class="reference internal" href="#object.__imatmul__"><code class="docutils literal notranslate"><span class="pre">__imatmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__itruediv__"><code class="docutils literal notranslate"><span class="pre">__itruediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__ifloordiv__"><code class="docutils literal notranslate"><span class="pre">__ifloordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__imod__"><code class="docutils literal notranslate"><span class="pre">__imod__()</span></code></a></li> <li><a class="reference internal" href="#object.__ipow__"><code class="docutils literal notranslate"><span class="pre">__ipow__()</span></code></a></li> <li><a class="reference internal" href="#object.__ilshift__"><code class="docutils literal notranslate"><span class="pre">__ilshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__irshift__"><code class="docutils literal notranslate"><span class="pre">__irshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__iand__"><code class="docutils literal notranslate"><span class="pre">__iand__()</span></code></a></li> <li><a class="reference internal" href="#object.__ixor__"><code class="docutils literal notranslate"><span class="pre">__ixor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ior__"><code class="docutils literal notranslate"><span class="pre">__ior__()</span></code></a></li> <li><a class="reference internal" href="#object.__neg__"><code class="docutils literal notranslate"><span class="pre">__neg__()</span></code></a></li> <li><a class="reference internal" href="#object.__pos__"><code class="docutils literal notranslate"><span class="pre">__pos__()</span></code></a></li> <li><a class="reference internal" href="#object.__abs__"><code class="docutils literal notranslate"><span class="pre">__abs__()</span></code></a></li> <li><a class="reference internal" href="#object.__invert__"><code class="docutils literal notranslate"><span class="pre">__invert__()</span></code></a></li> <li><a class="reference internal" href="#object.__complex__"><code class="docutils literal notranslate"><span class="pre">__complex__()</span></code></a></li> <li><a class="reference internal" href="#object.__int__"><code class="docutils literal notranslate"><span class="pre">__int__()</span></code></a></li> <li><a class="reference internal" href="#object.__float__"><code class="docutils literal notranslate"><span class="pre">__float__()</span></code></a></li> <li><a class="reference internal" href="#object.__index__"><code class="docutils literal notranslate"><span class="pre">__index__()</span></code></a></li> <li><a class="reference internal" href="#object.__round__"><code class="docutils literal notranslate"><span class="pre">__round__()</span></code></a></li> <li><a class="reference internal" href="#object.__trunc__"><code class="docutils literal notranslate"><span class="pre">__trunc__()</span></code></a></li> <li><a class="reference internal" href="#object.__floor__"><code class="docutils literal notranslate"><span class="pre">__floor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ceil__"><code class="docutils literal notranslate"><span class="pre">__ceil__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#with-statement-context-managers">3.3.9. With Statement Context Managers</a><ul> <li><a class="reference internal" href="#object.__enter__"><code class="docutils literal notranslate"><span class="pre">__enter__()</span></code></a></li> <li><a class="reference internal" href="#object.__exit__"><code class="docutils literal notranslate"><span class="pre">__exit__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#customizing-positional-arguments-in-class-pattern-matching">3.3.10. Customizing positional arguments in class pattern matching</a><ul> <li><a class="reference internal" href="#object.__match_args__"><code class="docutils literal notranslate"><span class="pre">__match_args__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-buffer-types">3.3.11. Emulating buffer types</a><ul> <li><a class="reference internal" href="#object.__buffer__"><code class="docutils literal notranslate"><span class="pre">__buffer__()</span></code></a></li> <li><a class="reference internal" href="#object.__release_buffer__"><code class="docutils literal notranslate"><span class="pre">__release_buffer__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-method-lookup">3.3.12. Special method lookup</a></li> </ul> </li> <li><a class="reference internal" href="#coroutines">3.4. Coroutines</a><ul> <li><a class="reference internal" href="#awaitable-objects">3.4.1. Awaitable Objects</a><ul> <li><a class="reference internal" href="#object.__await__"><code class="docutils literal notranslate"><span class="pre">__await__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#coroutine-objects">3.4.2. Coroutine Objects</a><ul> <li><a class="reference internal" href="#coroutine.send"><code class="docutils literal notranslate"><span class="pre">send()</span></code></a></li> <li><a class="reference internal" href="#coroutine.throw"><code class="docutils literal notranslate"><span class="pre">throw()</span></code></a></li> <li><a class="reference internal" href="#coroutine.close"><code class="docutils literal notranslate"><span class="pre">close()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#asynchronous-iterators">3.4.3. Asynchronous Iterators</a><ul> <li><a class="reference internal" href="#object.__aiter__"><code class="docutils literal notranslate"><span class="pre">__aiter__()</span></code></a></li> <li><a class="reference internal" href="#object.__anext__"><code class="docutils literal notranslate"><span class="pre">__anext__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. Asynchronous Context Managers</a><ul> <li><a class="reference internal" href="#object.__aenter__"><code class="docutils literal notranslate"><span class="pre">__aenter__()</span></code></a></li> <li><a class="reference internal" href="#object.__aexit__"><code class="docutils literal notranslate"><span class="pre">__aexit__()</span></code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <div> <h4>Previous topic</h4> <p class="topless"><a href="lexical_analysis.html" title="previous chapter"><span class="section-number">2. </span>Lexical analysis</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="executionmodel.html" title="next chapter"><span class="section-number">4. </span>Execution model</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/reference/datamodel.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="executionmodel.html" title="4. Execution model" accesskey="N">next</a> |</li> <li class="right" > <a href="lexical_analysis.html" title="2. Lexical analysis" 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> &#187;</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.0 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>Data model</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="data-model"> <span id="datamodel"></span><h1><span class="section-number">3. </span>Data model<a class="headerlink" href="#data-model" title="Link to this heading">¶</a></h1> <section id="objects-values-and-types"> <span id="objects"></span><h2><span class="section-number">3.1. </span>Objects, values and types<a class="headerlink" href="#objects-values-and-types" title="Link to this heading">¶</a></h2> <p id="index-0"><em class="dfn">Objects</em> are Python’s abstraction for data. All data in a Python program is represented by objects or by relations between objects. (In a sense, and in conformance to Von Neumann’s model of a “stored program computer”, code is also represented by objects.)</p> <span class="target" id="index-1"></span><p>Every object has an identity, a type and a value. An object’s <em>identity</em> never changes once it has been created; you may think of it as the object’s address in memory. The <a class="reference internal" href="expressions.html#is"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">is</span></code></a> operator compares the identity of two objects; the <a class="reference internal" href="../library/functions.html#id" title="id"><code class="xref py py-func docutils literal notranslate"><span class="pre">id()</span></code></a> function returns an integer representing its identity.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> For CPython, <code class="docutils literal notranslate"><span class="pre">id(x)</span></code> is the memory address where <code class="docutils literal notranslate"><span class="pre">x</span></code> is stored.</p> </div> <p>An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> function returns an object’s type (which is an object itself). Like its identity, an object’s <em class="dfn">type</em> is also unchangeable. <a class="footnote-reference brackets" href="#id19" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p> <p>The <em>value</em> of some objects can change. Objects whose value can change are said to be <em>mutable</em>; objects whose value is unchangeable once they are created are called <em>immutable</em>. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.</p> <p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (so you should always close files explicitly).</p> </div> <p>Note that the use of the implementation’s tracing or debugging facilities may keep objects alive that would normally be collectable. Also note that catching an exception with a <a class="reference internal" href="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="compound_stmts.html#except"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">except</span></code></a> statement may keep objects alive.</p> <p>Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly close such objects. The <a class="reference internal" href="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="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> statement and the <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement provide convenient ways to do this.</p> <p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>. Examples of containers are tuples, lists and dictionaries. The references are part of a container’s value. In most cases, when we talk about the value of a container, we imply the values, not the identities of the contained objects; however, when we talk about the mutability of a container, only the identities of the immediately contained objects are implied. So, if an immutable container (like a tuple) contains a reference to a mutable object, its value changes if that mutable object is changed.</p> <p>Types affect almost all aspects of object behavior. Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. For example, after <code class="docutils literal notranslate"><span class="pre">a</span> <span class="pre">=</span> <span class="pre">1;</span> <span class="pre">b</span> <span class="pre">=</span> <span class="pre">1</span></code>, <em>a</em> and <em>b</em> may or may not refer to the same object with the value one, depending on the implementation. This is because <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> is an immutable type, so the reference to <code class="docutils literal notranslate"><span class="pre">1</span></code> can be reused. This behaviour depends on the implementation used, so should not be relied upon, but is something to be aware of when making use of object identity tests. However, after <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">[];</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code>, <em>c</em> and <em>d</em> are guaranteed to refer to two different, unique, newly created empty lists. (Note that <code class="docutils literal notranslate"><span class="pre">e</span> <span class="pre">=</span> <span class="pre">f</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the <em>same</em> object to both <em>e</em> and <em>f</em>.)</p> </section> <section id="the-standard-type-hierarchy"> <span id="types"></span><h2><span class="section-number">3.2. </span>The standard type hierarchy<a class="headerlink" href="#the-standard-type-hierarchy" title="Link to this heading">¶</a></h2> <p id="index-4">Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.), although such additions will often be provided via the standard library instead.</p> <p id="index-5">Some of the type descriptions below contain a paragraph listing ‘special attributes.’ These are attributes that provide access to the implementation and are not intended for general use. Their definition may change in the future.</p> <section id="none"> <h3><span class="section-number">3.2.1. </span>None<a class="headerlink" href="#none" title="Link to this heading">¶</a></h3> <p id="index-6">This type has a single value. There is a single object with this value. This object is accessed through the built-in name <code class="docutils literal notranslate"><span class="pre">None</span></code>. It is used to signify the absence of a value in many situations, e.g., it is returned from functions that don’t explicitly return anything. Its truth value is false.</p> </section> <section id="notimplemented"> <h3><span class="section-number">3.2.2. </span>NotImplemented<a class="headerlink" href="#notimplemented" title="Link to this heading">¶</a></h3> <p id="index-7">This type has a single value. There is a single object with this value. This object is accessed through the built-in name <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>. Numeric methods and rich comparison methods should return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) It should not be evaluated in a boolean context.</p> <p>See <a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><span class="std std-ref">Implementing the arithmetic operations</span></a> for more details.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.9: </span>Evaluating <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> in a boolean context is deprecated. While it currently evaluates as true, it will emit a <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a>. It will raise a <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> in a future version of Python.</p> </div> </section> <section id="ellipsis"> <h3><span class="section-number">3.2.3. </span>Ellipsis<a class="headerlink" href="#ellipsis" title="Link to this heading">¶</a></h3> <p id="index-8">This type has a single value. There is a single object with this value. This object is accessed through the literal <code class="docutils literal notranslate"><span class="pre">...</span></code> or the built-in name <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>. Its truth value is true.</p> </section> <section id="numbers-number"> <h3><span class="section-number">3.2.4. </span><a class="reference internal" href="../library/numbers.html#numbers.Number" title="numbers.Number"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a><a class="headerlink" href="#numbers-number" title="Link to this heading">¶</a></h3> <p id="index-9">These are created by numeric literals and returned as results by arithmetic operators and arithmetic built-in functions. Numeric objects are immutable; once created their value never changes. Python numbers are of course strongly related to mathematical numbers, but subject to the limitations of numerical representation in computers.</p> <p>The string representations of the numeric classes, computed by <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> and <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>, have the following properties:</p> <ul class="simple"> <li><p>They are valid numeric literals which, when passed to their class constructor, produce an object having the value of the original numeric.</p></li> <li><p>The representation is in base 10, when possible.</p></li> <li><p>Leading zeros, possibly excepting a single zero before a decimal point, are not shown.</p></li> <li><p>Trailing zeros, possibly excepting a single zero after a decimal point, are not shown.</p></li> <li><p>A sign is shown only when the number is negative.</p></li> </ul> <p>Python distinguishes between integers, floating-point numbers, and complex numbers:</p> <section id="numbers-integral"> <h4><span class="section-number">3.2.4.1. </span><a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a><a class="headerlink" href="#numbers-integral" title="Link to this heading">¶</a></h4> <p id="index-10">These represent elements from the mathematical set of integers (positive and negative).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p id="index-11">The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers.</p> </div> <p>There are two types of integers:</p> <dl> <dt>Integers (<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>)</dt><dd><p>These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left.</p> </dd> <dt>Booleans (<a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-class docutils literal notranslate"><span class="pre">bool</span></code></a>)</dt><dd><p id="index-12">These represent the truth values False and True. The two objects representing the values <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code> are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings <code class="docutils literal notranslate"><span class="pre">&quot;False&quot;</span></code> or <code class="docutils literal notranslate"><span class="pre">&quot;True&quot;</span></code> are returned, respectively.</p> </dd> </dl> </section> <section id="numbers-real-float"> <h4><span class="section-number">3.2.4.2. </span><a class="reference internal" href="../library/numbers.html#numbers.Real" title="numbers.Real"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code></a> (<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>)<a class="headerlink" href="#numbers-real-float" title="Link to this heading">¶</a></h4> <p id="index-13">These represent machine-level double precision floating-point numbers. You are at the mercy of the underlying machine architecture (and C or Java implementation) for the accepted range and handling of overflow. Python does not support single-precision floating-point numbers; the savings in processor and memory usage that are usually the reason for using these are dwarfed by the overhead of using objects in Python, so there is no reason to complicate the language with two kinds of floating-point numbers.</p> </section> <section id="numbers-complex-complex"> <h4><span class="section-number">3.2.4.3. </span><a class="reference internal" href="../library/numbers.html#numbers.Complex" title="numbers.Complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code></a> (<a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code></a>)<a class="headerlink" href="#numbers-complex-complex" title="Link to this heading">¶</a></h4> <p id="index-14">These represent complex numbers as a pair of machine-level double precision floating-point numbers. The same caveats apply as for floating-point numbers. The real and imaginary parts of a complex number <code class="docutils literal notranslate"><span class="pre">z</span></code> can be retrieved through the read-only attributes <code class="docutils literal notranslate"><span class="pre">z.real</span></code> and <code class="docutils literal notranslate"><span class="pre">z.imag</span></code>.</p> </section> </section> <section id="sequences"> <h3><span class="section-number">3.2.5. </span>Sequences<a class="headerlink" href="#sequences" title="Link to this heading">¶</a></h3> <p id="index-15">These represent finite ordered sets indexed by non-negative numbers. 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 number of items of a sequence. When the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1, …, <em>n</em>-1. Item <em>i</em> of sequence <em>a</em> is selected by <code class="docutils literal notranslate"><span class="pre">a[i]</span></code>. Some sequences, including built-in sequences, interpret negative subscripts by adding the sequence length. For example, <code class="docutils literal notranslate"><span class="pre">a[-2]</span></code> equals <code class="docutils literal notranslate"><span class="pre">a[n-2]</span></code>, the second to last item of sequence a with length <code class="docutils literal notranslate"><span class="pre">n</span></code>.</p> <p id="index-16">Sequences also support slicing: <code class="docutils literal notranslate"><span class="pre">a[i:j]</span></code> selects all items with index <em>k</em> such that <em>i</em> <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> <em>k</em> <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> <em>j</em>. When used as an expression, a slice is a sequence of the same type. The comment above about negative indexes also applies to negative slice positions.</p> <p>Some sequences also support “extended slicing” with a third “step” parameter: <code class="docutils literal notranslate"><span class="pre">a[i:j:k]</span></code> selects all items of <em>a</em> with index <em>x</em> where <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">i</span> <span class="pre">+</span> <span class="pre">n*k</span></code>, <em>n</em> <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> <code class="docutils literal notranslate"><span class="pre">0</span></code> and <em>i</em> <code class="docutils literal notranslate"><span class="pre">&lt;=</span></code> <em>x</em> <code class="docutils literal notranslate"><span class="pre">&lt;</span></code> <em>j</em>.</p> <p>Sequences are distinguished according to their mutability:</p> <section id="immutable-sequences"> <h4><span class="section-number">3.2.5.1. </span>Immutable sequences<a class="headerlink" href="#immutable-sequences" title="Link to this heading">¶</a></h4> <p id="index-17">An object of an immutable sequence type cannot change once it is created. (If the object contains references to other objects, these other objects may be mutable and may be changed; however, the collection of objects directly referenced by an immutable object cannot change.)</p> <p>The following types are immutable sequences:</p> <dl id="index-18"> <dt>Strings</dt><dd><p id="index-19">A string is a sequence of values that represent Unicode code points. All the code points in the range <code class="docutils literal notranslate"><span class="pre">U+0000</span> <span class="pre">-</span> <span class="pre">U+10FFFF</span></code> can be represented in a string. Python doesn’t have a <span class="c-expr sig sig-inline c"><span class="kt">char</span></span> type; instead, every code point in the string is represented as a string object with length <code class="docutils literal notranslate"><span class="pre">1</span></code>. The built-in function <a class="reference internal" href="../library/functions.html#ord" title="ord"><code class="xref py py-func docutils literal notranslate"><span class="pre">ord()</span></code></a> converts a code point from its string form to an integer in the range <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code>; <a class="reference internal" href="../library/functions.html#chr" title="chr"><code class="xref py py-func docutils literal notranslate"><span class="pre">chr()</span></code></a> converts an integer in the range <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">-</span> <span class="pre">10FFFF</span></code> to the corresponding length <code class="docutils literal notranslate"><span class="pre">1</span></code> string object. <a class="reference internal" href="../library/stdtypes.html#str.encode" title="str.encode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">str.encode()</span></code></a> can be used to convert a <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> to <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> using the given text encoding, and <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">bytes.decode()</span></code></a> can be used to achieve the opposite.</p> </dd> <dt>Tuples</dt><dd><p id="index-20">The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a ‘singleton’) can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.</p> </dd> <dt>Bytes</dt><dd><p id="index-21">A bytes object is an immutable array. The items are 8-bit bytes, represented by integers in the range 0 &lt;= x &lt; 256. Bytes literals (like <code class="docutils literal notranslate"><span class="pre">b'abc'</span></code>) and the built-in <a class="reference internal" href="../library/stdtypes.html#bytes" title="bytes"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytes()</span></code></a> constructor can be used to create bytes objects. Also, bytes objects can be decoded to strings via the <a class="reference internal" href="../library/stdtypes.html#bytes.decode" title="bytes.decode"><code class="xref py py-meth docutils literal notranslate"><span class="pre">decode()</span></code></a> method.</p> </dd> </dl> </section> <section id="mutable-sequences"> <h4><span class="section-number">3.2.5.2. </span>Mutable sequences<a class="headerlink" href="#mutable-sequences" title="Link to this heading">¶</a></h4> <p id="index-22">Mutable sequences can be changed after they are created. The subscription and slicing notations can be used as the target of assignment and <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> (delete) statements.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p id="index-24"><span id="index-23"></span>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> and <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 provide additional examples of mutable sequence types.</p> </div> <p>There are currently two intrinsic mutable sequence types:</p> <dl> <dt>Lists</dt><dd><p id="index-25">The items of a list are arbitrary Python objects. Lists are formed by placing a comma-separated list of expressions in square brackets. (Note that there are no special cases needed to form lists of length 0 or 1.)</p> </dd> <dt>Byte Arrays</dt><dd><p id="index-26">A bytearray object is a mutable array. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#bytearray" title="bytearray"><code class="xref py py-func docutils literal notranslate"><span class="pre">bytearray()</span></code></a> constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable <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.</p> </dd> </dl> </section> </section> <section id="set-types"> <h3><span class="section-number">3.2.6. </span>Set types<a class="headerlink" href="#set-types" title="Link to this heading">¶</a></h3> <p id="index-27">These represent unordered, finite sets of unique, immutable objects. As such, they cannot be indexed by any subscript. However, they can be iterated over, and 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 number of items in a set. Common uses for sets are fast membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference.</p> <p>For set elements, the same immutability rules apply as for dictionary keys. Note that numeric types obey the normal rules for numeric comparison: if two numbers compare equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>), only one of them can be contained in a set.</p> <p>There are currently two intrinsic set types:</p> <dl> <dt>Sets</dt><dd><p id="index-28">These represent a mutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-func docutils literal notranslate"><span class="pre">set()</span></code></a> constructor and can be modified afterwards by several methods, such as <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>.</p> </dd> <dt>Frozen sets</dt><dd><p id="index-29">These represent an immutable set. They are created by the built-in <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-func docutils literal notranslate"><span class="pre">frozenset()</span></code></a> constructor. As a frozenset is immutable and <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a>, it can be used again as an element of another set, or as a dictionary key.</p> </dd> </dl> </section> <section id="mappings"> <h3><span class="section-number">3.2.7. </span>Mappings<a class="headerlink" href="#mappings" title="Link to this heading">¶</a></h3> <p id="index-30">These represent finite sets of objects indexed by arbitrary index sets. The subscript notation <code class="docutils literal notranslate"><span class="pre">a[k]</span></code> selects the item indexed by <code class="docutils literal notranslate"><span class="pre">k</span></code> from the mapping <code class="docutils literal notranslate"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or <a class="reference internal" href="simple_stmts.html#del"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">del</span></code></a> statements. 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 number of items in a mapping.</p> <p>There is currently a single intrinsic mapping type:</p> <section id="dictionaries"> <h4><span class="section-number">3.2.7.1. </span>Dictionaries<a class="headerlink" href="#dictionaries" title="Link to this heading">¶</a></h4> <p id="index-31">These represent finite sets of objects indexed by nearly arbitrary values. The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant. Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (e.g., <code class="docutils literal notranslate"><span class="pre">1</span></code> and <code class="docutils literal notranslate"><span class="pre">1.0</span></code>) then they can be used interchangeably to index the same dictionary entry.</p> <p>Dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary. Replacing an existing key does not change the order, however removing a key and re-inserting it will add it to the end instead of keeping its old place.</p> <p>Dictionaries are mutable; they can be created by the <code class="docutils literal notranslate"><span class="pre">{}</span></code> notation (see section <a class="reference internal" href="expressions.html#dict"><span class="std std-ref">Dictionary displays</span></a>).</p> <p id="index-32">The extension modules <a class="reference internal" href="../library/dbm.html#module-dbm.ndbm" title="dbm.ndbm: The New Database Manager (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.ndbm</span></code></a> and <a class="reference internal" href="../library/dbm.html#module-dbm.gnu" title="dbm.gnu: GNU database manager (Unix)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">dbm.gnu</span></code></a> provide additional examples of mapping types, as does 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.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Dictionaries did not preserve insertion order in versions of Python before 3.6. In CPython 3.6, insertion order was preserved, but it was considered an implementation detail at that time rather than a language guarantee.</p> </div> </section> </section> <section id="callable-types"> <h3><span class="section-number">3.2.8. </span>Callable types<a class="headerlink" href="#callable-types" title="Link to this heading">¶</a></h3> <p id="index-33">These are the types to which the function call operation (see section <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>) can be applied:</p> <section id="user-defined-functions"> <span id="user-defined-funcs"></span><h4><span class="section-number">3.2.8.1. </span>User-defined functions<a class="headerlink" href="#user-defined-functions" title="Link to this heading">¶</a></h4> <p id="index-34">A user-defined function object is created by a function definition (see section <a class="reference internal" href="compound_stmts.html#function"><span class="std std-ref">Function definitions</span></a>). It should be called with an argument list containing the same number of items as the function’s formal parameter list.</p> <section id="special-read-only-attributes"> <h5><span class="section-number">3.2.8.1.1. </span>Special read-only attributes<a class="headerlink" href="#special-read-only-attributes" title="Link to this heading">¶</a></h5> <table class="docutils align-default" id="index-35"> <thead> <tr class="row-odd"><th class="head"><p>Attribute</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__globals__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__globals__</span></span><a class="headerlink" href="#function.__globals__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A reference to the <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> that holds the function’s <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">global variables</span></a> – the global namespace of the module in which the function was defined.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__closure__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__closure__</span></span><a class="headerlink" href="#function.__closure__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p><code class="docutils literal notranslate"><span class="pre">None</span></code> or a <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> of cells that contain bindings for the names specified in the <a class="reference internal" href="#codeobject.co_freevars" title="codeobject.co_freevars"><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_freevars</span></code></a> attribute of the function’s <a class="reference internal" href="#function.__code__" title="function.__code__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">code</span> <span class="pre">object</span></code></a>.</p> <p>A cell object has the attribute <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code>. This can be used to get the value of the cell, as well as set the value.</p> </td> </tr> </tbody> </table> </section> <section id="special-writable-attributes"> <h5><span class="section-number">3.2.8.1.2. </span>Special writable attributes<a class="headerlink" href="#special-writable-attributes" title="Link to this heading">¶</a></h5> <p id="index-36">Most of these attributes check the type of the assigned value:</p> <table class="docutils align-default"> <thead> <tr class="row-odd"><th class="head"><p>Attribute</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__doc__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__doc__</span></span><a class="headerlink" href="#function.__doc__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The function’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__name__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__name__</span></span><a class="headerlink" href="#function.__name__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The function’s name. See also: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">attributes</span></code></a>.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__qualname__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__qualname__</span></span><a class="headerlink" href="#function.__qualname__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The function’s <a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a>. See also: <a class="reference internal" href="../library/stdtypes.html#definition.__qualname__" title="definition.__qualname__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__qualname__</span> <span class="pre">attributes</span></code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.3.</span></p> </div> </td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__module__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__module__</span></span><a class="headerlink" href="#function.__module__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The name of the module the function was defined in, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__defaults__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__defaults__</span></span><a class="headerlink" href="#function.__defaults__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing default <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameter</span></a> values for those parameters that have defaults, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no parameters have a default value.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__code__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__code__</span></span><a class="headerlink" href="#function.__code__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a> representing the compiled function body.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__dict__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__dict__</span></span><a class="headerlink" href="#function.__dict__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The namespace supporting arbitrary function attributes. See also: <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span> <span class="pre">attributes</span></code></a>.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__annotations__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__annotations__</span></span><a class="headerlink" href="#function.__annotations__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> containing annotations of <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a>. The keys of the dictionary are the parameter names, and <code class="docutils literal notranslate"><span class="pre">'return'</span></code> for the return annotation, if provided. See also: <a class="reference internal" href="../howto/annotations.html#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a>.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__kwdefaults__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__kwdefaults__</span></span><a class="headerlink" href="#function.__kwdefaults__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> containing defaults for keyword-only <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a>.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="function.__type_params__"> <span class="sig-prename descclassname"><span class="pre">function.</span></span><span class="sig-name descname"><span class="pre">__type_params__</span></span><a class="headerlink" href="#function.__type_params__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the <a class="reference internal" href="compound_stmts.html#type-params"><span class="std std-ref">type parameters</span></a> of a <a class="reference internal" href="compound_stmts.html#generic-functions"><span class="std std-ref">generic function</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.12.</span></p> </div> </td> </tr> </tbody> </table> <p>Function objects also support getting and setting arbitrary attributes, which can be used, for example, to attach metadata to functions. Regular attribute dot-notation is used to get and set such attributes.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> CPython’s current implementation only supports function attributes on user-defined functions. Function attributes on <a class="reference internal" href="#builtin-functions"><span class="std std-ref">built-in functions</span></a> may be supported in the future.</p> </div> <p>Additional information about a function’s definition can be retrieved from its <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a> (accessible via the <a class="reference internal" href="#function.__code__" title="function.__code__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__code__</span></code></a> attribute).</p> </section> </section> <section id="instance-methods"> <span id="id2"></span><h4><span class="section-number">3.2.8.2. </span>Instance methods<a class="headerlink" href="#instance-methods" title="Link to this heading">¶</a></h4> <p id="index-37">An instance method object combines a class, a class instance and any callable object (normally a user-defined function).</p> <p id="index-38">Special read-only attributes:</p> <table class="docutils align-default"> <tbody> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="method.__self__"> <span class="sig-prename descclassname"><span class="pre">method.</span></span><span class="sig-name descname"><span class="pre">__self__</span></span><a class="headerlink" href="#method.__self__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Refers to the class instance object to which the method is <a class="reference internal" href="#method-binding"><span class="std std-ref">bound</span></a></p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="method.__func__"> <span class="sig-prename descclassname"><span class="pre">method.</span></span><span class="sig-name descname"><span class="pre">__func__</span></span><a class="headerlink" href="#method.__func__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Refers to the original <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a></p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="method.__doc__"> <span class="sig-prename descclassname"><span class="pre">method.</span></span><span class="sig-name descname"><span class="pre">__doc__</span></span><a class="headerlink" href="#method.__doc__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The method’s documentation (same as <a class="reference internal" href="#function.__doc__" title="function.__doc__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method.__func__.__doc__</span></code></a>). A <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-class docutils literal notranslate"><span class="pre">string</span></code></a> if the original function had a docstring, else <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="method.__name__"> <span class="sig-prename descclassname"><span class="pre">method.</span></span><span class="sig-name descname"><span class="pre">__name__</span></span><a class="headerlink" href="#method.__name__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The name of the method (same as <a class="reference internal" href="#function.__name__" title="function.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">method.__func__.__name__</span></code></a>)</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="method.__module__"> <span class="sig-prename descclassname"><span class="pre">method.</span></span><span class="sig-name descname"><span class="pre">__module__</span></span><a class="headerlink" href="#method.__module__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The name of the module the method was defined in, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p></td> </tr> </tbody> </table> <p>Methods also support accessing (but not setting) the arbitrary function attributes on the underlying <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a>.</p> <p>User-defined method objects may be created when getting an attribute of a class (perhaps via an instance of that class), if that attribute is a user-defined <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a> or a <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">classmethod</span></code></a> object.</p> <p id="method-binding">When an instance method object is created by retrieving a user-defined <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a> from a class via one of its instances, its <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a> attribute is the instance, and the method object is said to be <em>bound</em>. The new method’s <a class="reference internal" href="#method.__func__" title="method.__func__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code></a> attribute is the original function object.</p> <p>When an instance method object is created by retrieving a <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">classmethod</span></code></a> object from a class or instance, its <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a> attribute is the class itself, and its <a class="reference internal" href="#method.__func__" title="method.__func__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code></a> attribute is the function object underlying the class method.</p> <p>When an instance method object is called, the underlying function (<a class="reference internal" href="#method.__func__" title="method.__func__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__func__</span></code></a>) is called, inserting the class instance (<a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a>) in front of the argument list. For instance, when <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code> is a class which contains a definition for a function <code class="xref py py-meth docutils literal notranslate"><span class="pre">f()</span></code>, and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, calling <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> is equivalent to calling <code class="docutils literal notranslate"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p> <p>When an instance method object is derived from a <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">classmethod</span></code></a> object, the “class instance” stored in <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a> will actually be the class itself, so that calling either <code class="docutils literal notranslate"><span class="pre">x.f(1)</span></code> or <code class="docutils literal notranslate"><span class="pre">C.f(1)</span></code> is equivalent to calling <code class="docutils literal notranslate"><span class="pre">f(C,1)</span></code> where <code class="docutils literal notranslate"><span class="pre">f</span></code> is the underlying function.</p> <p>It is important to note that user-defined functions which are attributes of a class instance are not converted to bound methods; this <em>only</em> happens when the function is an attribute of the class.</p> </section> <section id="generator-functions"> <h4><span class="section-number">3.2.8.3. </span>Generator functions<a class="headerlink" href="#generator-functions" title="Link to this heading">¶</a></h4> <p id="index-39">A function or method which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement (see section <a class="reference internal" href="simple_stmts.html#yield"><span class="std std-ref">The yield statement</span></a>) is called a <em class="dfn">generator function</em>. Such a function, when called, always returns an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> object which can be used to execute the body of the function: calling the iterator’s <a class="reference internal" href="../library/stdtypes.html#iterator.__next__" title="iterator.__next__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">iterator.__next__()</span></code></a> method will cause the function to execute until it provides a value using the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement. When the function executes a <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exception is raised and the iterator will have reached the end of the set of values to be returned.</p> </section> <section id="coroutine-functions"> <h4><span class="section-number">3.2.8.4. </span>Coroutine functions<a class="headerlink" href="#coroutine-functions" title="Link to this heading">¶</a></h4> <p id="index-40">A function or method which is defined using <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> is called a <em class="dfn">coroutine function</em>. Such a function, when called, returns a <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">coroutine</span></a> object. It may contain <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expressions, as well as <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> and <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statements. See also the <a class="reference internal" href="#coroutine-objects"><span class="std std-ref">Coroutine Objects</span></a> section.</p> </section> <section id="asynchronous-generator-functions"> <h4><span class="section-number">3.2.8.5. </span>Asynchronous generator functions<a class="headerlink" href="#asynchronous-generator-functions" title="Link to this heading">¶</a></h4> <p id="index-41">A function or method which is defined using <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> and which uses the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> statement is called a <em class="dfn">asynchronous generator function</em>. Such a function, when called, returns an <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a> object which can be used in an <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement to execute the body of the function.</p> <p>Calling the asynchronous iterator’s <a class="reference internal" href="#object.__anext__" title="object.__anext__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">aiterator.__anext__</span></code></a> method will return an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> which when awaited will execute until it provides a value using the <a class="reference internal" href="simple_stmts.html#yield"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code></a> expression. When the function executes an empty <a class="reference internal" href="simple_stmts.html#return"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">return</span></code></a> statement or falls off the end, a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> exception is raised and the asynchronous iterator will have reached the end of the set of values to be yielded.</p> </section> <section id="built-in-functions"> <span id="builtin-functions"></span><h4><span class="section-number">3.2.8.6. </span>Built-in functions<a class="headerlink" href="#built-in-functions" title="Link to this heading">¶</a></h4> <p id="index-42">A built-in function object is a wrapper around a C function. Examples of built-in functions are <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> and <a class="reference internal" href="../library/math.html#math.sin" title="math.sin"><code class="xref py py-func docutils literal notranslate"><span class="pre">math.sin()</span></code></a> (<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> is a standard built-in module). The number and type of the arguments are determined by the C function. Special read-only attributes:</p> <ul class="simple"> <li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code> is the function’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable. See <a class="reference internal" href="#function.__doc__" title="function.__doc__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">function.__doc__</span></code></a>.</p></li> <li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code> is the function’s name. See <a class="reference internal" href="#function.__name__" title="function.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">function.__name__</span></code></a>.</p></li> <li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is set to <code class="docutils literal notranslate"><span class="pre">None</span></code> (but see the next item).</p></li> <li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the name of the module the function was defined in or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable. See <a class="reference internal" href="#function.__module__" title="function.__module__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">function.__module__</span></code></a>.</p></li> </ul> </section> <section id="built-in-methods"> <span id="builtin-methods"></span><h4><span class="section-number">3.2.8.7. </span>Built-in methods<a class="headerlink" href="#built-in-methods" title="Link to this heading">¶</a></h4> <p id="index-43">This is really a different disguise of a built-in function, this time containing an object passed to the C function as an implicit extra argument. An example of a built-in method is <code class="docutils literal notranslate"><span class="pre">alist.append()</span></code>, assuming <em>alist</em> is a list object. In this case, the special read-only attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code> is set to the object denoted by <em>alist</em>. (The attribute has the same semantics as it does with <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">other</span> <span class="pre">instance</span> <span class="pre">methods</span></code></a>.)</p> </section> <section id="classes"> <span id="id3"></span><h4><span class="section-number">3.2.8.8. </span>Classes<a class="headerlink" href="#classes" title="Link to this heading">¶</a></h4> <p>Classes are callable. These objects normally act as factories for new instances of themselves, but variations are possible for class types that override <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>. The arguments of the call are passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code> and, in the typical case, to <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to initialize the new instance.</p> </section> <section id="class-instances"> <h4><span class="section-number">3.2.8.9. </span>Class Instances<a class="headerlink" href="#class-instances" title="Link to this heading">¶</a></h4> <p>Instances of arbitrary classes can be made callable by defining a <a class="reference internal" href="#object.__call__" title="object.__call__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__call__()</span></code></a> method in their class.</p> </section> </section> <section id="modules"> <span id="module-objects"></span><h3><span class="section-number">3.2.9. </span>Modules<a class="headerlink" href="#modules" title="Link to this heading">¶</a></h3> <p id="index-44">Modules are a basic organizational unit of Python code, and are created by the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a> as invoked either by the <a class="reference internal" href="simple_stmts.html#import"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">import</span></code></a> statement, or by calling functions such as <a class="reference internal" href="../library/importlib.html#importlib.import_module" title="importlib.import_module"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.import_module()</span></code></a> and built-in <a class="reference internal" href="../library/functions.html#import__" title="__import__"><code class="xref py py-func docutils literal notranslate"><span class="pre">__import__()</span></code></a>. A module object has a namespace implemented by a <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> object (this is the dictionary referenced by the <a class="reference internal" href="#function.__globals__" title="function.__globals__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__globals__</span></code></a> attribute of functions defined in the module). Attribute references are translated to lookups in this dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.__dict__[&quot;x&quot;]</span></code>. A module object does not contain the code object used to initialize the module (since it isn’t needed once the initialization is done).</p> <p>Attribute assignment updates the module’s namespace dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span> <span class="pre">=</span> <span class="pre">1</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">m.__dict__[&quot;x&quot;]</span> <span class="pre">=</span> <span class="pre">1</span></code>.</p> <section id="import-related-attributes-on-module-objects"> <span id="import-mod-attrs"></span><span id="index-45"></span><h4><span class="section-number">3.2.9.1. </span>Import-related attributes on module objects<a class="headerlink" href="#import-related-attributes-on-module-objects" title="Link to this heading">¶</a></h4> <p>Module objects have the following attributes that relate to the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a>. When a module is created using the machinery associated with the import system, these attributes are filled in based on the module’s <a class="reference internal" href="../glossary.html#term-module-spec"><span class="xref std std-term">spec</span></a>, before the <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a> executes and loads the module.</p> <p>To create a module dynamically rather than using the import system, it’s recommended to use <a class="reference internal" href="../library/importlib.html#importlib.util.module_from_spec" title="importlib.util.module_from_spec"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.util.module_from_spec()</span></code></a>, which will set the various import-controlled attributes to appropriate values. It’s also possible to use the <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> constructor to create modules directly, but this technique is more error-prone, as most attributes must be manually set on the module object after it has been created when using this approach.</p> <div class="admonition caution"> <p class="admonition-title">Caution</p> <p>With the exception of <a class="reference internal" href="#module.__name__" title="module.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a>, it is <strong>strongly</strong> recommended that you rely on <a class="reference internal" href="#module.__spec__" title="module.__spec__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__</span></code></a> and its attributes instead of any of the other individual attributes listed in this subsection. Note that updating an attribute on <code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__</span></code> will not update the corresponding attribute on the module itself:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">typing</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">typing</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">typing</span><span class="o">.</span><span class="n">__spec__</span><span class="o">.</span><span class="n">name</span> <span class="go">(&#39;typing&#39;, &#39;typing&#39;)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">typing</span><span class="o">.</span><span class="n">__spec__</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">&#39;spelling&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">typing</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">typing</span><span class="o">.</span><span class="n">__spec__</span><span class="o">.</span><span class="n">name</span> <span class="go">(&#39;typing&#39;, &#39;spelling&#39;)</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">typing</span><span class="o">.</span><span class="vm">__name__</span> <span class="o">=</span> <span class="s1">&#39;keyboard_smashing&#39;</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">typing</span><span class="o">.</span><span class="vm">__name__</span><span class="p">,</span> <span class="n">typing</span><span class="o">.</span><span class="n">__spec__</span><span class="o">.</span><span class="n">name</span> <span class="go">(&#39;keyboard_smashing&#39;, &#39;spelling&#39;)</span> </pre></div> </div> </div> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__name__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__name__</span></span><a class="headerlink" href="#module.__name__" title="Link to this definition">¶</a></dt> <dd><p>The name used to uniquely identify the module in the import system. For a directly executed module, this will be set to <code class="docutils literal notranslate"><span class="pre">&quot;__main__&quot;</span></code>.</p> <p>This attribute must be set to the fully qualified name of the module. It is expected to match the value of <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.name" title="importlib.machinery.ModuleSpec.name"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__spec__.name</span></code></a>.</p> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__spec__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__spec__</span></span><a class="headerlink" href="#module.__spec__" title="Link to this definition">¶</a></dt> <dd><p>A record of the module’s import-system-related state.</p> <p>Set to the <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec" title="importlib.machinery.ModuleSpec"><code class="xref py py-class docutils literal notranslate"><span class="pre">module</span> <span class="pre">spec</span></code></a> that was used when importing the module. See <a class="reference internal" href="import.html#module-specs"><span class="std std-ref">Module specs</span></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.4.</span></p> </div> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__package__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__package__</span></span><a class="headerlink" href="#module.__package__" title="Link to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../glossary.html#term-package"><span class="xref std std-term">package</span></a> a module belongs to.</p> <p>If the module is top-level (that is, not a part of any specific package) then the attribute should be set to <code class="docutils literal notranslate"><span class="pre">''</span></code> (the empty string). Otherwise, it should be set to the name of the module’s package (which can be equal to <a class="reference internal" href="#module.__name__" title="module.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__name__</span></code></a> if the module itself is a package). See <span class="target" id="index-46"></span><a class="pep reference external" href="https://peps.python.org/pep-0366/"><strong>PEP 366</strong></a> for further details.</p> <p>This attribute is used instead of <a class="reference internal" href="#module.__name__" title="module.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a> to calculate explicit relative imports for main modules. It defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> for modules created dynamically using the <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> constructor; use <a class="reference internal" href="../library/importlib.html#importlib.util.module_from_spec" title="importlib.util.module_from_spec"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.util.module_from_spec()</span></code></a> instead to ensure the attribute is set to a <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>.</p> <p>It is <strong>strongly</strong> recommended that you use <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.parent" title="importlib.machinery.ModuleSpec.parent"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__spec__.parent</span></code></a> instead of <code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__package__</span></code>. <a class="reference internal" href="#module.__package__" title="module.__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> is now only used as a fallback if <code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.parent</span></code> is not set, and this fallback path is deprecated.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>This attribute now defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> for modules created dynamically using the <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> constructor. Previously the attribute was optional.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.6: </span>The value of <code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> is expected to be the same as <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.parent" title="importlib.machinery.ModuleSpec.parent"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.parent</span></code></a>. <a class="reference internal" href="#module.__package__" title="module.__package__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code></a> is now only used as a fallback during import resolution if <code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.parent</span></code> is not defined.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.10: </span><a class="reference internal" href="../library/exceptions.html#ImportWarning" title="ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a> is raised if an import resolution falls back to <code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> instead of <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.parent" title="importlib.machinery.ModuleSpec.parent"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.parent</span></code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>Raise <a class="reference internal" href="../library/exceptions.html#DeprecationWarning" title="DeprecationWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DeprecationWarning</span></code></a> instead of <a class="reference internal" href="../library/exceptions.html#ImportWarning" title="ImportWarning"><code class="xref py py-exc docutils literal notranslate"><span class="pre">ImportWarning</span></code></a> when falling back to <code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> during import resolution.</p> </div> <div class="deprecated-removed"> <p><span class="versionmodified deprecated">Deprecated since version 3.13, will be removed in version 3.15: </span><code class="xref py py-attr docutils literal notranslate"><span class="pre">__package__</span></code> will cease to be set or taken into consideration by the import system or standard library.</p> </div> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__loader__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__loader__</span></span><a class="headerlink" href="#module.__loader__" title="Link to this definition">¶</a></dt> <dd><p>The <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a> object that the import machinery used to load the module.</p> <p>This attribute is mostly useful for introspection, but can be used for additional loader-specific functionality, for example getting data associated with a loader.</p> <p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__loader__</span></code> defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> for modules created dynamically using the <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> constructor; use <a class="reference internal" href="../library/importlib.html#importlib.util.module_from_spec" title="importlib.util.module_from_spec"><code class="xref py py-func docutils literal notranslate"><span class="pre">importlib.util.module_from_spec()</span></code></a> instead to ensure the attribute is set to a <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a> object.</p> <p>It is <strong>strongly</strong> recommended that you use <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.loader" title="importlib.machinery.ModuleSpec.loader"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__spec__.loader</span></code></a> instead of <code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__loader__</span></code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>This attribute now defaults to <code class="docutils literal notranslate"><span class="pre">None</span></code> for modules created dynamically using the <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a> constructor. Previously the attribute was optional.</p> </div> <div class="deprecated-removed"> <p><span class="versionmodified deprecated">Deprecated since version 3.12, will be removed in version 3.16: </span>Setting <code class="xref py py-attr docutils literal notranslate"><span class="pre">__loader__</span></code> on a module while failing to set <code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.loader</span></code> is deprecated. In Python 3.16, <code class="xref py py-attr docutils literal notranslate"><span class="pre">__loader__</span></code> will cease to be set or taken into consideration by the import system or the standard library.</p> </div> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__path__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__path__</span></span><a class="headerlink" href="#module.__path__" title="Link to this definition">¶</a></dt> <dd><p>A (possibly empty) <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> of strings enumerating the locations where the package’s submodules will be found. Non-package modules should not have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__path__</span></code> attribute. See <a class="reference internal" href="import.html#package-path-rules"><span class="std std-ref">__path__ attributes on modules</span></a> for more details.</p> <p>It is <strong>strongly</strong> recommended that you use <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.submodule_search_locations" title="importlib.machinery.ModuleSpec.submodule_search_locations"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__spec__.submodule_search_locations</span></code></a> instead of <code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__path__</span></code>.</p> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__file__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__file__</span></span><a class="headerlink" href="#module.__file__" title="Link to this definition">¶</a></dt> <dd></dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__cached__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__cached__</span></span><a class="headerlink" href="#module.__cached__" title="Link to this definition">¶</a></dt> <dd><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> are both optional attributes that may or may not be set. Both attributes should be a <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> when they are available.</p> <p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> indicates the pathname of the file from which the module was loaded (if loaded from a file), or the pathname of the shared library file for extension modules loaded dynamically from a shared library. It might be missing for certain types of modules, such as C modules that are statically linked into the interpreter, and the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a> may opt to leave it unset if it has no semantic meaning (for example, a module loaded from a database).</p> <p>If <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> is set then the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> attribute might also be set, which is the path to any compiled version of the code (for example, a byte-compiled file). The file does not need to exist to set this attribute; the path can simply point to where the compiled file <em>would</em> exist (see <span class="target" id="index-47"></span><a class="pep reference external" href="https://peps.python.org/pep-3147/"><strong>PEP 3147</strong></a>).</p> <p>Note that <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> may be set even if <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> is not set. However, that scenario is quite atypical. Ultimately, the <a class="reference internal" href="../glossary.html#term-loader"><span class="xref std std-term">loader</span></a> is what makes use of the module spec provided by the <a class="reference internal" href="../glossary.html#term-finder"><span class="xref std std-term">finder</span></a> (from which <code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> are derived). So if a loader can load from a cached module but otherwise does not load from a file, that atypical scenario may be appropriate.</p> <p>It is <strong>strongly</strong> recommended that you use <a class="reference internal" href="../library/importlib.html#importlib.machinery.ModuleSpec.cached" title="importlib.machinery.ModuleSpec.cached"><code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__spec__.cached</span></code></a> instead of <code class="xref py py-attr docutils literal notranslate"><span class="pre">module.__cached__</span></code>.</p> <div class="deprecated-removed"> <p><span class="versionmodified deprecated">Deprecated since version 3.13, will be removed in version 3.15: </span>Setting <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> on a module while failing to set <code class="xref py py-attr docutils literal notranslate"><span class="pre">__spec__.cached</span></code> is deprecated. In Python 3.15, <code class="xref py py-attr docutils literal notranslate"><span class="pre">__cached__</span></code> will cease to be set or taken into consideration by the import system or standard library.</p> </div> </dd></dl> </section> <section id="other-writable-attributes-on-module-objects"> <h4><span class="section-number">3.2.9.2. </span>Other writable attributes on module objects<a class="headerlink" href="#other-writable-attributes-on-module-objects" title="Link to this heading">¶</a></h4> <p>As well as the import-related attributes listed above, module objects also have the following writable attributes:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__doc__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__doc__</span></span><a class="headerlink" href="#module.__doc__" title="Link to this definition">¶</a></dt> <dd><p>The module’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable. See also: <a class="reference internal" href="../library/stdtypes.html#definition.__doc__" title="definition.__doc__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span> <span class="pre">attributes</span></code></a>.</p> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="module.__annotations__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__annotations__</span></span><a class="headerlink" href="#module.__annotations__" title="Link to this definition">¶</a></dt> <dd><p>A dictionary containing <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a> collected during module body execution. For best practices on working with <a class="reference internal" href="#module.__annotations__" title="module.__annotations__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code></a>, please see <a class="reference internal" href="../howto/annotations.html#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a>.</p> </dd></dl> </section> <section id="module-dictionaries"> <h4><span class="section-number">3.2.9.3. </span>Module dictionaries<a class="headerlink" href="#module-dictionaries" title="Link to this heading">¶</a></h4> <p>Module objects also have the following special read-only attribute:</p> <dl class="py attribute" id="index-48"> <dt class="sig sig-object py" id="module.__dict__"> <span class="sig-prename descclassname"><span class="pre">module.</span></span><span class="sig-name descname"><span class="pre">__dict__</span></span><a class="headerlink" href="#module.__dict__" title="Link to this definition">¶</a></dt> <dd><p>The module’s namespace as a dictionary object. Uniquely among the attributes listed here, <code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code> cannot be accessed as a global variable from within a module; it can only be accessed as an attribute on module objects.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module dictionary will be cleared when the module falls out of scope even if the dictionary still has live references. To avoid this, copy the dictionary or keep the module around while using its dictionary directly.</p> </div> </dd></dl> </section> </section> <section id="custom-classes"> <span id="class-attrs-and-methods"></span><h3><span class="section-number">3.2.10. </span>Custom classes<a class="headerlink" href="#custom-classes" title="Link to this heading">¶</a></h3> <p>Custom class types are typically created by class definitions (see section <a class="reference internal" href="compound_stmts.html#class"><span class="std std-ref">Class definitions</span></a>). A class has a namespace implemented by a dictionary object. Class attribute references are translated to lookups in this dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">C.x</span></code> is translated to <code class="docutils literal notranslate"><span class="pre">C.__dict__[&quot;x&quot;]</span></code> (although there are a number of hooks which allow for other means of locating attributes). When the attribute name is not found there, the attribute search continues in the base classes. This search of the base classes uses the C3 method resolution order which behaves correctly even in the presence of ‘diamond’ inheritance structures where there are multiple inheritance paths leading back to a common ancestor. Additional details on the C3 MRO used by Python can be found at <a class="reference internal" href="../howto/mro.html#python-2-3-mro"><span class="std std-ref">The Python 2.3 Method Resolution Order</span></a>.</p> <p id="index-49">When a class attribute reference (for class <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>, say) would yield a class method object, it is transformed into an instance method object whose <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a> attribute is <code class="xref py py-class docutils literal notranslate"><span class="pre">C</span></code>. When it would yield a <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-class docutils literal notranslate"><span class="pre">staticmethod</span></code></a> object, it is transformed into the object wrapped by the static method object. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which attributes retrieved from a class may differ from those actually contained in its <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p> <p id="index-50">Class attribute assignments update the class’s dictionary, never the dictionary of a base class.</p> <p id="index-51">A class object can be called (see above) to yield a class instance (see below).</p> <section id="special-attributes"> <h4><span class="section-number">3.2.10.1. </span>Special attributes<a class="headerlink" href="#special-attributes" title="Link to this heading">¶</a></h4> <table class="docutils align-default" id="index-52"> <thead> <tr class="row-odd"><th class="head"><p>Attribute</p></th> <th class="head"><p>Meaning</p></th> </tr> </thead> <tbody> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__name__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__name__</span></span><a class="headerlink" href="#type.__name__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The class’s name. See also: <a class="reference internal" href="../library/stdtypes.html#definition.__name__" title="definition.__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span> <span class="pre">attributes</span></code></a>.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__qualname__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__qualname__</span></span><a class="headerlink" href="#type.__qualname__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The class’s <a class="reference internal" href="../glossary.html#term-qualified-name"><span class="xref std std-term">qualified name</span></a>. See also: <a class="reference internal" href="../library/stdtypes.html#definition.__qualname__" title="definition.__qualname__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__qualname__</span> <span class="pre">attributes</span></code></a>.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__module__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__module__</span></span><a class="headerlink" href="#type.__module__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The name of the module in which the class was defined.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__dict__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__dict__</span></span><a class="headerlink" href="#type.__dict__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/types.html#types.MappingProxyType" title="types.MappingProxyType"><code class="xref py py-class docutils literal notranslate"><span class="pre">mapping</span> <span class="pre">proxy</span></code></a> providing a read-only view of the class’s namespace. See also: <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span> <span class="pre">attributes</span></code></a>.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__bases__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__bases__</span></span><a class="headerlink" href="#type.__bases__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the class’s bases. In most cases, for a class defined as <code class="docutils literal notranslate"><span class="pre">class</span> <span class="pre">X(A,</span> <span class="pre">B,</span> <span class="pre">C)</span></code>, <code class="docutils literal notranslate"><span class="pre">X.__bases__</span></code> will be exactly equal to <code class="docutils literal notranslate"><span class="pre">(A,</span> <span class="pre">B,</span> <span class="pre">C)</span></code>.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__doc__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__doc__</span></span><a class="headerlink" href="#type.__doc__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The class’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined. Not inherited by subclasses.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__annotations__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__annotations__</span></span><a class="headerlink" href="#type.__annotations__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A dictionary containing <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a> collected during class body execution. For best practices on working with <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>, please see <a class="reference internal" href="../howto/annotations.html#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a>.</p> <div class="admonition caution"> <p class="admonition-title">Caution</p> <p>Accessing the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute of a class object directly may yield incorrect results in the presence of metaclasses. In addition, the attribute may not exist for some classes. Use <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a> to retrieve class annotations safely.</p> </div> </td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__type_params__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__type_params__</span></span><a class="headerlink" href="#type.__type_params__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the <a class="reference internal" href="compound_stmts.html#type-params"><span class="std std-ref">type parameters</span></a> of a <a class="reference internal" href="compound_stmts.html#generic-classes"><span class="std std-ref">generic class</span></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.12.</span></p> </div> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__static_attributes__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__static_attributes__</span></span><a class="headerlink" href="#type.__static_attributes__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing names of attributes of this class which are assigned through <code class="docutils literal notranslate"><span class="pre">self.X</span></code> from any function in its body.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.13.</span></p> </div> </td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__firstlineno__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__firstlineno__</span></span><a class="headerlink" href="#type.__firstlineno__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The line number of the first line of the class definition, including decorators. Setting the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> attribute removes the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__firstlineno__</span></code> item from the type’s dictionary.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.13.</span></p> </div> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="type.__mro__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__mro__</span></span><a class="headerlink" href="#type.__mro__" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> of classes that are considered when looking for base classes during method resolution.</p></td> </tr> </tbody> </table> </section> <section id="special-methods"> <h4><span class="section-number">3.2.10.2. </span>Special methods<a class="headerlink" href="#special-methods" title="Link to this heading">¶</a></h4> <p>In addition to the special attributes described above, all Python classes also have the following two methods available:</p> <dl class="py method"> <dt class="sig sig-object py" id="type.mro"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">mro</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#type.mro" title="Link to this definition">¶</a></dt> <dd><p>This method can be overridden by a metaclass to customize the method resolution order for its instances. It is called at class instantiation, and its result is stored in <a class="reference internal" href="#type.__mro__" title="type.__mro__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__mro__</span></code></a>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="type.__subclasses__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__subclasses__</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#type.__subclasses__" title="Link to this definition">¶</a></dt> <dd><p>Each class keeps a list of weak references to its immediate subclasses. This method returns a list of all those references still alive. The list is in definition order. Example:</p> <div class="highlight-pycon notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span> <span class="k">pass</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">B</span><span class="p">(</span><span class="n">A</span><span class="p">):</span> <span class="k">pass</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">A</span><span class="o">.</span><span class="n">__subclasses__</span><span class="p">()</span> <span class="go">[&lt;class &#39;B&#39;&gt;]</span> </pre></div> </div> </dd></dl> </section> </section> <section id="id4"> <h3><span class="section-number">3.2.11. </span>Class instances<a class="headerlink" href="#id4" title="Link to this heading">¶</a></h3> <p id="index-53">A class instance is created by calling a class object (see above). A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched. When an attribute is not found there, and the instance’s class has an attribute by that name, the search continues with the class attributes. If a class attribute is found that is a user-defined function object, it is transformed into an instance method object whose <a class="reference internal" href="#method.__self__" title="method.__self__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__self__</span></code></a> attribute is the instance. Static method and class method objects are also transformed; see above under “Classes”. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which attributes of a class retrieved via its instances may differ from the objects actually stored in the class’s <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. If no class attribute is found, and the object’s class has a <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> method, that is called to satisfy the lookup.</p> <p id="index-54">Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary. If the class has a <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> or <a class="reference internal" href="#object.__delattr__" title="object.__delattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delattr__()</span></code></a> method, this is called instead of updating the instance dictionary directly.</p> <p id="index-55">Class instances can pretend to be numbers, sequences, or mappings if they have methods with certain special names. See section <a class="reference internal" href="#specialnames"><span class="std std-ref">Special method names</span></a>.</p> <section id="id5"> <h4><span class="section-number">3.2.11.1. </span>Special attributes<a class="headerlink" href="#id5" title="Link to this heading">¶</a></h4> <dl class="py attribute" id="index-56"> <dt class="sig sig-object py" id="object.__class__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__class__</span></span><a class="headerlink" href="#object.__class__" title="Link to this definition">¶</a></dt> <dd><p>The class to which a class instance belongs.</p> </dd></dl> <dl class="py attribute"> <dt class="sig sig-object py" id="object.__dict__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__dict__</span></span><a class="headerlink" href="#object.__dict__" title="Link to this definition">¶</a></dt> <dd><p>A dictionary or other mapping object used to store an object’s (writable) attributes. Not all instances have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code> attribute; see the section on <a class="reference internal" href="#slots"><span class="std std-ref">__slots__</span></a> for more details.</p> </dd></dl> </section> </section> <section id="i-o-objects-also-known-as-file-objects"> <h3><span class="section-number">3.2.12. </span>I/O objects (also known as file objects)<a class="headerlink" href="#i-o-objects-also-known-as-file-objects" title="Link to this heading">¶</a></h3> <p id="index-57">A <a class="reference internal" href="../glossary.html#term-file-object"><span class="xref std std-term">file object</span></a> represents an open file. Various shortcuts are available to create file objects: the <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> built-in function, and also <a class="reference internal" href="../library/os.html#os.popen" title="os.popen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.popen()</span></code></a>, <a class="reference internal" href="../library/os.html#os.fdopen" title="os.fdopen"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.fdopen()</span></code></a>, and the <a class="reference internal" href="../library/socket.html#socket.socket.makefile" title="socket.socket.makefile"><code class="xref py py-meth docutils literal notranslate"><span class="pre">makefile()</span></code></a> method of socket objects (and perhaps by other functions or methods provided by extension modules).</p> <p>The objects <code class="docutils literal notranslate"><span class="pre">sys.stdin</span></code>, <code class="docutils literal notranslate"><span class="pre">sys.stdout</span></code> and <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> are initialized to file objects corresponding to the interpreter’s standard input, output and error streams; they are all open in text mode and therefore follow the interface defined by the <a class="reference internal" href="../library/io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOBase</span></code></a> abstract class.</p> </section> <section id="internal-types"> <h3><span class="section-number">3.2.13. </span>Internal types<a class="headerlink" href="#internal-types" title="Link to this heading">¶</a></h3> <p id="index-58">A few types used internally by the interpreter are exposed to the user. Their definitions may change with future versions of the interpreter, but they are mentioned here for completeness.</p> <section id="code-objects"> <span id="id6"></span><h4><span class="section-number">3.2.13.1. </span>Code objects<a class="headerlink" href="#code-objects" title="Link to this heading">¶</a></h4> <p id="index-59">Code objects represent <em>byte-compiled</em> executable Python code, or <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>. The difference between a code object and a function object is that the function object contains an explicit reference to the function’s globals (the module in which it was defined), while a code object contains no context; also the default argument values are stored in the function object, not in the code object (because they represent values calculated at run-time). Unlike function objects, code objects are immutable and contain no references (directly or indirectly) to mutable objects.</p> <section id="index-60"> <span id="id7"></span><h5><span class="section-number">3.2.13.1.1. </span>Special read-only attributes<a class="headerlink" href="#index-60" title="Link to this heading">¶</a></h5> <table class="docutils align-default"> <tbody> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_name"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_name</span></span><a class="headerlink" href="#codeobject.co_name" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The function name</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_qualname"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_qualname</span></span><a class="headerlink" href="#codeobject.co_qualname" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The fully qualified function name</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.11.</span></p> </div> </td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_argcount"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_argcount</span></span><a class="headerlink" href="#codeobject.co_argcount" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The total number of positional <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> (including positional-only parameters and parameters with default values) that the function has</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_posonlyargcount"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_posonlyargcount</span></span><a class="headerlink" href="#codeobject.co_posonlyargcount" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The number of positional-only <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> (including arguments with default values) that the function has</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_kwonlyargcount"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_kwonlyargcount</span></span><a class="headerlink" href="#codeobject.co_kwonlyargcount" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The number of keyword-only <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a> (including arguments with default values) that the function has</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_nlocals"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_nlocals</span></span><a class="headerlink" href="#codeobject.co_nlocals" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The number of <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">local variables</span></a> used by the function (including parameters)</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_varnames"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_varnames</span></span><a class="headerlink" href="#codeobject.co_varnames" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the names of the local variables in the function (starting with the parameter names)</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_cellvars"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_cellvars</span></span><a class="headerlink" href="#codeobject.co_cellvars" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the names of <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">local variables</span></a> that are referenced from at least one <a class="reference internal" href="../glossary.html#term-nested-scope"><span class="xref std std-term">nested scope</span></a> inside the function</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_freevars"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_freevars</span></span><a class="headerlink" href="#codeobject.co_freevars" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the names of <a class="reference internal" href="../glossary.html#term-closure-variable"><span class="xref std std-term">free (closure) variables</span></a> that a <a class="reference internal" href="../glossary.html#term-nested-scope"><span class="xref std std-term">nested scope</span></a> references in an outer scope. See also <a class="reference internal" href="#function.__closure__" title="function.__closure__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">function.__closure__</span></code></a>.</p> <p>Note: references to global and builtin names are <em>not</em> included.</p> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_code"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_code</span></span><a class="headerlink" href="#codeobject.co_code" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A string representing the sequence of <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> instructions in the function</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_consts"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_consts</span></span><a class="headerlink" href="#codeobject.co_consts" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the literals used by the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> in the function</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_names"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_names</span></span><a class="headerlink" href="#codeobject.co_names" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> containing the names used by the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> in the function</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_filename"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_filename</span></span><a class="headerlink" href="#codeobject.co_filename" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The name of the file from which the code was compiled</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_firstlineno"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_firstlineno</span></span><a class="headerlink" href="#codeobject.co_firstlineno" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The line number of the first line of the function</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_lnotab"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_lnotab</span></span><a class="headerlink" href="#codeobject.co_lnotab" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>A string encoding the mapping from <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> offsets to line numbers. For details, see the source code of the interpreter.</p> <div class="deprecated"> <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>This attribute of code objects is deprecated, and may be removed in Python 3.15.</p> </div> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_stacksize"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_stacksize</span></span><a class="headerlink" href="#codeobject.co_stacksize" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The required stack size of the code object</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="codeobject.co_flags"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_flags</span></span><a class="headerlink" href="#codeobject.co_flags" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>An <a class="reference internal" href="../library/functions.html#int" title="int"><code class="xref py py-class docutils literal notranslate"><span class="pre">integer</span></code></a> encoding a number of flags for the interpreter.</p></td> </tr> </tbody> </table> <p id="index-61">The following flag bits are defined for <a class="reference internal" href="#codeobject.co_flags" title="codeobject.co_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code></a>: bit <code class="docutils literal notranslate"><span class="pre">0x04</span></code> is set if the function uses the <code class="docutils literal notranslate"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of positional arguments; bit <code class="docutils literal notranslate"><span class="pre">0x08</span></code> is set if the function uses the <code class="docutils literal notranslate"><span class="pre">**keywords</span></code> syntax to accept arbitrary keyword arguments; bit <code class="docutils literal notranslate"><span class="pre">0x20</span></code> is set if the function is a generator. See <a class="reference internal" href="../library/inspect.html#inspect-module-co-flags"><span class="std std-ref">Code Objects Bit Flags</span></a> for details on the semantics of each flags that might be present.</p> <p>Future feature declarations (<code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">division</span></code>) also use bits in <a class="reference internal" href="#codeobject.co_flags" title="codeobject.co_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code></a> to indicate whether a code object was compiled with a particular feature enabled: bit <code class="docutils literal notranslate"><span class="pre">0x2000</span></code> is set if the function was compiled with future division enabled; bits <code class="docutils literal notranslate"><span class="pre">0x10</span></code> and <code class="docutils literal notranslate"><span class="pre">0x1000</span></code> were used in earlier versions of Python.</p> <p>Other bits in <a class="reference internal" href="#codeobject.co_flags" title="codeobject.co_flags"><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_flags</span></code></a> are reserved for internal use.</p> <p id="index-62">If a code object represents a function, the first item in <a class="reference internal" href="#codeobject.co_consts" title="codeobject.co_consts"><code class="xref py py-attr docutils literal notranslate"><span class="pre">co_consts</span></code></a> is the documentation string of the function, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p> </section> <section id="methods-on-code-objects"> <h5><span class="section-number">3.2.13.1.2. </span>Methods on code objects<a class="headerlink" href="#methods-on-code-objects" title="Link to this heading">¶</a></h5> <dl class="py method"> <dt class="sig sig-object py" id="codeobject.co_positions"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_positions</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codeobject.co_positions" title="Link to this definition">¶</a></dt> <dd><p>Returns an iterable over the source code positions of each <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> instruction in the code object.</p> <p>The iterator returns <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>s containing the <code class="docutils literal notranslate"><span class="pre">(start_line,</span> <span class="pre">end_line,</span> <span class="pre">start_column,</span> <span class="pre">end_column)</span></code>. The <em>i-th</em> tuple corresponds to the position of the source code that compiled to the <em>i-th</em> code unit. Column information is 0-indexed utf-8 byte offsets on the given source line.</p> <p>This positional information can be missing. A non-exhaustive lists of cases where this may happen:</p> <ul class="simple"> <li><p>Running the interpreter with <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> <code class="docutils literal notranslate"><span class="pre">no_debug_ranges</span></code>.</p></li> <li><p>Loading a pyc file compiled while using <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> <code class="docutils literal notranslate"><span class="pre">no_debug_ranges</span></code>.</p></li> <li><p>Position tuples corresponding to artificial instructions.</p></li> <li><p>Line and column numbers that can’t be represented due to implementation specific limitations.</p></li> </ul> <p>When this occurs, some or all of the tuple elements can be <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.11.</span></p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This feature requires storing column positions in code objects which may result in a small increase of disk usage of compiled Python files or interpreter memory usage. To avoid storing the extra information and/or deactivate printing the extra traceback information, the <a class="reference internal" href="../using/cmdline.html#cmdoption-X"><code class="xref std std-option docutils literal notranslate"><span class="pre">-X</span></code></a> <code class="docutils literal notranslate"><span class="pre">no_debug_ranges</span></code> command line flag or the <span class="target" id="index-63"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONNODEBUGRANGES"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONNODEBUGRANGES</span></code></a> environment variable can be used.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="codeobject.co_lines"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">co_lines</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#codeobject.co_lines" title="Link to this definition">¶</a></dt> <dd><p>Returns an iterator that yields information about successive ranges of <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>s. Each item yielded is a <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">end,</span> <span class="pre">lineno)</span></code> <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>:</p> <ul class="simple"> <li><p><code class="docutils literal notranslate"><span class="pre">start</span></code> (an <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>) represents the offset (inclusive) of the start of the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> range</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">end</span></code> (an <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>) represents the offset (exclusive) of the end of the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> range</p></li> <li><p><code class="docutils literal notranslate"><span class="pre">lineno</span></code> is an <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> representing the line number of the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> range, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if the bytecodes in the given range have no line number</p></li> </ul> <p>The items yielded will have the following properties:</p> <ul class="simple"> <li><p>The first range yielded will have a <code class="docutils literal notranslate"><span class="pre">start</span></code> of 0.</p></li> <li><p>The <code class="docutils literal notranslate"><span class="pre">(start,</span> <span class="pre">end)</span></code> ranges will be non-decreasing and consecutive. That is, for any pair of <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>s, the <code class="docutils literal notranslate"><span class="pre">start</span></code> of the second will be equal to the <code class="docutils literal notranslate"><span class="pre">end</span></code> of the first.</p></li> <li><p>No range will be backwards: <code class="docutils literal notranslate"><span class="pre">end</span> <span class="pre">&gt;=</span> <span class="pre">start</span></code> for all triples.</p></li> <li><p>The last <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a> yielded will have <code class="docutils literal notranslate"><span class="pre">end</span></code> equal to the size of the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.</p></li> </ul> <p>Zero-width ranges, where <code class="docutils literal notranslate"><span class="pre">start</span> <span class="pre">==</span> <span class="pre">end</span></code>, are allowed. Zero-width ranges are used for lines that are present in the source code, but have been eliminated by the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> compiler.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.10.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-64"></span><a class="pep reference external" href="https://peps.python.org/pep-0626/"><strong>PEP 626</strong></a> - Precise line numbers for debugging and other tools.</dt><dd><p>The PEP that introduced the <code class="xref py py-meth docutils literal notranslate"><span class="pre">co_lines()</span></code> method.</p> </dd> </dl> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="codeobject.replace"> <span class="sig-prename descclassname"><span class="pre">codeobject.</span></span><span class="sig-name descname"><span class="pre">replace</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="o"><span class="pre">**</span></span><span class="n"><span class="pre">kwargs</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#codeobject.replace" title="Link to this definition">¶</a></dt> <dd><p>Return a copy of the code object with new values for the specified fields.</p> <p>Code objects are also supported by the generic function <a class="reference internal" href="../library/copy.html#copy.replace" title="copy.replace"><code class="xref py py-func docutils literal notranslate"><span class="pre">copy.replace()</span></code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.8.</span></p> </div> </dd></dl> </section> </section> <section id="frame-objects"> <span id="id8"></span><h4><span class="section-number">3.2.13.2. </span>Frame objects<a class="headerlink" href="#frame-objects" title="Link to this heading">¶</a></h4> <p id="index-65">Frame objects represent execution frames. They may occur in <a class="reference internal" href="#traceback-objects"><span class="std std-ref">traceback objects</span></a>, and are also passed to registered trace functions.</p> <section id="index-66"> <span id="id9"></span><h5><span class="section-number">3.2.13.2.1. </span>Special read-only attributes<a class="headerlink" href="#index-66" title="Link to this heading">¶</a></h5> <table class="docutils align-default"> <tbody> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_back"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_back</span></span><a class="headerlink" href="#frame.f_back" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Points to the previous stack frame (towards the caller), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if this is the bottom stack frame</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_code"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_code</span></span><a class="headerlink" href="#frame.f_code" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a> being executed in this frame. Accessing this attribute raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;f_code&quot;</span></code>.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_locals"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_locals</span></span><a class="headerlink" href="#frame.f_locals" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The mapping used by the frame to look up <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">local variables</span></a>. If the frame refers to an <a class="reference internal" href="../glossary.html#term-optimized-scope"><span class="xref std std-term">optimized scope</span></a>, this may return a write-through proxy object.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.13: </span>Return a proxy for optimized scopes.</p> </div> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_globals"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_globals</span></span><a class="headerlink" href="#frame.f_globals" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The dictionary used by the frame to look up <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">global variables</span></a></p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_builtins"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_builtins</span></span><a class="headerlink" href="#frame.f_builtins" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The dictionary used by the frame to look up <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">built-in (intrinsic) names</span></a></p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_lasti"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_lasti</span></span><a class="headerlink" href="#frame.f_lasti" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The “precise instruction” of the frame object (this is an index into the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> string of the <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a>)</p></td> </tr> </tbody> </table> </section> <section id="index-67"> <span id="id10"></span><h5><span class="section-number">3.2.13.2.2. </span>Special writable attributes<a class="headerlink" href="#index-67" title="Link to this heading">¶</a></h5> <table class="docutils align-default"> <tbody> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_trace"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_trace</span></span><a class="headerlink" href="#frame.f_trace" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>If not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this is a function called for various events during code execution (this is used by debuggers). Normally an event is triggered for each new source line (see <a class="reference internal" href="#frame.f_trace_lines" title="frame.f_trace_lines"><code class="xref py py-attr docutils literal notranslate"><span class="pre">f_trace_lines</span></code></a>).</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_trace_lines"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_trace_lines</span></span><a class="headerlink" href="#frame.f_trace_lines" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Set this attribute to <a class="reference internal" href="../library/constants.html#False" title="False"><code class="xref py py-const docutils literal notranslate"><span class="pre">False</span></code></a> to disable triggering a tracing event for each source line.</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_trace_opcodes"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_trace_opcodes</span></span><a class="headerlink" href="#frame.f_trace_opcodes" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Set this attribute to <a class="reference internal" href="../library/constants.html#True" title="True"><code class="xref py py-const docutils literal notranslate"><span class="pre">True</span></code></a> to allow per-opcode events to be requested. Note that this may lead to undefined interpreter behaviour if exceptions raised by the trace function escape to the function being traced.</p></td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="frame.f_lineno"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">f_lineno</span></span><a class="headerlink" href="#frame.f_lineno" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>The current line number of the frame – writing to this from within a trace function jumps to the given line (only for the bottom-most frame). A debugger can implement a Jump command (aka Set Next Statement) by writing to this attribute.</p></td> </tr> </tbody> </table> </section> <section id="frame-object-methods"> <h5><span class="section-number">3.2.13.2.3. </span>Frame object methods<a class="headerlink" href="#frame-object-methods" title="Link to this heading">¶</a></h5> <p>Frame objects support one method:</p> <dl class="py method"> <dt class="sig sig-object py" id="frame.clear"> <span class="sig-prename descclassname"><span class="pre">frame.</span></span><span class="sig-name descname"><span class="pre">clear</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#frame.clear" title="Link to this definition">¶</a></dt> <dd><p>This method clears all references to <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">local variables</span></a> held by the frame. Also, if the frame belonged to a <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generator</span></a>, the generator is finalized. This helps break reference cycles involving frame objects (for example when catching an <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">exception</span></a> and storing its <a class="reference internal" href="#traceback-objects"><span class="std std-ref">traceback</span></a> for later use).</p> <p><a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> is raised if the frame is currently executing or suspended.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.4.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.13: </span>Attempting to clear a suspended frame raises <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> (as has always been the case for executing frames).</p> </div> </dd></dl> </section> </section> <section id="traceback-objects"> <span id="id11"></span><h4><span class="section-number">3.2.13.3. </span>Traceback objects<a class="headerlink" href="#traceback-objects" title="Link to this heading">¶</a></h4> <p id="index-68">Traceback objects represent the stack trace of an <a class="reference internal" href="../tutorial/errors.html#tut-errors"><span class="std std-ref">exception</span></a>. A traceback object is implicitly created when an exception occurs, and may also be explicitly created by calling <a class="reference internal" href="../library/types.html#types.TracebackType" title="types.TracebackType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.TracebackType</span></code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Traceback objects can now be explicitly instantiated from Python code.</p> </div> <p>For implicitly created tracebacks, when the search for an exception handler unwinds the execution stack, at each unwound level a traceback object is inserted in front of the current traceback. When an exception handler is entered, the stack trace is made available to the program. (See section <a class="reference internal" href="compound_stmts.html#try"><span class="std std-ref">The try statement</span></a>.) It is accessible as the third item of the tuple returned by <a class="reference internal" href="../library/sys.html#sys.exc_info" title="sys.exc_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">sys.exc_info()</span></code></a>, and as the <a class="reference internal" href="../library/exceptions.html#BaseException.__traceback__" title="BaseException.__traceback__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__traceback__</span></code></a> attribute of the caught exception.</p> <p>When the program contains no suitable handler, the stack trace is written (nicely formatted) to the standard error stream; if the interpreter is interactive, it is also made available to the user as <a class="reference internal" href="../library/sys.html#sys.last_traceback" title="sys.last_traceback"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.last_traceback</span></code></a>.</p> <p>For explicitly created tracebacks, it is up to the creator of the traceback to determine how the <a class="reference internal" href="#traceback.tb_next" title="traceback.tb_next"><code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_next</span></code></a> attributes should be linked to form a full stack trace.</p> <p id="index-69">Special read-only attributes:</p> <table class="docutils align-default"> <tbody> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="traceback.tb_frame"> <span class="sig-prename descclassname"><span class="pre">traceback.</span></span><span class="sig-name descname"><span class="pre">tb_frame</span></span><a class="headerlink" href="#traceback.tb_frame" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Points to the execution <a class="reference internal" href="#frame-objects"><span class="std std-ref">frame</span></a> of the current level.</p> <p>Accessing this attribute raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">&quot;tb_frame&quot;</span></code>.</p> </td> </tr> <tr class="row-even"><td><dl class="py attribute"> <dt class="sig sig-object py" id="traceback.tb_lineno"> <span class="sig-prename descclassname"><span class="pre">traceback.</span></span><span class="sig-name descname"><span class="pre">tb_lineno</span></span><a class="headerlink" href="#traceback.tb_lineno" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Gives the line number where the exception occurred</p></td> </tr> <tr class="row-odd"><td><dl class="py attribute"> <dt class="sig sig-object py" id="traceback.tb_lasti"> <span class="sig-prename descclassname"><span class="pre">traceback.</span></span><span class="sig-name descname"><span class="pre">tb_lasti</span></span><a class="headerlink" href="#traceback.tb_lasti" title="Link to this definition">¶</a></dt> <dd></dd></dl> </td> <td><p>Indicates the “precise instruction”.</p></td> </tr> </tbody> </table> <p>The line number and last instruction in the traceback may differ from the line number of its <a class="reference internal" href="#frame-objects"><span class="std std-ref">frame object</span></a> if the exception occurred in a <a class="reference internal" href="compound_stmts.html#try"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">try</span></code></a> statement with no matching except clause or with a <a class="reference internal" href="compound_stmts.html#finally"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">finally</span></code></a> clause.</p> <dl class="py attribute" id="index-70"> <dt class="sig sig-object py" id="traceback.tb_next"> <span class="sig-prename descclassname"><span class="pre">traceback.</span></span><span class="sig-name descname"><span class="pre">tb_next</span></span><a class="headerlink" href="#traceback.tb_next" title="Link to this definition">¶</a></dt> <dd><p>The special writable attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">tb_next</span></code> is the next level in the stack trace (towards the frame where the exception occurred), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if there is no next level.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>This attribute is now writable</p> </div> </dd></dl> </section> <section id="slice-objects"> <h4><span class="section-number">3.2.13.4. </span>Slice objects<a class="headerlink" href="#slice-objects" title="Link to this heading">¶</a></h4> <p id="index-71">Slice objects are used to represent slices for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> methods. They are also created by the built-in <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-func docutils literal notranslate"><span class="pre">slice()</span></code></a> function.</p> <p id="index-72">Special read-only attributes: <a class="reference internal" href="../library/functions.html#slice.start" title="slice.start"><code class="xref py py-attr docutils literal notranslate"><span class="pre">start</span></code></a> is the lower bound; <a class="reference internal" href="../library/functions.html#slice.stop" title="slice.stop"><code class="xref py py-attr docutils literal notranslate"><span class="pre">stop</span></code></a> is the upper bound; <a class="reference internal" href="../library/functions.html#slice.step" title="slice.step"><code class="xref py py-attr docutils literal notranslate"><span class="pre">step</span></code></a> is the step value; each is <code class="docutils literal notranslate"><span class="pre">None</span></code> if omitted. These attributes can have any type.</p> <p>Slice objects support one method:</p> <dl class="py method"> <dt class="sig sig-object py" id="slice.indices"> <span class="sig-prename descclassname"><span class="pre">slice.</span></span><span class="sig-name descname"><span class="pre">indices</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">length</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#slice.indices" title="Link to this definition">¶</a></dt> <dd><p>This method takes a single integer argument <em>length</em> and computes information about the slice that the slice object would describe if applied to a sequence of <em>length</em> items. It returns a tuple of three integers; respectively these are the <em>start</em> and <em>stop</em> indices and the <em>step</em> or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices.</p> </dd></dl> </section> <section id="static-method-objects"> <h4><span class="section-number">3.2.13.5. </span>Static method objects<a class="headerlink" href="#static-method-objects" title="Link to this heading">¶</a></h4> <p>Static method objects provide a way of defeating the transformation of function objects to method objects described above. A static method object is a wrapper around any other object, usually a user-defined method object. When a static method object is retrieved from a class or a class instance, the object actually returned is the wrapped object, which is not subject to any further transformation. Static method objects are also callable. Static method objects are created by the built-in <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">staticmethod()</span></code></a> constructor.</p> </section> <section id="class-method-objects"> <h4><span class="section-number">3.2.13.6. </span>Class method objects<a class="headerlink" href="#class-method-objects" title="Link to this heading">¶</a></h4> <p>A class method object, like a static method object, is a wrapper around another object that alters the way in which that object is retrieved from classes and class instances. The behaviour of class method objects upon such retrieval is described above, under <a class="reference internal" href="#instance-methods"><span class="std std-ref">“instance methods”</span></a>. Class method objects are created by the built-in <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod()</span></code></a> constructor.</p> </section> </section> </section> <section id="special-method-names"> <span id="specialnames"></span><h2><span class="section-number">3.3. </span>Special method names<a class="headerlink" href="#special-method-names" title="Link to this heading">¶</a></h2> <p id="index-73">A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to <em class="dfn">operator overloading</em>, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, and <code class="docutils literal notranslate"><span class="pre">x</span></code> is an instance of this class, then <code class="docutils literal notranslate"><span class="pre">x[i]</span></code> is roughly equivalent to <code class="docutils literal notranslate"><span class="pre">type(x).__getitem__(x,</span> <span class="pre">i)</span></code>. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> or <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>).</p> <p>Setting a special method to <code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that the corresponding operation is not available. For example, if a class sets <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> to <code class="docutils literal notranslate"><span class="pre">None</span></code>, the class is not iterable, so calling <a class="reference internal" href="../library/functions.html#iter" title="iter"><code class="xref py py-func docutils literal notranslate"><span class="pre">iter()</span></code></a> on its instances will raise a <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> (without falling back to <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>). <a class="footnote-reference brackets" href="#id20" id="id12" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a></p> <p>When implementing a class that emulates any built-in type, it is important that the emulation only be implemented to the degree that it makes sense for the object being modelled. For example, some sequences may work well with retrieval of individual elements, but extracting a slice may not make sense. (One example of this is the <code class="xref py py-class docutils literal notranslate"><span class="pre">NodeList</span></code> interface in the W3C’s Document Object Model.)</p> <section id="basic-customization"> <span id="customization"></span><h3><span class="section-number">3.3.1. </span>Basic customization<a class="headerlink" href="#basic-customization" title="Link to this heading">¶</a></h3> <dl class="py method"> <dt class="sig sig-object py" id="object.__new__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__new__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cls</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__new__" title="Link to this definition">¶</a></dt> <dd><p id="index-74">Called to create a new instance of class <em>cls</em>. <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class). The return value of <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> should be the new object instance (usually an instance of <em>cls</em>).</p> <p>Typical implementations create a new instance of the class by invoking the superclass’s <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> method using <code class="docutils literal notranslate"><span class="pre">super().__new__(cls[,</span> <span class="pre">...])</span></code> with appropriate arguments and then modifying the newly created instance as necessary before returning it.</p> <p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is invoked during object construction and it returns an instance of <em>cls</em>, then the new instance’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will be invoked like <code class="docutils literal notranslate"><span class="pre">__init__(self[,</span> <span class="pre">...])</span></code>, where <em>self</em> is the new instance and the remaining arguments are the same as were passed to the object constructor.</p> <p>If <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> does not return an instance of <em>cls</em>, then the new instance’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method will not be invoked.</p> <p><a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> is intended mainly to allow subclasses of immutable types (like int, str, or tuple) to customize instance creation. It is also commonly overridden in custom metaclasses in order to customize class creation.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__init__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__init__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">...</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__init__" title="Link to this definition">¶</a></dt> <dd><p id="index-75">Called after the instance has been created (by <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a>), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, the derived class’s <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: <code class="docutils literal notranslate"><span class="pre">super().__init__([args...])</span></code>.</p> <p>Because <a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> work together in constructing objects (<a class="reference internal" href="#object.__new__" title="object.__new__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__new__()</span></code></a> to create it, and <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a> to customize it), no non-<code class="docutils literal notranslate"><span class="pre">None</span></code> value may be returned by <a class="reference internal" href="#object.__init__" title="object.__init__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init__()</span></code></a>; doing so will cause a <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> to be raised at runtime.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__del__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__del__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__del__" title="Link to this definition">¶</a></dt> <dd><p id="index-76">Called when the instance is about to be destroyed. This is also called a finalizer or (improperly) a destructor. If a base class has a <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, the derived class’s <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance.</p> <p>It is possible (though not recommended!) for the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method to postpone destruction of the instance by creating a new reference to it. This is called object <em>resurrection</em>. It is implementation-dependent whether <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> is called a second time when a resurrected object is about to be destroyed; the current <a class="reference internal" href="../glossary.html#term-CPython"><span class="xref std std-term">CPython</span></a> implementation only calls it once.</p> <p>It is not guaranteed that <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are called for objects that still exist when the interpreter exits. <a class="reference internal" href="../library/weakref.html#weakref.finalize" title="weakref.finalize"><code class="xref py py-class docutils literal notranslate"><span class="pre">weakref.finalize</span></code></a> provides a straightforward way to register a cleanup function to be called when an object is garbage collected.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">x</span></code> doesn’t directly call <code class="docutils literal notranslate"><span class="pre">x.__del__()</span></code> — the former decrements the reference count for <code class="docutils literal notranslate"><span class="pre">x</span></code> by one, and the latter is only called when <code class="docutils literal notranslate"><span class="pre">x</span></code>’s reference count reaches zero.</p> </div> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> It is possible for a reference cycle to prevent the reference count of an object from going to zero. In this case, the cycle will be later detected and deleted by the <a class="reference internal" href="../glossary.html#term-garbage-collection"><span class="xref std std-term">cyclic garbage collector</span></a>. A common cause of reference cycles is when an exception has been caught in a local variable. The frame’s locals then reference the exception, which references its own traceback, which references the locals of all frames caught in the traceback.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>Documentation for the <a class="reference internal" href="../library/gc.html#module-gc" title="gc: Interface to the cycle-detecting garbage collector."><code class="xref py py-mod docutils literal notranslate"><span class="pre">gc</span></code></a> module.</p> </div> </div> <div class="admonition warning"> <p class="admonition-title">Warning</p> <p>Due to the precarious circumstances under which <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> instead. In particular:</p> <ul class="simple"> <li><p><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> can be invoked when arbitrary code is being executed, including from any arbitrary thread. If <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> needs to take a lock or invoke any other blocking resource, it may deadlock as the resource may already be taken by the code that gets interrupted to execute <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a>.</p></li> <li><p><a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> can be executed during interpreter shutdown. As a consequence, the global variables it needs to access (including other modules) may already have been deleted or set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the <a class="reference internal" href="#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__del__()</span></code></a> method is called.</p></li> </ul> </div> <span class="target" id="index-77"></span></dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__repr__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__repr__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__repr__" title="Link to this definition">¶</a></dt> <dd><p>Called by 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> built-in function to compute the “official” string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <code class="docutils literal notranslate"><span class="pre">&lt;...some</span> <span class="pre">useful</span> <span class="pre">description...&gt;</span></code> should be returned. The return value must be a string object. If a class defines <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> but not <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>, then <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> is also used when an “informal” string representation of instances of that class is required.</p> <p>This is typically used for debugging, so it is important that the representation is information-rich and unambiguous. A default implementation is provided by the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself.</p> <span class="target" id="index-78"></span></dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__str__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__str__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__str__" title="Link to this definition">¶</a></dt> <dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#str" title="str"><code class="xref py py-func docutils literal notranslate"><span class="pre">str(object)</span></code></a>, the default <a class="reference internal" href="#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a> implementation, and the built-in 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>, to compute the “informal” or nicely printable string representation of an object. The return value must be a <a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">str</span></a> object.</p> <p>This method differs from <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a> in that there is no expectation that <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a> return a valid Python expression: a more convenient or concise representation can be used.</p> <p>The default implementation defined by the built-in type <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> calls <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__repr__()</span></code></a>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__bytes__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__bytes__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bytes__" title="Link to this definition">¶</a></dt> <dd><p id="index-79">Called by <a class="reference internal" href="../library/functions.html#func-bytes"><span class="std std-ref">bytes</span></a> to compute a byte-string representation of an object. This should return a <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> object. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide this method.</p> <span class="target" id="index-80"></span></dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__format__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__format__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">format_spec</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__format__" title="Link to this definition">¶</a></dt> <dd><p>Called by the <a class="reference internal" href="../library/functions.html#format" title="format"><code class="xref py py-func docutils literal notranslate"><span class="pre">format()</span></code></a> built-in function, and by extension, evaluation of <a class="reference internal" href="lexical_analysis.html#f-strings"><span class="std std-ref">formatted string literals</span></a> and 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, to produce a “formatted” string representation of an object. The <em>format_spec</em> argument is a string that contains a description of the formatting options desired. The interpretation of the <em>format_spec</em> argument is up to the type implementing <a class="reference internal" href="#object.__format__" title="object.__format__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__format__()</span></code></a>, however most classes will either delegate formatting to one of the built-in types, or use a similar formatting option syntax.</p> <p>See <a class="reference internal" href="../library/string.html#formatspec"><span class="std std-ref">Format Specification Mini-Language</span></a> for a description of the standard formatting syntax.</p> <p>The return value must be a string object.</p> <p>The default implementation by the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class should be given an empty <em>format_spec</em> string. It delegates to <a class="reference internal" href="#object.__str__" title="object.__str__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__str__()</span></code></a>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.4: </span>The __format__ method of <code class="docutils literal notranslate"><span class="pre">object</span></code> itself raises a <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> if passed any non-empty string.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span><code class="docutils literal notranslate"><span class="pre">object.__format__(x,</span> <span class="pre">'')</span></code> is now equivalent to <code class="docutils literal notranslate"><span class="pre">str(x)</span></code> rather than <code class="docutils literal notranslate"><span class="pre">format(str(x),</span> <span class="pre">'')</span></code>.</p> </div> </dd></dl> <dl class="py method" id="richcmpfuncs"> <dt class="sig sig-object py" id="object.__lt__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__lt__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lt__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__le__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__le__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__le__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__eq__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__eq__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__eq__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ne__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ne__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ne__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__gt__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__gt__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__gt__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ge__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ge__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ge__" title="Link to this definition">¶</a></dt> <dd><p id="index-81">These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: <code class="docutils literal notranslate"><span class="pre">x&lt;y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__lt__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x&lt;=y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__le__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x==y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__eq__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x!=y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__ne__(y)</span></code>, <code class="docutils literal notranslate"><span class="pre">x&gt;y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__gt__(y)</span></code>, and <code class="docutils literal notranslate"><span class="pre">x&gt;=y</span></code> calls <code class="docutils literal notranslate"><span class="pre">x.__ge__(y)</span></code>.</p> <p>A rich comparison method may return the singleton <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> if it does not implement the operation for a given pair of arguments. By convention, <code class="docutils literal notranslate"><span class="pre">False</span></code> and <code class="docutils literal notranslate"><span class="pre">True</span></code> are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an <code class="docutils literal notranslate"><span class="pre">if</span></code> statement), Python will call <a class="reference internal" href="../library/functions.html#bool" title="bool"><code class="xref py py-func docutils literal notranslate"><span class="pre">bool()</span></code></a> on the value to determine if the result is true or false.</p> <p>By default, <code class="docutils literal notranslate"><span class="pre">object</span></code> implements <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> by using <code class="docutils literal notranslate"><span class="pre">is</span></code>, returning <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a> in the case of a false comparison: <code class="docutils literal notranslate"><span class="pre">True</span> <span class="pre">if</span> <span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span> <span class="pre">else</span> <span class="pre">NotImplemented</span></code>. For <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a>, by default it delegates to <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and inverts the result unless it is <code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code>. There are no other implied relationships among the comparison operators or default implementations; for example, the truth of <code class="docutils literal notranslate"><span class="pre">(x&lt;y</span> <span class="pre">or</span> <span class="pre">x==y)</span></code> does not imply <code class="docutils literal notranslate"><span class="pre">x&lt;=y</span></code>. To automatically generate ordering operations from a single root operation, see <a class="reference internal" href="../library/functools.html#functools.total_ordering" title="functools.total_ordering"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.total_ordering()</span></code></a>.</p> <p>By default, the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class provides implementations consistent with <a class="reference internal" href="expressions.html#expressions-value-comparisons"><span class="std std-ref">Value comparisons</span></a>: equality compares according to object identity, and order comparisons raise <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>. Each default method may generate these results directly, but may also return <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>.</p> <p>See the paragraph on <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> for some important notes on creating <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> objects which support custom comparison operations and are usable as dictionary keys.</p> <p>There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, <a class="reference internal" href="#object.__lt__" title="object.__lt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__lt__()</span></code></a> and <a class="reference internal" href="#object.__gt__" title="object.__gt__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__gt__()</span></code></a> are each other’s reflection, <a class="reference internal" href="#object.__le__" title="object.__le__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__le__()</span></code></a> and <a class="reference internal" href="#object.__ge__" title="object.__ge__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ge__()</span></code></a> are each other’s reflection, and <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__ne__" title="object.__ne__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__ne__()</span></code></a> are their own reflection. If the operands are of different types, and the right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.</p> <p>When no appropriate method returns any value other than <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>, the <code class="docutils literal notranslate"><span class="pre">==</span></code> and <code class="docutils literal notranslate"><span class="pre">!=</span></code> operators will fall back to <code class="docutils literal notranslate"><span class="pre">is</span></code> and <code class="docutils literal notranslate"><span class="pre">is</span> <span class="pre">not</span></code>, respectively.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__hash__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__hash__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__hash__" title="Link to this definition">¶</a></dt> <dd><p id="index-82">Called by built-in function <a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> and for operations on members of hashed collections including <a class="reference internal" href="../library/stdtypes.html#set" title="set"><code class="xref py py-class docutils literal notranslate"><span class="pre">set</span></code></a>, <a class="reference internal" href="../library/stdtypes.html#frozenset" title="frozenset"><code class="xref py py-class docutils literal notranslate"><span class="pre">frozenset</span></code></a>, and <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>. The <code class="docutils literal notranslate"><span class="pre">__hash__()</span></code> method should return an integer. The only required property is that objects which compare equal have the same hash value; it is advised to mix together the hash values of the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">def</span> <span class="fm">__hash__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">hash</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">nick</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">color</span><span class="p">))</span> </pre></div> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="../library/functions.html#hash" title="hash"><code class="xref py py-func docutils literal notranslate"><span class="pre">hash()</span></code></a> truncates the value returned from an object’s custom <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method to the size of a <a class="reference internal" href="../c-api/intro.html#c.Py_ssize_t" title="Py_ssize_t"><code class="xref c c-type docutils literal notranslate"><span class="pre">Py_ssize_t</span></code></a>. This is typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an object’s <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> must interoperate on builds of different bit sizes, be sure to check the width on all supported builds. An easy way to do this is with <code class="docutils literal notranslate"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">&quot;import</span> <span class="pre">sys;</span> <span class="pre">print(sys.hash_info.width)&quot;</span></code>.</p> </div> <p>If a class does not define an <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method it should not define a <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> operation either; if it defines <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> but not <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, its instances will not be usable as items in hashable collections. If a class defines mutable objects and implements an <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> method, it should not implement <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, since the implementation of <a class="reference internal" href="../glossary.html#term-hashable"><span class="xref std std-term">hashable</span></a> collections requires that a key’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).</p> <p>User-defined classes have <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> methods by default (inherited from the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class); with them, all objects compare unequal (except with themselves) and <code class="docutils literal notranslate"><span class="pre">x.__hash__()</span></code> returns an appropriate value such that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">==</span> <span class="pre">y</span></code> implies both that <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">is</span> <span class="pre">y</span></code> and <code class="docutils literal notranslate"><span class="pre">hash(x)</span> <span class="pre">==</span> <span class="pre">hash(y)</span></code>.</p> <p>A class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> and does not define <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> will have its <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> implicitly set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. When the <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> method of a class is <code class="docutils literal notranslate"><span class="pre">None</span></code>, instances of the class will raise an appropriate <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> when a program attempts to retrieve their hash value, and will also be correctly identified as unhashable when checking <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code>.</p> <p>If a class that overrides <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> needs to retain the implementation of <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> from a parent class, the interpreter must be told this explicitly by setting <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">&lt;ParentClass&gt;.__hash__</span></code>.</p> <p>If a class that does not override <a class="reference internal" href="#object.__eq__" title="object.__eq__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__eq__()</span></code></a> wishes to suppress hash support, it should include <code class="docutils literal notranslate"><span class="pre">__hash__</span> <span class="pre">=</span> <span class="pre">None</span></code> in the class definition. A class which defines its own <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> that explicitly raises a <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> would be incorrectly identified as hashable by an <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code> call.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>By default, the <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> values of str and bytes objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.</p> <p>This is intended to provide protection against a denial-of-service caused by carefully chosen inputs that exploit the worst case performance of a dict insertion, <em>O</em>(<em>n</em><sup>2</sup>) complexity. See <a class="reference external" href="http://ocert.org/advisories/ocert-2011-003.html">http://ocert.org/advisories/ocert-2011-003.html</a> for details.</p> <p>Changing hash values affects the iteration order of sets. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).</p> <p>See also <span class="target" id="index-83"></span><a class="reference internal" href="../using/cmdline.html#envvar-PYTHONHASHSEED"><code class="xref std std-envvar docutils literal notranslate"><span class="pre">PYTHONHASHSEED</span></code></a>.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Hash randomization is enabled by default.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__bool__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__bool__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__bool__" title="Link to this definition">¶</a></dt> <dd><p id="index-84">Called to implement truth value testing and the built-in operation <code class="docutils literal notranslate"><span class="pre">bool()</span></code>; should return <code class="docutils literal notranslate"><span class="pre">False</span></code> or <code class="docutils literal notranslate"><span class="pre">True</span></code>. When this method is not defined, <a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> nor <code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code> (which is true of the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself), all its instances are considered true.</p> </dd></dl> </section> <section id="customizing-attribute-access"> <span id="attribute-access"></span><h3><span class="section-number">3.3.2. </span>Customizing attribute access<a class="headerlink" href="#customizing-attribute-access" title="Link to this heading">¶</a></h3> <p>The following methods can be defined to customize the meaning of attribute access (use of, assignment to, or deletion of <code class="docutils literal notranslate"><span class="pre">x.name</span></code>) for class instances.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__getattr__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getattr__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattr__" title="Link to this definition">¶</a></dt> <dd><p>Called when the default attribute access fails with an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> (either <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> raises an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> because <em>name</em> is not an instance attribute or an attribute in the class tree for <code class="docutils literal notranslate"><span class="pre">self</span></code>; or <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> of a <em>name</em> property raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>). This method should either return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide this method.</p> <p>Note that if the attribute is found through the normal mechanism, <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> is not called. (This is an intentional asymmetry between <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> and <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a>.) This is done both for efficiency reasons and because otherwise <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a> would have no way to access other attributes of the instance. Note that at least for instance variables, you can take total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method below for a way to actually get total control over attribute access.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__getattribute__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getattribute__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getattribute__" title="Link to this definition">¶</a></dt> <dd><p>Called unconditionally to implement attribute accesses for instances of the class. If the class also defines <a class="reference internal" href="#object.__getattr__" title="object.__getattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattr__()</span></code></a>, the latter will not be called unless <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> either calls it explicitly or raises an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. This method should return the (computed) attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, <code class="docutils literal notranslate"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>This method may still be bypassed when looking up special methods as the result of implicit invocation via language syntax or <a class="reference internal" href="#builtin-functions"><span class="std std-ref">built-in functions</span></a>. See <a class="reference internal" href="#special-lookup"><span class="std std-ref">Special method lookup</span></a>.</p> </div> <p class="audit-hook"><p>For certain sensitive attribute accesses, raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">object.__getattr__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">name</span></code>.</p> </p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__setattr__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__setattr__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setattr__" title="Link to this definition">¶</a></dt> <dd><p>Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). <em>name</em> is the attribute name, <em>value</em> is the value to be assigned to it.</p> <p>If <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> wants to assign to an instance attribute, it should call the base class method with the same name, for example, <code class="docutils literal notranslate"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></code>.</p> <p class="audit-hook"><p>For certain sensitive attribute assignments, raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">object.__setattr__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">obj</span></code>, <code class="docutils literal notranslate"><span class="pre">name</span></code>, <code class="docutils literal notranslate"><span class="pre">value</span></code>.</p> </p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__delattr__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__delattr__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delattr__" title="Link to this definition">¶</a></dt> <dd><p>Like <a class="reference internal" href="#object.__setattr__" title="object.__setattr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setattr__()</span></code></a> but for attribute deletion instead of assignment. This should only be implemented if <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">obj.name</span></code> is meaningful for the object.</p> <p class="audit-hook"><p>For certain sensitive attribute deletions, raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">object.__delattr__</span></code> with arguments <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">name</span></code>.</p> </p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__dir__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__dir__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__dir__" title="Link to this definition">¶</a></dt> <dd><p>Called when <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 called on the object. An iterable must be returned. <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> converts the returned iterable to a list and sorts it.</p> </dd></dl> <section id="customizing-module-attribute-access"> <h4><span class="section-number">3.3.2.1. </span>Customizing module attribute access<a class="headerlink" href="#customizing-module-attribute-access" title="Link to this heading">¶</a></h4> <p id="index-85">Special names <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> and <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> can be also used to customize access to module attributes. The <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> function at the module level should accept one argument which is the name of an attribute and return the computed value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. If an attribute is not found on a module object through the normal lookup, i.e. <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__getattribute__()</span></code></a>, then <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> is searched in the module <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> before raising an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. If found, it is called with the attribute name and the result is returned.</p> <p>The <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> function should accept no arguments, and return an iterable of strings that represents the names accessible on module. If present, this function overrides the standard <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> search on a module.</p> <p>For a more fine grained customization of the module behavior (setting attributes, properties, etc.), one can set the <code class="docutils literal notranslate"><span class="pre">__class__</span></code> attribute of a module object to a subclass of <a class="reference internal" href="../library/types.html#types.ModuleType" title="types.ModuleType"><code class="xref py py-class docutils literal notranslate"><span class="pre">types.ModuleType</span></code></a>. For example:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span> <span class="kn">from</span> <span class="nn">types</span> <span class="kn">import</span> <span class="n">ModuleType</span> <span class="k">class</span> <span class="nc">VerboseModule</span><span class="p">(</span><span class="n">ModuleType</span><span class="p">):</span> <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="sa">f</span><span class="s1">&#39;Verbose </span><span class="si">{</span><span class="bp">self</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="s1">&#39;</span> <span class="k">def</span> <span class="fm">__setattr__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">):</span> <span class="nb">print</span><span class="p">(</span><span class="sa">f</span><span class="s1">&#39;Setting </span><span class="si">{</span><span class="n">attr</span><span class="si">}</span><span class="s1">...&#39;</span><span class="p">)</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="fm">__setattr__</span><span class="p">(</span><span class="n">attr</span><span class="p">,</span> <span class="n">value</span><span class="p">)</span> <span class="n">sys</span><span class="o">.</span><span class="n">modules</span><span class="p">[</span><span class="vm">__name__</span><span class="p">]</span><span class="o">.</span><span class="vm">__class__</span> <span class="o">=</span> <span class="n">VerboseModule</span> </pre></div> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>Defining module <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> and setting module <code class="docutils literal notranslate"><span class="pre">__class__</span></code> only affect lookups made using the attribute access syntax – directly accessing the module globals (whether by code within the module, or via a reference to the module’s globals dictionary) is unaffected.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><code class="docutils literal notranslate"><span class="pre">__class__</span></code> module attribute is now writable.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.7: </span><code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> and <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> module attributes.</p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-86"></span><a class="pep reference external" href="https://peps.python.org/pep-0562/"><strong>PEP 562</strong></a> - Module __getattr__ and __dir__</dt><dd><p>Describes the <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> and <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> functions on modules.</p> </dd> </dl> </div> </section> <section id="implementing-descriptors"> <span id="descriptors"></span><h4><span class="section-number">3.3.2.2. </span>Implementing Descriptors<a class="headerlink" href="#implementing-descriptors" title="Link to this heading">¶</a></h4> <p>The following methods only apply when an instance of the class containing the method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the descriptor must be in either the owner’s class dictionary or in the class dictionary for one of its parents). In the examples below, “the attribute” refers to the attribute whose name is the key of the property in the owner class’ <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not implement any of these protocols.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__get__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__get__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">instance</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">owner</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__get__" title="Link to this definition">¶</a></dt> <dd><p>Called to get the attribute of the owner class (class attribute access) or of an instance of that class (instance attribute access). The optional <em>owner</em> argument is the owner class, while <em>instance</em> is the instance that the attribute was accessed through, or <code class="docutils literal notranslate"><span class="pre">None</span></code> when the attribute is accessed through the <em>owner</em>.</p> <p>This method should return the computed attribute value or raise an <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a> exception.</p> <p><span class="target" id="index-87"></span><a class="pep reference external" href="https://peps.python.org/pep-0252/"><strong>PEP 252</strong></a> specifies that <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a> is callable with one or two arguments. Python’s own built-in descriptors support this specification; however, it is likely that some third-party tools have descriptors that require both arguments. Python’s own <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> implementation always passes in both arguments whether they are required or not.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__set__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__set__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">instance</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set__" title="Link to this definition">¶</a></dt> <dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a new value, <em>value</em>.</p> <p>Note, adding <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> or <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a> changes the kind of descriptor to a “data descriptor”. See <a class="reference internal" href="#descriptor-invocation"><span class="std std-ref">Invoking Descriptors</span></a> for more details.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__delete__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__delete__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">instance</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delete__" title="Link to this definition">¶</a></dt> <dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p> </dd></dl> <p>Instances of descriptors may also have the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__objclass__</span></code> attribute present:</p> <dl class="py attribute"> <dt class="sig sig-object py" id="object.__objclass__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__objclass__</span></span><a class="headerlink" href="#object.__objclass__" title="Link to this definition">¶</a></dt> <dd><p>The attribute <code class="xref py py-attr docutils literal notranslate"><span class="pre">__objclass__</span></code> is interpreted by the <a class="reference internal" href="../library/inspect.html#module-inspect" title="inspect: Extract information and source code from live objects."><code class="xref py py-mod docutils literal notranslate"><span class="pre">inspect</span></code></a> module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).</p> </dd></dl> </section> <section id="invoking-descriptors"> <span id="descriptor-invocation"></span><h4><span class="section-number">3.3.2.3. </span>Invoking Descriptors<a class="headerlink" href="#invoking-descriptors" title="Link to this heading">¶</a></h4> <p>In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol: <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a>, and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>. If any of those methods are defined for an object, it is said to be a descriptor.</p> <p>The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> has a lookup chain starting with <code class="docutils literal notranslate"><span class="pre">a.__dict__['x']</span></code>, then <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x']</span></code>, and continuing through the base classes of <code class="docutils literal notranslate"><span class="pre">type(a)</span></code> excluding metaclasses.</p> <p>However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called.</p> <p>The starting point for descriptor invocation is a binding, <code class="docutils literal notranslate"><span class="pre">a.x</span></code>. How the arguments are assembled depends on <code class="docutils literal notranslate"><span class="pre">a</span></code>:</p> <dl class="simple"> <dt>Direct Call</dt><dd><p>The simplest and least common call is when user code directly invokes a descriptor method: <code class="docutils literal notranslate"><span class="pre">x.__get__(a)</span></code>.</p> </dd> <dt>Instance Binding</dt><dd><p>If binding to an object instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> is transformed into the call: <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>.</p> </dd> <dt>Class Binding</dt><dd><p>If binding to a class, <code class="docutils literal notranslate"><span class="pre">A.x</span></code> is transformed into the call: <code class="docutils literal notranslate"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>.</p> </dd> <dt>Super Binding</dt><dd><p>A dotted lookup such as <code class="docutils literal notranslate"><span class="pre">super(A,</span> <span class="pre">a).x</span></code> searches <code class="docutils literal notranslate"><span class="pre">a.__class__.__mro__</span></code> for a base class <code class="docutils literal notranslate"><span class="pre">B</span></code> following <code class="docutils literal notranslate"><span class="pre">A</span></code> and then returns <code class="docutils literal notranslate"><span class="pre">B.__dict__['x'].__get__(a,</span> <span class="pre">A)</span></code>. If not a descriptor, <code class="docutils literal notranslate"><span class="pre">x</span></code> is returned unchanged.</p> </dd> </dl> <p>For instance bindings, the precedence of descriptor invocation depends on which descriptor methods are defined. A descriptor can define any combination of <a class="reference internal" href="#object.__get__" title="object.__get__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code></a>, <a class="reference internal" href="#object.__set__" title="object.__set__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code></a> and <a class="reference internal" href="#object.__delete__" title="object.__delete__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code></a>. If it does not define <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code>, then accessing the attribute will return the descriptor object itself unless there is a value in the object’s instance dictionary. If the descriptor defines <code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code> and/or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code>, it is a data descriptor; if it defines neither, it is a non-data descriptor. Normally, data descriptors define both <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code>, while non-data descriptors have just the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code> method. Data descriptors with <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">__set__()</span></code> (and/or <code class="xref py py-meth docutils literal notranslate"><span class="pre">__delete__()</span></code>) defined always override a redefinition in an instance dictionary. In contrast, non-data descriptors can be overridden by instances.</p> <p>Python methods (including those decorated with <a class="reference internal" href="../library/functions.html#staticmethod" title="staticmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;staticmethod</span></code></a> and <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;classmethod</span></code></a>) are implemented as non-data descriptors. Accordingly, instances can redefine and override methods. This allows individual instances to acquire behaviors that differ from other instances of the same class.</p> <p>The <a class="reference internal" href="../library/functions.html#property" title="property"><code class="xref py py-func docutils literal notranslate"><span class="pre">property()</span></code></a> function is implemented as a data descriptor. Accordingly, instances cannot override the behavior of a property.</p> </section> <section id="slots"> <span id="id13"></span><h4><span class="section-number">3.3.2.4. </span>__slots__<a class="headerlink" href="#slots" title="Link to this heading">¶</a></h4> <p><em>__slots__</em> allow us to explicitly declare data members (like properties) and deny the creation of <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and <em>__weakref__</em> (unless explicitly declared in <em>__slots__</em> or available in a parent.)</p> <p>The space saved over using <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> can be significant. Attribute lookup speed can be significantly improved as well.</p> <dl class="py data"> <dt class="sig sig-object py" id="object.__slots__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__slots__</span></span><a class="headerlink" href="#object.__slots__" title="Link to this definition">¶</a></dt> <dd><p>This class variable can be assigned a string, iterable, or sequence of strings with variable names used by instances. <em>__slots__</em> reserves space for the declared variables and prevents the automatic creation of <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and <em>__weakref__</em> for each instance.</p> </dd></dl> <p id="datamodel-note-slots">Notes on using <em>__slots__</em>:</p> <ul class="simple"> <li><p>When inheriting from a class without <em>__slots__</em>, the <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and <em>__weakref__</em> attribute of the instances will always be accessible.</p></li> <li><p>Without a <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> variable, instances cannot be assigned new variables not listed in the <em>__slots__</em> definition. Attempts to assign to an unlisted variable name raises <a class="reference internal" href="../library/exceptions.html#AttributeError" title="AttributeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">AttributeError</span></code></a>. If dynamic assignment of new variables is desired, then add <code class="docutils literal notranslate"><span class="pre">'__dict__'</span></code> to the sequence of strings in the <em>__slots__</em> declaration.</p></li> <li><p>Without a <em>__weakref__</em> variable for each instance, classes defining <em>__slots__</em> do not support <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">weak</span> <span class="pre">references</span></code></a> to its instances. If weak reference support is needed, then add <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> to the sequence of strings in the <em>__slots__</em> declaration.</p></li> <li><p><em>__slots__</em> are implemented at the class level by creating <a class="reference internal" href="#descriptors"><span class="std std-ref">descriptors</span></a> for each variable name. As a result, class attributes cannot be used to set default values for instance variables defined by <em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor assignment.</p></li> <li><p>The action of a <em>__slots__</em> declaration is not limited to the class where it is defined. <em>__slots__</em> declared in parents are available in child classes. However, instances of a child subclass will get a <a class="reference internal" href="#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and <em>__weakref__</em> unless the subclass also defines <em>__slots__</em> (which should only contain names of any <em>additional</em> slots).</p></li> <li><p>If a class defines a slot also defined in a base class, the instance variable defined by the base class slot is inaccessible (except by retrieving its descriptor directly from the base class). This renders the meaning of the program undefined. In the future, a check may be added to prevent this.</p></li> <li><p><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> will be raised if nonempty <em>__slots__</em> are defined for a class derived from a <a class="reference internal" href="../c-api/typeobj.html#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code class="xref c c-member docutils literal notranslate"><span class="pre">&quot;variable-length&quot;</span> <span class="pre">built-in</span> <span class="pre">type</span></code></a> such as <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>, <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>, and <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuple</span></code></a>.</p></li> <li><p>Any non-string <a class="reference internal" href="../glossary.html#term-iterable"><span class="xref std std-term">iterable</span></a> may be assigned to <em>__slots__</em>.</p></li> <li><p>If a <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> is used to assign <em>__slots__</em>, the dictionary keys will be used as the slot names. The values of the dictionary can be used to provide per-attribute docstrings that will be recognised by <a class="reference internal" href="../library/inspect.html#inspect.getdoc" title="inspect.getdoc"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.getdoc()</span></code></a> and displayed in the output of <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>.</p></li> <li><p><a class="reference internal" href="#object.__class__" title="object.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> assignment works only if both classes have the same <em>__slots__</em>.</p></li> <li><p><a class="reference internal" href="../tutorial/classes.html#tut-multiple"><span class="std std-ref">Multiple inheritance</span></a> with multiple slotted parent classes can be used, but only one parent is allowed to have attributes created by slots (the other bases must have empty slot layouts) - violations raise <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>.</p></li> <li><p>If an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> is used for <em>__slots__</em> then a <a class="reference internal" href="../glossary.html#term-descriptor"><span class="xref std std-term">descriptor</span></a> is created for each of the iterator’s values. However, the <em>__slots__</em> attribute will be an empty iterator.</p></li> </ul> </section> </section> <section id="customizing-class-creation"> <span id="class-customization"></span><h3><span class="section-number">3.3.3. </span>Customizing class creation<a class="headerlink" href="#customizing-class-creation" title="Link to this heading">¶</a></h3> <p>Whenever a class inherits from another class, <a class="reference internal" href="#object.__init_subclass__" title="object.__init_subclass__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init_subclass__()</span></code></a> is called on the parent class. This way, it is possible to write classes which change the behavior of subclasses. This is closely related to class decorators, but where class decorators only affect the specific class they’re applied to, <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> solely applies to future subclasses of the class defining the method.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__init_subclass__"> <em class="property"><span class="pre">classmethod</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__init_subclass__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cls</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__init_subclass__" title="Link to this definition">¶</a></dt> <dd><p>This method is called whenever the containing class is subclassed. <em>cls</em> is then the new subclass. If defined as a normal instance method, this method is implicitly converted to a class method.</p> <p>Keyword arguments which are given to a new class are passed to the parent class’s <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code>. For compatibility with other classes using <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code>, one should take out the needed keyword arguments and pass the others over to the base class, as in:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Philosopher</span><span class="p">:</span> <span class="k">def</span> <span class="nf">__init_subclass__</span><span class="p">(</span><span class="bp">cls</span><span class="p">,</span> <span class="o">/</span><span class="p">,</span> <span class="n">default_name</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">__init_subclass__</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span> <span class="bp">cls</span><span class="o">.</span><span class="n">default_name</span> <span class="o">=</span> <span class="n">default_name</span> <span class="k">class</span> <span class="nc">AustralianPhilosopher</span><span class="p">(</span><span class="n">Philosopher</span><span class="p">,</span> <span class="n">default_name</span><span class="o">=</span><span class="s2">&quot;Bruce&quot;</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>The default implementation <code class="docutils literal notranslate"><span class="pre">object.__init_subclass__</span></code> does nothing, but raises an error if it is called with any arguments.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The metaclass hint <code class="docutils literal notranslate"><span class="pre">metaclass</span></code> is consumed by the rest of the type machinery, and is never passed to <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> implementations. The actual metaclass (rather than the explicit hint) can be accessed as <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code>.</p> </div> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.6.</span></p> </div> </dd></dl> <p>When a class is created, <code class="xref py py-meth docutils literal notranslate"><span class="pre">type.__new__()</span></code> scans the class variables and makes callbacks to those with a <a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> hook.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__set_name__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__set_name__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">owner</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">name</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__set_name__" title="Link to this definition">¶</a></dt> <dd><p>Automatically called at the time the owning class <em>owner</em> is created. The object has been assigned to <em>name</em> in that class:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span> <span class="n">x</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="c1"># Automatically calls: x.__set_name__(A, &#39;x&#39;)</span> </pre></div> </div> <p>If the class variable is assigned after the class is created, <a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> will not be called automatically. If needed, <a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> can be called directly:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">A</span><span class="p">:</span> <span class="k">pass</span> <span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="n">A</span><span class="o">.</span><span class="n">x</span> <span class="o">=</span> <span class="n">c</span> <span class="c1"># The hook is not called</span> <span class="n">c</span><span class="o">.</span><span class="n">__set_name__</span><span class="p">(</span><span class="n">A</span><span class="p">,</span> <span class="s1">&#39;x&#39;</span><span class="p">)</span> <span class="c1"># Manually invoke the hook</span> </pre></div> </div> <p>See <a class="reference internal" href="#class-object-creation"><span class="std std-ref">Creating the class object</span></a> for more details.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.6.</span></p> </div> </dd></dl> <section id="metaclasses"> <span id="id14"></span><h4><span class="section-number">3.3.3.1. </span>Metaclasses<a class="headerlink" href="#metaclasses" title="Link to this heading">¶</a></h4> <p id="index-88">By default, classes are constructed using <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>. The class body is executed in a new namespace and the class name is bound locally to the result of <code class="docutils literal notranslate"><span class="pre">type(name,</span> <span class="pre">bases,</span> <span class="pre">namespace)</span></code>.</p> <p>The class creation process can be customized by passing the <code class="docutils literal notranslate"><span class="pre">metaclass</span></code> keyword argument in the class definition line, or by inheriting from an existing class that included such an argument. In the following example, both <code class="docutils literal notranslate"><span class="pre">MyClass</span></code> and <code class="docutils literal notranslate"><span class="pre">MySubclass</span></code> are instances of <code class="docutils literal notranslate"><span class="pre">Meta</span></code>:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span> <span class="k">pass</span> <span class="k">class</span> <span class="nc">MyClass</span><span class="p">(</span><span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span> <span class="k">pass</span> <span class="k">class</span> <span class="nc">MySubclass</span><span class="p">(</span><span class="n">MyClass</span><span class="p">):</span> <span class="k">pass</span> </pre></div> </div> <p>Any other keyword arguments that are specified in the class definition are passed through to all metaclass operations described below.</p> <p>When a class definition is executed, the following steps occur:</p> <ul class="simple"> <li><p>MRO entries are resolved;</p></li> <li><p>the appropriate metaclass is determined;</p></li> <li><p>the class namespace is prepared;</p></li> <li><p>the class body is executed;</p></li> <li><p>the class object is created.</p></li> </ul> </section> <section id="resolving-mro-entries"> <h4><span class="section-number">3.3.3.2. </span>Resolving MRO entries<a class="headerlink" href="#resolving-mro-entries" title="Link to this heading">¶</a></h4> <dl class="py method"> <dt class="sig sig-object py" id="object.__mro_entries__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__mro_entries__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">bases</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mro_entries__" title="Link to this definition">¶</a></dt> <dd><p>If a base that appears in a class definition is not an instance of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>, then an <code class="xref py py-meth docutils literal notranslate"><span class="pre">__mro_entries__()</span></code> method is searched on the base. If an <code class="xref py py-meth docutils literal notranslate"><span class="pre">__mro_entries__()</span></code> method is found, the base is substituted with the result of a call to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__mro_entries__()</span></code> when creating the class. The method is called with the original bases tuple passed to the <em>bases</em> parameter, and must return a tuple of classes that will be used instead of the base. The returned tuple may be empty: in these cases, the original base is ignored.</p> </dd></dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><a class="reference internal" href="../library/types.html#types.resolve_bases" title="types.resolve_bases"><code class="xref py py-func docutils literal notranslate"><span class="pre">types.resolve_bases()</span></code></a></dt><dd><p>Dynamically resolve bases that are not instances of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>.</p> </dd> <dt><a class="reference internal" href="../library/types.html#types.get_original_bases" title="types.get_original_bases"><code class="xref py py-func docutils literal notranslate"><span class="pre">types.get_original_bases()</span></code></a></dt><dd><p>Retrieve a class’s “original bases” prior to modifications by <a class="reference internal" href="#object.__mro_entries__" title="object.__mro_entries__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mro_entries__()</span></code></a>.</p> </dd> <dt><span class="target" id="index-89"></span><a class="pep reference external" href="https://peps.python.org/pep-0560/"><strong>PEP 560</strong></a></dt><dd><p>Core support for typing module and generic types.</p> </dd> </dl> </div> </section> <section id="determining-the-appropriate-metaclass"> <h4><span class="section-number">3.3.3.3. </span>Determining the appropriate metaclass<a class="headerlink" href="#determining-the-appropriate-metaclass" title="Link to this heading">¶</a></h4> <p id="index-90">The appropriate metaclass for a class definition is determined as follows:</p> <ul class="simple"> <li><p>if no bases and no explicit metaclass are given, then <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> is used;</p></li> <li><p>if an explicit metaclass is given and it is <em>not</em> an instance of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a>, then it is used directly as the metaclass;</p></li> <li><p>if an instance of <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-func docutils literal notranslate"><span class="pre">type()</span></code></a> is given as the explicit metaclass, or bases are defined, then the most derived metaclass is used.</p></li> </ul> <p>The most derived metaclass is selected from the explicitly specified metaclass (if any) and the metaclasses (i.e. <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code>) of all specified base classes. The most derived metaclass is one which is a subtype of <em>all</em> of these candidate metaclasses. If none of the candidate metaclasses meets that criterion, then the class definition will fail with <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p> </section> <section id="preparing-the-class-namespace"> <span id="prepare"></span><h4><span class="section-number">3.3.3.4. </span>Preparing the class namespace<a class="headerlink" href="#preparing-the-class-namespace" title="Link to this heading">¶</a></h4> <p id="index-91">Once the appropriate metaclass has been identified, then the class namespace is prepared. If the metaclass has a <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> attribute, it is called as <code class="docutils literal notranslate"><span class="pre">namespace</span> <span class="pre">=</span> <span class="pre">metaclass.__prepare__(name,</span> <span class="pre">bases,</span> <span class="pre">**kwds)</span></code> (where the additional keyword arguments, if any, come from the class definition). The <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> method should be implemented as a <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">classmethod</span></code></a>. The namespace returned by <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> is passed in to <code class="docutils literal notranslate"><span class="pre">__new__</span></code>, but when the final class object is created the namespace is copied into a new <code class="docutils literal notranslate"><span class="pre">dict</span></code>.</p> <p>If the metaclass has no <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> attribute, then the class namespace is initialised as an empty ordered mapping.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-92"></span><a class="pep reference external" href="https://peps.python.org/pep-3115/"><strong>PEP 3115</strong></a> - Metaclasses in Python 3000</dt><dd><p>Introduced the <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> namespace hook</p> </dd> </dl> </div> </section> <section id="executing-the-class-body"> <h4><span class="section-number">3.3.3.5. </span>Executing the class body<a class="headerlink" href="#executing-the-class-body" title="Link to this heading">¶</a></h4> <p id="index-93">The class body is executed (approximately) as <code class="docutils literal notranslate"><span class="pre">exec(body,</span> <span class="pre">globals(),</span> <span class="pre">namespace)</span></code>. The key difference from a normal call to <a class="reference internal" href="../library/functions.html#exec" title="exec"><code class="xref py py-func docutils literal notranslate"><span class="pre">exec()</span></code></a> is that lexical scoping allows the class body (including any methods) to reference names from the current and outer scopes when the class definition occurs inside a function.</p> <p>However, even when the class definition occurs inside the function, methods defined inside the class still cannot see names defined at the class scope. Class variables must be accessed through the first parameter of instance or class methods, or through the implicit lexically scoped <code class="docutils literal notranslate"><span class="pre">__class__</span></code> reference described in the next section.</p> </section> <section id="creating-the-class-object"> <span id="class-object-creation"></span><h4><span class="section-number">3.3.3.6. </span>Creating the class object<a class="headerlink" href="#creating-the-class-object" title="Link to this heading">¶</a></h4> <p id="index-94">Once the class namespace has been populated by executing the class body, the class object is created by calling <code class="docutils literal notranslate"><span class="pre">metaclass(name,</span> <span class="pre">bases,</span> <span class="pre">namespace,</span> <span class="pre">**kwds)</span></code> (the additional keywords passed here are the same as those passed to <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code>).</p> <p>This class object is the one that will be referenced by the zero-argument form of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a>. <code class="docutils literal notranslate"><span class="pre">__class__</span></code> is an implicit closure reference created by the compiler if any methods in a class body refer to either <code class="docutils literal notranslate"><span class="pre">__class__</span></code> or <code class="docutils literal notranslate"><span class="pre">super</span></code>. This allows the zero argument form of <a class="reference internal" href="../library/functions.html#super" title="super"><code class="xref py py-func docutils literal notranslate"><span class="pre">super()</span></code></a> to correctly identify the class being defined based on lexical scoping, while the class or instance that was used to make the current call is identified based on the first argument passed to the method.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> In CPython 3.6 and later, the <code class="docutils literal notranslate"><span class="pre">__class__</span></code> cell is passed to the metaclass as a <code class="docutils literal notranslate"><span class="pre">__classcell__</span></code> entry in the class namespace. If present, this must be propagated up to the <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> call in order for the class to be initialised correctly. Failing to do so will result in a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> in Python 3.8.</p> </div> <p>When using the default metaclass <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a>, or any metaclass that ultimately calls <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code>, the following additional customization steps are invoked after creating the class object:</p> <ol class="arabic simple"> <li><p>The <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> method collects all of the attributes in the class namespace that define a <a class="reference internal" href="#object.__set_name__" title="object.__set_name__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__set_name__()</span></code></a> method;</p></li> <li><p>Those <code class="docutils literal notranslate"><span class="pre">__set_name__</span></code> methods are called with the class being defined and the assigned name of that particular attribute;</p></li> <li><p>The <a class="reference internal" href="#object.__init_subclass__" title="object.__init_subclass__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__init_subclass__()</span></code></a> hook is called on the immediate parent of the new class in its method resolution order.</p></li> </ol> <p>After the class object is created, it is passed to the class decorators included in the class definition (if any) and the resulting object is bound in the local namespace as the defined class.</p> <p>When a new class is created by <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code>, the object provided as the namespace parameter is copied to a new ordered mapping and the original object is discarded. The new copy is wrapped in a read-only proxy, which becomes the <a class="reference internal" href="#type.__dict__" title="type.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute of the class object.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-95"></span><a class="pep reference external" href="https://peps.python.org/pep-3135/"><strong>PEP 3135</strong></a> - New super</dt><dd><p>Describes the implicit <code class="docutils literal notranslate"><span class="pre">__class__</span></code> closure reference</p> </dd> </dl> </div> </section> <section id="uses-for-metaclasses"> <h4><span class="section-number">3.3.3.7. </span>Uses for metaclasses<a class="headerlink" href="#uses-for-metaclasses" title="Link to this heading">¶</a></h4> <p>The potential uses for metaclasses are boundless. Some ideas that have been explored include enum, logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.</p> </section> </section> <section id="customizing-instance-and-subclass-checks"> <h3><span class="section-number">3.3.4. </span>Customizing instance and subclass checks<a class="headerlink" href="#customizing-instance-and-subclass-checks" title="Link to this heading">¶</a></h3> <p>The following methods are used to override the default behavior of the <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> built-in functions.</p> <p>In particular, the metaclass <a class="reference internal" href="../library/abc.html#abc.ABCMeta" title="abc.ABCMeta"><code class="xref py py-class docutils literal notranslate"><span class="pre">abc.ABCMeta</span></code></a> implements these methods in order to allow the addition of Abstract Base Classes (ABCs) as “virtual base classes” to any class or type (including built-in types), including other ABCs.</p> <dl class="py method"> <dt class="sig sig-object py" id="type.__instancecheck__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__instancecheck__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">instance</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#type.__instancecheck__" title="Link to this definition">¶</a></dt> <dd><p>Return true if <em>instance</em> should be considered a (direct or indirect) instance of <em>class</em>. If defined, called to implement <code class="docutils literal notranslate"><span class="pre">isinstance(instance,</span> <span class="pre">class)</span></code>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="type.__subclasscheck__"> <span class="sig-prename descclassname"><span class="pre">type.</span></span><span class="sig-name descname"><span class="pre">__subclasscheck__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">subclass</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#type.__subclasscheck__" title="Link to this definition">¶</a></dt> <dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect) subclass of <em>class</em>. If defined, called to implement <code class="docutils literal notranslate"><span class="pre">issubclass(subclass,</span> <span class="pre">class)</span></code>.</p> </dd></dl> <p>Note that these methods are looked up on the type (metaclass) of a class. They cannot be defined as class methods in the actual class. This is consistent with the lookup of special methods that are called on instances, only in this case the instance is itself a class.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-96"></span><a class="pep reference external" href="https://peps.python.org/pep-3119/"><strong>PEP 3119</strong></a> - Introducing Abstract Base Classes</dt><dd><p>Includes the specification for customizing <a class="reference internal" href="../library/functions.html#isinstance" title="isinstance"><code class="xref py py-func docutils literal notranslate"><span class="pre">isinstance()</span></code></a> and <a class="reference internal" href="../library/functions.html#issubclass" title="issubclass"><code class="xref py py-func docutils literal notranslate"><span class="pre">issubclass()</span></code></a> behavior through <a class="reference internal" href="#type.__instancecheck__" title="type.__instancecheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a> and <a class="reference internal" href="#type.__subclasscheck__" title="type.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a>, with motivation for this functionality in the context of adding Abstract Base Classes (see the <a class="reference internal" href="../library/abc.html#module-abc" title="abc: Abstract base classes according to :pep:`3119`."><code class="xref py py-mod docutils literal notranslate"><span class="pre">abc</span></code></a> module) to the language.</p> </dd> </dl> </div> </section> <section id="emulating-generic-types"> <h3><span class="section-number">3.3.5. </span>Emulating generic types<a class="headerlink" href="#emulating-generic-types" title="Link to this heading">¶</a></h3> <p>When using <a class="reference internal" href="../glossary.html#term-annotation"><span class="xref std std-term">type annotations</span></a>, it is often useful to <em>parameterize</em> a <a class="reference internal" href="../glossary.html#term-generic-type"><span class="xref std std-term">generic type</span></a> using Python’s square-brackets notation. For example, the annotation <code class="docutils literal notranslate"><span class="pre">list[int]</span></code> might be used to signify a <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> in which all the elements are of 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>.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-97"></span><a class="pep reference external" href="https://peps.python.org/pep-0484/"><strong>PEP 484</strong></a> - Type Hints</dt><dd><p>Introducing Python’s framework for type annotations</p> </dd> <dt><a class="reference internal" href="../library/stdtypes.html#types-genericalias"><span class="std std-ref">Generic Alias Types</span></a></dt><dd><p>Documentation for objects representing parameterized generic classes</p> </dd> <dt><a class="reference internal" href="../library/typing.html#generics"><span class="std std-ref">Generics</span></a>, <a class="reference internal" href="../library/typing.html#user-defined-generics"><span class="std std-ref">user-defined generics</span></a> and <a class="reference internal" href="../library/typing.html#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">typing.Generic</span></code></a></dt><dd><p>Documentation on how to implement generic classes that can be parameterized at runtime and understood by static type-checkers.</p> </dd> </dl> </div> <p>A class can <em>generally</em> only be parameterized if it defines the special class method <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code>.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__class_getitem__"> <em class="property"><span class="pre">classmethod</span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__class_getitem__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">cls</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">key</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__class_getitem__" title="Link to this definition">¶</a></dt> <dd><p>Return an object representing the specialization of a generic class by type arguments found in <em>key</em>.</p> <p>When defined on a class, <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> is automatically a class method. As such, there is no need for it to be decorated with <a class="reference internal" href="../library/functions.html#classmethod" title="classmethod"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;classmethod</span></code></a> when it is defined.</p> </dd></dl> <section id="the-purpose-of-class-getitem"> <h4><span class="section-number">3.3.5.1. </span>The purpose of <em>__class_getitem__</em><a class="headerlink" href="#the-purpose-of-class-getitem" title="Link to this heading">¶</a></h4> <p>The purpose of <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> is to allow runtime parameterization of standard-library generic classes in order to more easily apply <a class="reference internal" href="../glossary.html#term-type-hint"><span class="xref std std-term">type hints</span></a> to these classes.</p> <p>To implement custom generic classes that can be parameterized at runtime and understood by static type-checkers, users should either inherit from a standard library class that already implements <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a>, or inherit from <a class="reference internal" href="../library/typing.html#typing.Generic" title="typing.Generic"><code class="xref py py-class docutils literal notranslate"><span class="pre">typing.Generic</span></code></a>, which has its own implementation of <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code>.</p> <p>Custom implementations of <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> on classes defined outside of the standard library may not be understood by third-party type-checkers such as mypy. Using <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> on any class for purposes other than type hinting is discouraged.</p> </section> <section id="class-getitem-versus-getitem"> <span id="classgetitem-versus-getitem"></span><h4><span class="section-number">3.3.5.2. </span><em>__class_getitem__</em> versus <em>__getitem__</em><a class="headerlink" href="#class-getitem-versus-getitem" title="Link to this heading">¶</a></h4> <p>Usually, the <a class="reference internal" href="expressions.html#subscriptions"><span class="std std-ref">subscription</span></a> of an object using square brackets will call the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> instance method defined on the object’s class. However, if the object being subscribed is itself a class, the class method <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> may be called instead. <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> should return a <a class="reference internal" href="../library/stdtypes.html#types-genericalias"><span class="std std-ref">GenericAlias</span></a> object if it is properly defined.</p> <p>Presented with the <a class="reference internal" href="../glossary.html#term-expression"><span class="xref std std-term">expression</span></a> <code class="docutils literal notranslate"><span class="pre">obj[x]</span></code>, the Python interpreter follows something like the following process to decide whether <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> or <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> should be called:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">inspect</span> <span class="kn">import</span> <span class="n">isclass</span> <span class="k">def</span> <span class="nf">subscribe</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">x</span><span class="p">):</span> <span class="w"> </span><span class="sd">&quot;&quot;&quot;Return the result of the expression &#39;obj[x]&#39;&quot;&quot;&quot;</span> <span class="n">class_of_obj</span> <span class="o">=</span> <span class="nb">type</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="c1"># If the class of obj defines __getitem__,</span> <span class="c1"># call class_of_obj.__getitem__(obj, x)</span> <span class="k">if</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">class_of_obj</span><span class="p">,</span> <span class="s1">&#39;__getitem__&#39;</span><span class="p">):</span> <span class="k">return</span> <span class="n">class_of_obj</span><span class="o">.</span><span class="fm">__getitem__</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="n">x</span><span class="p">)</span> <span class="c1"># Else, if obj is a class and defines __class_getitem__,</span> <span class="c1"># call obj.__class_getitem__(x)</span> <span class="k">elif</span> <span class="n">isclass</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="ow">and</span> <span class="nb">hasattr</span><span class="p">(</span><span class="n">obj</span><span class="p">,</span> <span class="s1">&#39;__class_getitem__&#39;</span><span class="p">):</span> <span class="k">return</span> <span class="n">obj</span><span class="o">.</span><span class="n">__class_getitem__</span><span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="c1"># Else, raise an exception</span> <span class="k">else</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span> <span class="sa">f</span><span class="s2">&quot;&#39;</span><span class="si">{</span><span class="n">class_of_obj</span><span class="o">.</span><span class="vm">__name__</span><span class="si">}</span><span class="s2">&#39; object is not subscriptable&quot;</span> <span class="p">)</span> </pre></div> </div> <p>In Python, all classes are themselves instances of other classes. The class of a class is known as that class’s <a class="reference internal" href="../glossary.html#term-metaclass"><span class="xref std std-term">metaclass</span></a>, and most classes have the <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> class as their metaclass. <a class="reference internal" href="../library/functions.html#type" title="type"><code class="xref py py-class docutils literal notranslate"><span class="pre">type</span></code></a> does not define <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, meaning that expressions such as <code class="docutils literal notranslate"><span class="pre">list[int]</span></code>, <code class="docutils literal notranslate"><span class="pre">dict[str,</span> <span class="pre">float]</span></code> and <code class="docutils literal notranslate"><span class="pre">tuple[str,</span> <span class="pre">bytes]</span></code> all result in <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> being called:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="c1"># list has class &quot;type&quot; as its metaclass, like most classes:</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span> <span class="go">&lt;class &#39;type&#39;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">dict</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="nb">list</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="nb">tuple</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="nb">str</span><span class="p">)</span> <span class="o">==</span> <span class="nb">type</span><span class="p">(</span><span class="nb">bytes</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># &quot;list[int]&quot; calls &quot;list.__class_getitem__(int)&quot;</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">[</span><span class="nb">int</span><span class="p">]</span> <span class="go">list[int]</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># list.__class_getitem__ returns a GenericAlias object:</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">list</span><span class="p">[</span><span class="nb">int</span><span class="p">])</span> <span class="go">&lt;class &#39;types.GenericAlias&#39;&gt;</span> </pre></div> </div> <p>However, if a class has a custom metaclass that defines <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, subscribing the class may result in different behaviour. An example of this can be found in the <a class="reference internal" href="../library/enum.html#module-enum" title="enum: Implementation of an enumeration class."><code class="xref py py-mod docutils literal notranslate"><span class="pre">enum</span></code></a> module:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">enum</span> <span class="kn">import</span> <span class="n">Enum</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Menu</span><span class="p">(</span><span class="n">Enum</span><span class="p">):</span> <span class="gp">... </span><span class="w"> </span><span class="sd">&quot;&quot;&quot;A breakfast menu&quot;&quot;&quot;</span> <span class="gp">... </span> <span class="n">SPAM</span> <span class="o">=</span> <span class="s1">&#39;spam&#39;</span> <span class="gp">... </span> <span class="n">BACON</span> <span class="o">=</span> <span class="s1">&#39;bacon&#39;</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Enum classes have a custom metaclass:</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">Menu</span><span class="p">)</span> <span class="go">&lt;class &#39;enum.EnumMeta&#39;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># EnumMeta defines __getitem__,</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># so __class_getitem__ is not called,</span> <span class="gp">&gt;&gt;&gt; </span><span class="c1"># and the result is not a GenericAlias object:</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">Menu</span><span class="p">[</span><span class="s1">&#39;SPAM&#39;</span><span class="p">]</span> <span class="go">&lt;Menu.SPAM: &#39;spam&#39;&gt;</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">Menu</span><span class="p">[</span><span class="s1">&#39;SPAM&#39;</span><span class="p">])</span> <span class="go">&lt;enum &#39;Menu&#39;&gt;</span> </pre></div> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-98"></span><a class="pep reference external" href="https://peps.python.org/pep-0560/"><strong>PEP 560</strong></a> - Core Support for typing module and generic types</dt><dd><p>Introducing <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a>, and outlining when a <a class="reference internal" href="expressions.html#subscriptions"><span class="std std-ref">subscription</span></a> results in <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> being called instead of <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a></p> </dd> </dl> </div> </section> </section> <section id="emulating-callable-objects"> <span id="id15"></span><h3><span class="section-number">3.3.6. </span>Emulating callable objects<a class="headerlink" href="#emulating-callable-objects" title="Link to this heading">¶</a></h3> <dl class="py method"> <dt class="sig sig-object py" id="object.__call__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__call__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">args...</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__call__" title="Link to this definition">¶</a></dt> <dd><p id="index-99">Called when the instance is “called” as a function; if this method is defined, <code class="docutils literal notranslate"><span class="pre">x(arg1,</span> <span class="pre">arg2,</span> <span class="pre">...)</span></code> roughly translates to <code class="docutils literal notranslate"><span class="pre">type(x).__call__(x,</span> <span class="pre">arg1,</span> <span class="pre">...)</span></code>. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide this method.</p> </dd></dl> </section> <section id="emulating-container-types"> <span id="sequence-types"></span><h3><span class="section-number">3.3.7. </span>Emulating container types<a class="headerlink" href="#emulating-container-types" title="Link to this heading">¶</a></h3> <p>The following methods can be defined to implement container objects. None of them are provided by the <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself. Containers usually are <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequences</span></a> (such as <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">lists</span></code></a> or <a class="reference internal" href="../library/stdtypes.html#tuple" title="tuple"><code class="xref py py-class docutils literal notranslate"><span class="pre">tuples</span></code></a>) or <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mappings</span></a> (like <a class="reference internal" href="../glossary.html#term-dictionary"><span class="xref std std-term">dictionaries</span></a>), but can represent other containers as well. The first set of methods is used either to emulate a sequence or to emulate a mapping; the difference is that for a sequence, the allowable keys should be the integers <em>k</em> for which <code class="docutils literal notranslate"><span class="pre">0</span> <span class="pre">&lt;=</span> <span class="pre">k</span> <span class="pre">&lt;</span> <span class="pre">N</span></code> where <em>N</em> is the length of the sequence, or <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> objects, which define a range of items. It is also recommended that mappings provide the methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">values()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">items()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">get()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">clear()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">setdefault()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">popitem()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">copy()</span></code>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">update()</span></code> behaving similar to those for Python’s standard <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionary</span></code></a> objects. The <a class="reference internal" href="../library/collections.abc.html#module-collections.abc" title="collections.abc: Abstract base classes for containers"><code class="xref py py-mod docutils literal notranslate"><span class="pre">collections.abc</span></code></a> module provides a <a class="reference internal" href="../library/collections.abc.html#collections.abc.MutableMapping" title="collections.abc.MutableMapping"><code class="xref py py-class docutils literal notranslate"><span class="pre">MutableMapping</span></code></a> <a class="reference internal" href="../glossary.html#term-abstract-base-class"><span class="xref std std-term">abstract base class</span></a> to help create those methods from a base set of <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, <a class="reference internal" href="#object.__setitem__" title="object.__setitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__setitem__()</span></code></a>, <a class="reference internal" href="#object.__delitem__" title="object.__delitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__delitem__()</span></code></a>, and <code class="xref py py-meth docutils literal notranslate"><span class="pre">keys()</span></code>. Mutable sequences should provide methods <code class="xref py py-meth docutils literal notranslate"><span class="pre">append()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">count()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">index()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">extend()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">insert()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">pop()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">remove()</span></code>, <code class="xref py py-meth docutils literal notranslate"><span class="pre">reverse()</span></code> and <code class="xref py py-meth docutils literal notranslate"><span class="pre">sort()</span></code>, like Python standard <a class="reference internal" href="../library/stdtypes.html#list" title="list"><code class="xref py py-class docutils literal notranslate"><span class="pre">list</span></code></a> objects. Finally, sequence types should implement addition (meaning concatenation) and multiplication (meaning repetition) by defining the methods <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a>, <a class="reference internal" href="#object.__radd__" title="object.__radd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__radd__()</span></code></a>, <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a>, <a class="reference internal" href="#object.__mul__" title="object.__mul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mul__()</span></code></a>, <a class="reference internal" href="#object.__rmul__" title="object.__rmul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rmul__()</span></code></a> and <a class="reference internal" href="#object.__imul__" title="object.__imul__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__imul__()</span></code></a> described below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a> method to allow efficient use of the <code class="docutils literal notranslate"><span class="pre">in</span></code> operator; for mappings, <code class="docutils literal notranslate"><span class="pre">in</span></code> should search the mapping’s keys; for sequences, it should search through the values. It is further recommended that both mappings and sequences implement the <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a> method to allow efficient iteration through the container; for mappings, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> should iterate through the object’s keys; for sequences, it should iterate through the values.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__len__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__len__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__len__" title="Link to this definition">¶</a></dt> <dd><p id="index-100">Called to implement 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>. Should return the length of the object, an integer <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> 0. Also, an object that doesn’t define a <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> method and whose <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> method returns zero is considered to be false in a Boolean context.</p> <div class="impl-detail compound"> <p><strong>CPython implementation detail:</strong> In CPython, the length is required to be at most <a class="reference internal" href="../library/sys.html#sys.maxsize" title="sys.maxsize"><code class="xref py py-data docutils literal notranslate"><span class="pre">sys.maxsize</span></code></a>. If the length is larger than <code class="xref py py-data docutils literal notranslate"><span class="pre">sys.maxsize</span></code> some features (such as <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>) may raise <a class="reference internal" href="../library/exceptions.html#OverflowError" title="OverflowError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code></a>. To prevent raising <code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code> by truth value testing, an object must define a <a class="reference internal" href="#object.__bool__" title="object.__bool__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__bool__()</span></code></a> method.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__length_hint__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__length_hint__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__length_hint__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.length_hint" title="operator.length_hint"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.length_hint()</span></code></a>. Should return an estimated length for the object (which may be greater or less than the actual length). The length must be an integer <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> 0. The return value may also be <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>, which is treated the same as if the <code class="docutils literal notranslate"><span class="pre">__length_hint__</span></code> method didn’t exist at all. This method is purely an optimization and is never required for correctness.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.4.</span></p> </div> </dd></dl> <div class="admonition note" id="index-101"> <p class="admonition-title">Note</p> <p>Slicing is done exclusively with the following three methods. A call like</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</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="o">=</span> <span class="n">b</span> </pre></div> </div> <p>is translated to</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="p">[</span><span class="nb">slice</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="kc">None</span><span class="p">)]</span> <span class="o">=</span> <span class="n">b</span> </pre></div> </div> <p>and so forth. Missing slice items are always filled in with <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="object.__getitem__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__getitem__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">key</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__getitem__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement evaluation of <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. For <a class="reference internal" href="../glossary.html#term-sequence"><span class="xref std std-term">sequence</span></a> types, the accepted keys should be integers. Optionally, they may support <a class="reference internal" href="../library/functions.html#slice" title="slice"><code class="xref py py-class docutils literal notranslate"><span class="pre">slice</span></code></a> objects as well. Negative index support is also optional. If <em>key</em> is of an inappropriate type, <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> may be raised; if <em>key</em> is a value outside the set of indexes for the sequence (after any special interpretation of negative values), <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> should be raised. For <a class="reference internal" href="../glossary.html#term-mapping"><span class="xref std std-term">mapping</span></a> types, if <em>key</em> is missing (not in the container), <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> should be raised.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p><a class="reference internal" href="compound_stmts.html#for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">for</span></code></a> loops expect that an <a class="reference internal" href="../library/exceptions.html#IndexError" title="IndexError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IndexError</span></code></a> will be raised for illegal indexes to allow proper detection of the end of the sequence.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>When <a class="reference internal" href="expressions.html#subscriptions"><span class="std std-ref">subscripting</span></a> a <em>class</em>, the special class method <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> may be called instead of <code class="docutils literal notranslate"><span class="pre">__getitem__()</span></code>. See <a class="reference internal" href="#classgetitem-versus-getitem"><span class="std std-ref">__class_getitem__ versus __getitem__</span></a> for more details.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__setitem__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__setitem__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">key</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__setitem__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement assignment to <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. Same note as for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. This should only be implemented for mappings if the objects support changes to the values for keys, or if new keys can be added, or for sequences if elements can be replaced. The same exceptions should be raised for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__delitem__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__delitem__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">key</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__delitem__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement deletion of <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. Same note as for <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>. This should only be implemented for mappings if the objects support removal of keys, or for sequences if elements can be removed from the sequence. The same exceptions should be raised for improper <em>key</em> values as for the <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> method.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__missing__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__missing__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">key</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__missing__" title="Link to this definition">¶</a></dt> <dd><p>Called by <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dict</span></code></a>.<a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a> to implement <code class="docutils literal notranslate"><span class="pre">self[key]</span></code> for dict subclasses when key is not in the dictionary.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__iter__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__iter__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iter__" title="Link to this definition">¶</a></dt> <dd><p>This method is called when an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a> is required for a container. This method should return a new iterator object that can iterate over all the objects in the container. For mappings, it should iterate over the keys of the container.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__reversed__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__reversed__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__reversed__" title="Link to this definition">¶</a></dt> <dd><p>Called (if present) by the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> built-in to implement reverse iteration. It should return a new iterator object that iterates over all the objects in the container in reverse order.</p> <p>If the <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> method is not provided, the <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a> built-in will fall back to using the sequence protocol (<a class="reference internal" href="#object.__len__" title="object.__len__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code></a> and <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>). Objects that support the sequence protocol should only provide <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a> if they can provide an implementation that is more efficient than the one provided by <a class="reference internal" href="../library/functions.html#reversed" title="reversed"><code class="xref py py-func docutils literal notranslate"><span class="pre">reversed()</span></code></a>.</p> </dd></dl> <p>The membership test operators (<a class="reference internal" href="expressions.html#in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">in</span></code></a> and <a class="reference internal" href="expressions.html#not-in"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">not</span> <span class="pre">in</span></code></a>) are normally implemented as an iteration through a container. However, container objects can supply the following special method with a more efficient implementation, which also does not require the object be iterable.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__contains__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__contains__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">item</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__contains__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement membership test operators. Should return true if <em>item</em> is in <em>self</em>, false otherwise. For mapping objects, this should consider the keys of the mapping rather than the values or the key-item pairs.</p> <p>For objects that don’t define <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, the membership test first tries iteration via <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, then the old sequence iteration protocol via <a class="reference internal" href="#object.__getitem__" title="object.__getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code></a>, see <a class="reference internal" href="expressions.html#membership-test-details"><span class="std std-ref">this section in the language reference</span></a>.</p> </dd></dl> </section> <section id="emulating-numeric-types"> <span id="numeric-types"></span><h3><span class="section-number">3.3.8. </span>Emulating numeric types<a class="headerlink" href="#emulating-numeric-types" title="Link to this heading">¶</a></h3> <p>The following methods can be defined to emulate numeric objects. Methods corresponding to operations that are not supported by the particular kind of number implemented (e.g., bitwise operations for non-integral numbers) should be left undefined.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__add__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__add__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__add__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__sub__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__sub__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__sub__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__mul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__mul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__matmul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__matmul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__matmul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__truediv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__truediv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__truediv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__floordiv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__floordiv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floordiv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__mod__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__mod__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__mod__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__divmod__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__divmod__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__divmod__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__pow__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__pow__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">modulo</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__pow__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__lshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__lshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__lshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__and__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__and__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__and__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__xor__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__xor__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__xor__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__or__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__or__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__or__" title="Link to this definition">¶</a></dt> <dd><p id="index-102">These methods are called to implement the binary arithmetic operations (<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>, <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>, <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>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>). For instance, to evaluate the expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>, where <em>x</em> is an instance of a class that has an <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">type(x).__add__(x,</span> <span class="pre">y)</span></code> is called. The <a class="reference internal" href="#object.__divmod__" title="object.__divmod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__divmod__()</span></code></a> method should be the equivalent to using <a class="reference internal" href="#object.__floordiv__" title="object.__floordiv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a> and <a class="reference internal" href="#object.__mod__" title="object.__mod__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__mod__()</span></code></a>; it should not be related to <a class="reference internal" href="#object.__truediv__" title="object.__truediv__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__truediv__()</span></code></a>. Note that <a class="reference internal" href="#object.__pow__" title="object.__pow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__pow__()</span></code></a> should be defined to accept an optional third argument if the ternary version of the built-in <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> function is to be supported.</p> <p>If one of those methods does not support the operation with the supplied arguments, it should return <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__radd__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__radd__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__radd__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rsub__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rsub__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rsub__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rmul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rmul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rmatmul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rmatmul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmatmul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rtruediv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rtruediv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rtruediv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rfloordiv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rfloordiv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rfloordiv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rmod__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rmod__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rmod__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rdivmod__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rdivmod__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rdivmod__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rpow__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rpow__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">modulo</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__rpow__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rlshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rlshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rlshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rrshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rrshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rrshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rand__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rand__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rand__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__rxor__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__rxor__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__rxor__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ror__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ror__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ror__" title="Link to this definition">¶</a></dt> <dd><p id="index-103">These methods are called to implement the binary arithmetic operations (<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>, <code class="docutils literal notranslate"><span class="pre">&#64;</span></code>, <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>, <a class="reference internal" href="../library/functions.html#divmod" title="divmod"><code class="xref py py-func docutils literal notranslate"><span class="pre">divmod()</span></code></a>, <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a>, <code class="docutils literal notranslate"><span class="pre">**</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;</span></code>, <code class="docutils literal notranslate"><span class="pre">^</span></code>, <code class="docutils literal notranslate"><span class="pre">|</span></code>) with reflected (swapped) operands. These functions are only called if the left operand does not support the corresponding operation <a class="footnote-reference brackets" href="#id21" id="id16" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a> and the operands are of different types. <a class="footnote-reference brackets" href="#id22" id="id17" role="doc-noteref"><span class="fn-bracket">[</span>4<span class="fn-bracket">]</span></a> For instance, to evaluate the expression <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">-</span> <span class="pre">y</span></code>, where <em>y</em> is an instance of a class that has an <a class="reference internal" href="#object.__rsub__" title="object.__rsub__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rsub__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">type(y).__rsub__(y,</span> <span class="pre">x)</span></code> is called if <code class="docutils literal notranslate"><span class="pre">type(x).__sub__(x,</span> <span class="pre">y)</span></code> returns <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>.</p> <p id="index-104">Note that ternary <a class="reference internal" href="../library/functions.html#pow" title="pow"><code class="xref py py-func docutils literal notranslate"><span class="pre">pow()</span></code></a> will not try calling <a class="reference internal" href="#object.__rpow__" title="object.__rpow__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__rpow__()</span></code></a> (the coercion rules would become too complicated).</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>If the right operand’s type is a subclass of the left operand’s type and that subclass provides a different implementation of the reflected method for the operation, this method will be called before the left operand’s non-reflected method. This behavior allows subclasses to override their ancestors’ operations.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__iadd__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__iadd__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iadd__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__isub__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__isub__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__isub__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__imul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__imul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__imatmul__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__imatmul__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imatmul__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__itruediv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__itruediv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__itruediv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ifloordiv__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ifloordiv__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ifloordiv__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__imod__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__imod__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__imod__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ipow__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ipow__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">modulo</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__ipow__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ilshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ilshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ilshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__irshift__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__irshift__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__irshift__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__iand__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__iand__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__iand__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ixor__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ixor__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ixor__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ior__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ior__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">other</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ior__" title="Link to this definition">¶</a></dt> <dd><p>These methods are called to implement the augmented arithmetic assignments (<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>, <code class="docutils literal notranslate"><span class="pre">&#64;=</span></code>, <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>, <code class="docutils literal notranslate"><span class="pre">**=</span></code>, <code class="docutils literal notranslate"><span class="pre">&lt;&lt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&gt;&gt;=</span></code>, <code class="docutils literal notranslate"><span class="pre">&amp;=</span></code>, <code class="docutils literal notranslate"><span class="pre">^=</span></code>, <code class="docutils literal notranslate"><span class="pre">|=</span></code>). These methods should attempt to do the operation in-place (modifying <em>self</em>) and return the result (which could be, but does not have to be, <em>self</em>). If a specific method is not defined, or if that method returns <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>, the augmented assignment falls back to the normal methods. For instance, if <em>x</em> is an instance of a class with an <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> method, <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+=</span> <span class="pre">y</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">=</span> <span class="pre">x.__iadd__(y)</span></code> . If <a class="reference internal" href="#object.__iadd__" title="object.__iadd__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iadd__()</span></code></a> does not exist, or if <code class="docutils literal notranslate"><span class="pre">x.__iadd__(y)</span></code> returns <code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code>, <code class="docutils literal notranslate"><span class="pre">x.__add__(y)</span></code> and <code class="docutils literal notranslate"><span class="pre">y.__radd__(x)</span></code> are considered, as with the evaluation of <code class="docutils literal notranslate"><span class="pre">x</span> <span class="pre">+</span> <span class="pre">y</span></code>. In certain situations, augmented assignment can result in unexpected errors (see <a class="reference internal" href="../faq/programming.html#faq-augmented-assignment-tuple-error"><span class="std std-ref">Why does a_tuple[i] += [‘item’] raise an exception when the addition works?</span></a>), but this behavior is in fact part of the data model.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__neg__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__neg__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__neg__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__pos__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__pos__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__pos__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__abs__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__abs__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__abs__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__invert__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__invert__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__invert__" title="Link to this definition">¶</a></dt> <dd><p id="index-105">Called to implement the unary arithmetic operations (<code class="docutils literal notranslate"><span class="pre">-</span></code>, <code class="docutils literal notranslate"><span class="pre">+</span></code>, <a class="reference internal" href="../library/functions.html#abs" title="abs"><code class="xref py py-func docutils literal notranslate"><span class="pre">abs()</span></code></a> and <code class="docutils literal notranslate"><span class="pre">~</span></code>).</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__complex__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__complex__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__complex__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__int__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__int__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__int__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__float__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__float__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__float__" title="Link to this definition">¶</a></dt> <dd><p id="index-106">Called to implement the built-in functions <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a>, <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> and <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a>. Should return a value of the appropriate type.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__index__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__index__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__index__" title="Link to this definition">¶</a></dt> <dd><p>Called to implement <a class="reference internal" href="../library/operator.html#operator.index" title="operator.index"><code class="xref py py-func docutils literal notranslate"><span class="pre">operator.index()</span></code></a>, and whenever Python needs to losslessly convert the numeric object to an integer object (such as in slicing, or in the built-in <a class="reference internal" href="../library/functions.html#bin" title="bin"><code class="xref py py-func docutils literal notranslate"><span class="pre">bin()</span></code></a>, <a class="reference internal" href="../library/functions.html#hex" title="hex"><code class="xref py py-func docutils literal notranslate"><span class="pre">hex()</span></code></a> and <a class="reference internal" href="../library/functions.html#oct" title="oct"><code class="xref py py-func docutils literal notranslate"><span class="pre">oct()</span></code></a> functions). Presence of this method indicates that the numeric object is an integer type. Must return an integer.</p> <p>If <a class="reference internal" href="#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a>, <a class="reference internal" href="#object.__float__" title="object.__float__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__float__()</span></code></a> and <a class="reference internal" href="#object.__complex__" title="object.__complex__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__complex__()</span></code></a> are not defined then corresponding built-in functions <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>, <a class="reference internal" href="../library/functions.html#float" title="float"><code class="xref py py-func docutils literal notranslate"><span class="pre">float()</span></code></a> and <a class="reference internal" href="../library/functions.html#complex" title="complex"><code class="xref py py-func docutils literal notranslate"><span class="pre">complex()</span></code></a> fall back to <a class="reference internal" href="#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__round__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__round__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">ndigits</span></span></em><span class="optional">]</span><span class="sig-paren">)</span><a class="headerlink" href="#object.__round__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__trunc__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__trunc__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__trunc__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__floor__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__floor__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__floor__" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py" id="object.__ceil__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__ceil__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__ceil__" title="Link to this definition">¶</a></dt> <dd><p id="index-107">Called to implement the built-in function <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> and <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> functions <a class="reference internal" href="../library/math.html#math.trunc" title="math.trunc"><code class="xref py py-func docutils literal notranslate"><span class="pre">trunc()</span></code></a>, <a class="reference internal" href="../library/math.html#math.floor" title="math.floor"><code class="xref py py-func docutils literal notranslate"><span class="pre">floor()</span></code></a> and <a class="reference internal" href="../library/math.html#math.ceil" title="math.ceil"><code class="xref py py-func docutils literal notranslate"><span class="pre">ceil()</span></code></a>. Unless <em>ndigits</em> is passed to <code class="xref py py-meth docutils literal notranslate"><span class="pre">__round__()</span></code> all these methods should return the value of the object truncated to an <a class="reference internal" href="../library/numbers.html#numbers.Integral" title="numbers.Integral"><code class="xref py py-class docutils literal notranslate"><span class="pre">Integral</span></code></a> (typically an <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>).</p> <p>The built-in function <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> falls back to <a class="reference internal" href="#object.__trunc__" title="object.__trunc__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__trunc__()</span></code></a> if neither <a class="reference internal" href="#object.__int__" title="object.__int__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__int__()</span></code></a> nor <a class="reference internal" href="#object.__index__" title="object.__index__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__index__()</span></code></a> is defined.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>The delegation of <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> to <a class="reference internal" href="#object.__trunc__" title="object.__trunc__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__trunc__()</span></code></a> is deprecated.</p> </div> </dd></dl> </section> <section id="with-statement-context-managers"> <span id="context-managers"></span><h3><span class="section-number">3.3.9. </span>With Statement Context Managers<a class="headerlink" href="#with-statement-context-managers" title="Link to this heading">¶</a></h3> <p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be established when executing a <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code> statement (described in section <a class="reference internal" href="compound_stmts.html#with"><span class="std std-ref">The with statement</span></a>), but can also be used by directly invoking their methods.</p> <p id="index-108">Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc.</p> <p>For more information on context managers, see <a class="reference internal" href="../library/stdtypes.html#typecontextmanager"><span class="std std-ref">Context Manager Types</span></a>. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide the context manager methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__enter__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__enter__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__enter__" title="Link to this definition">¶</a></dt> <dd><p>Enter the runtime context related to this object. The <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement will bind this method’s return value to the target(s) specified in the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause of the statement, if any.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__exit__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__exit__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exc_type</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exc_value</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__exit__" title="Link to this definition">¶</a></dt> <dd><p>Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be <a class="reference internal" href="../library/constants.html#None" title="None"><code class="xref py py-const docutils literal notranslate"><span class="pre">None</span></code></a>.</p> <p>If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.</p> <p>Note that <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a> methods should not reraise the passed-in exception; this is the caller’s responsibility.</p> </dd></dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-109"></span><a class="pep reference external" href="https://peps.python.org/pep-0343/"><strong>PEP 343</strong></a> - The “with” statement</dt><dd><p>The specification, background, and examples for the Python <a class="reference internal" href="compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement.</p> </dd> </dl> </div> </section> <section id="customizing-positional-arguments-in-class-pattern-matching"> <span id="class-pattern-matching"></span><h3><span class="section-number">3.3.10. </span>Customizing positional arguments in class pattern matching<a class="headerlink" href="#customizing-positional-arguments-in-class-pattern-matching" title="Link to this heading">¶</a></h3> <p>When using a class name in a pattern, positional arguments in the pattern are not allowed by default, i.e. <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">MyClass(x,</span> <span class="pre">y)</span></code> is typically invalid without special support in <code class="docutils literal notranslate"><span class="pre">MyClass</span></code>. To be able to use that kind of pattern, the class needs to define a <em>__match_args__</em> attribute.</p> <dl class="py data"> <dt class="sig sig-object py" id="object.__match_args__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__match_args__</span></span><a class="headerlink" href="#object.__match_args__" title="Link to this definition">¶</a></dt> <dd><p>This class variable can be assigned a tuple of strings. When this class is used in a class pattern with positional arguments, each positional argument will be converted into a keyword argument, using the corresponding value in <em>__match_args__</em> as the keyword. The absence of this attribute is equivalent to setting it to <code class="docutils literal notranslate"><span class="pre">()</span></code>.</p> </dd></dl> <p>For example, if <code class="docutils literal notranslate"><span class="pre">MyClass.__match_args__</span></code> is <code class="docutils literal notranslate"><span class="pre">(&quot;left&quot;,</span> <span class="pre">&quot;center&quot;,</span> <span class="pre">&quot;right&quot;)</span></code> that means that <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">MyClass(x,</span> <span class="pre">y)</span></code> is equivalent to <code class="docutils literal notranslate"><span class="pre">case</span> <span class="pre">MyClass(left=x,</span> <span class="pre">center=y)</span></code>. Note that the number of arguments in the pattern must be smaller than or equal to the number of elements in <em>__match_args__</em>; if it is larger, the pattern match attempt will raise a <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>.</p> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.10.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-110"></span><a class="pep reference external" href="https://peps.python.org/pep-0634/"><strong>PEP 634</strong></a> - Structural Pattern Matching</dt><dd><p>The specification for the Python <code class="docutils literal notranslate"><span class="pre">match</span></code> statement.</p> </dd> </dl> </div> </section> <section id="emulating-buffer-types"> <span id="python-buffer-protocol"></span><h3><span class="section-number">3.3.11. </span>Emulating buffer types<a class="headerlink" href="#emulating-buffer-types" title="Link to this heading">¶</a></h3> <p>The <a class="reference internal" href="../c-api/buffer.html#bufferobjects"><span class="std std-ref">buffer protocol</span></a> provides a way for Python objects to expose efficient access to a low-level memory array. This protocol is implemented by builtin types such 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> and <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a>, and third-party libraries may define additional buffer types.</p> <p>While buffer types are usually implemented in C, it is also possible to implement the protocol in Python.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__buffer__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__buffer__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">flags</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__buffer__" title="Link to this definition">¶</a></dt> <dd><p>Called when a buffer is requested from <em>self</em> (for example, by the <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> constructor). The <em>flags</em> argument is an integer representing the kind of buffer requested, affecting for example whether the returned buffer is read-only or writable. <a class="reference internal" href="../library/inspect.html#inspect.BufferFlags" title="inspect.BufferFlags"><code class="xref py py-class docutils literal notranslate"><span class="pre">inspect.BufferFlags</span></code></a> provides a convenient way to interpret the flags. The method must return a <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__release_buffer__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__release_buffer__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffer</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__release_buffer__" title="Link to this definition">¶</a></dt> <dd><p>Called when a buffer is no longer needed. The <em>buffer</em> argument is a <a class="reference internal" href="../library/stdtypes.html#memoryview" title="memoryview"><code class="xref py py-class docutils literal notranslate"><span class="pre">memoryview</span></code></a> object that was previously returned by <a class="reference internal" href="#object.__buffer__" title="object.__buffer__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__buffer__()</span></code></a>. The method must release any resources associated with the buffer. This method should return <code class="docutils literal notranslate"><span class="pre">None</span></code>. Buffer objects that do not need to perform any cleanup are not required to implement this method.</p> </dd></dl> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.12.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt><span class="target" id="index-111"></span><a class="pep reference external" href="https://peps.python.org/pep-0688/"><strong>PEP 688</strong></a> - Making the buffer protocol accessible in Python</dt><dd><p>Introduces the Python <code class="docutils literal notranslate"><span class="pre">__buffer__</span></code> and <code class="docutils literal notranslate"><span class="pre">__release_buffer__</span></code> methods.</p> </dd> <dt><a class="reference internal" href="../library/collections.abc.html#collections.abc.Buffer" title="collections.abc.Buffer"><code class="xref py py-class docutils literal notranslate"><span class="pre">collections.abc.Buffer</span></code></a></dt><dd><p>ABC for buffer types.</p> </dd> </dl> </div> </section> <section id="special-method-lookup"> <span id="special-lookup"></span><h3><span class="section-number">3.3.12. </span>Special method lookup<a class="headerlink" href="#special-method-lookup" title="Link to this heading">¶</a></h3> <p>For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">:</span> <span class="gp">... </span> <span class="k">pass</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span> <span class="o">=</span> <span class="k">lambda</span><span class="p">:</span> <span class="mi">5</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span> <span class="gr">TypeError</span>: <span class="n">object of type &#39;C&#39; has no len()</span> </pre></div> </div> <p>The rationale behind this behaviour lies with a number of special methods such as <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a> and <a class="reference internal" href="#object.__repr__" title="object.__repr__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__repr__()</span></code></a> that are implemented by all objects, including type objects. If the implicit lookup of these methods used the conventional lookup process, they would fail when invoked on the type object itself:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="mi">1</span> <span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">int</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">()</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="gt">Traceback (most recent call last):</span> File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span> <span class="gr">TypeError</span>: <span class="n">descriptor &#39;__hash__&#39; of &#39;int&#39; object needs an argument</span> </pre></div> </div> <p>Incorrectly attempting to invoke an unbound method of a class in this way is sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing the instance when looking up special methods:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span> <span class="go">True</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span><span class="o">.</span><span class="fm">__hash__</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="o">==</span> <span class="nb">hash</span><span class="p">(</span><span class="nb">int</span><span class="p">)</span> <span class="go">True</span> </pre></div> </div> <p>In addition to bypassing any instance attributes in the interest of correctness, implicit special method lookup generally also bypasses the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> method even of the object’s metaclass:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">Meta</span><span class="p">(</span><span class="nb">type</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Metaclass getattribute invoked&quot;</span><span class="p">)</span> <span class="gp">... </span> <span class="k">return</span> <span class="nb">type</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">C</span><span class="p">(</span><span class="nb">object</span><span class="p">,</span> <span class="n">metaclass</span><span class="o">=</span><span class="n">Meta</span><span class="p">):</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__len__</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="mi">10</span> <span class="gp">... </span> <span class="k">def</span> <span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">):</span> <span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Class getattribute invoked&quot;</span><span class="p">)</span> <span class="gp">... </span> <span class="k">return</span> <span class="nb">object</span><span class="o">.</span><span class="fm">__getattribute__</span><span class="p">(</span><span class="o">*</span><span class="n">args</span><span class="p">)</span> <span class="gp">...</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span> <span class="gp">&gt;&gt;&gt; </span><span class="n">c</span><span class="o">.</span><span class="fm">__len__</span><span class="p">()</span> <span class="c1"># Explicit lookup via instance</span> <span class="go">Class getattribute invoked</span> <span class="go">10</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">)</span><span class="o">.</span><span class="fm">__len__</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># Explicit lookup via type</span> <span class="go">Metaclass getattribute invoked</span> <span class="go">10</span> <span class="gp">&gt;&gt;&gt; </span><span class="nb">len</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="c1"># Implicit lookup</span> <span class="go">10</span> </pre></div> </div> <p>Bypassing the <a class="reference internal" href="#object.__getattribute__" title="object.__getattribute__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a> machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method <em>must</em> be set on the class object itself in order to be consistently invoked by the interpreter).</p> </section> </section> <section id="coroutines"> <span id="index-112"></span><h2><span class="section-number">3.4. </span>Coroutines<a class="headerlink" href="#coroutines" title="Link to this heading">¶</a></h2> <section id="awaitable-objects"> <h3><span class="section-number">3.4.1. </span>Awaitable Objects<a class="headerlink" href="#awaitable-objects" title="Link to this heading">¶</a></h3> <p>An <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object generally implements an <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> method. <a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">Coroutine objects</span></a> returned from <a class="reference internal" href="compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> functions are awaitable.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The <a class="reference internal" href="../glossary.html#term-generator-iterator"><span class="xref std std-term">generator iterator</span></a> objects returned from generators decorated with <a class="reference internal" href="../library/types.html#types.coroutine" title="types.coroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">types.coroutine()</span></code></a> are also awaitable, but they do not implement <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a>.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="object.__await__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__await__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__await__" title="Link to this definition">¶</a></dt> <dd><p>Must return an <a class="reference internal" href="../glossary.html#term-iterator"><span class="xref std std-term">iterator</span></a>. Should be used to implement <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> objects. For instance, <a class="reference internal" href="../library/asyncio-future.html#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">asyncio.Future</span></code></a> implements this method to be compatible with the <a class="reference internal" href="expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expression. The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself is not awaitable and does not provide this method.</p> <div class="admonition note"> <p class="admonition-title">Note</p> <p>The language doesn’t place any restriction on the type or value of the objects yielded by the iterator returned by <code class="docutils literal notranslate"><span class="pre">__await__</span></code>, as this is specific to the implementation of the asynchronous execution framework (e.g. <a class="reference internal" href="../library/asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a>) that will be managing the <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p> </div> </dd></dl> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.5.</span></p> </div> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><span class="target" id="index-113"></span><a class="pep reference external" href="https://peps.python.org/pep-0492/"><strong>PEP 492</strong></a> for additional information about awaitable objects.</p> </div> </section> <section id="coroutine-objects"> <span id="id18"></span><h3><span class="section-number">3.4.2. </span>Coroutine Objects<a class="headerlink" href="#coroutine-objects" title="Link to this heading">¶</a></h3> <p><a class="reference internal" href="../glossary.html#term-coroutine"><span class="xref std std-term">Coroutine objects</span></a> are <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> objects. A coroutine’s execution can be controlled by calling <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> and iterating over the result. When the coroutine has finished executing and returns, the iterator raises <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, and the exception’s <a class="reference internal" href="../library/exceptions.html#StopIteration.value" title="StopIteration.value"><code class="xref py py-attr docutils literal notranslate"><span class="pre">value</span></code></a> attribute holds the return value. If the coroutine raises an exception, it is propagated by the iterator. Coroutines should not directly raise unhandled <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a> exceptions.</p> <p>Coroutines also have the methods listed below, which are analogous to those of generators (see <a class="reference internal" href="expressions.html#generator-methods"><span class="std std-ref">Generator-iterator methods</span></a>). However, unlike generators, coroutines do not directly support iteration.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5.2: </span>It is a <a class="reference internal" href="../library/exceptions.html#RuntimeError" title="RuntimeError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">RuntimeError</span></code></a> to await on a coroutine more than once.</p> </div> <dl class="py method"> <dt class="sig sig-object py" id="coroutine.send"> <span class="sig-prename descclassname"><span class="pre">coroutine.</span></span><span class="sig-name descname"><span class="pre">send</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.send" title="Link to this definition">¶</a></dt> <dd><p>Starts or resumes execution of the coroutine. If <em>value</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, this is equivalent to advancing the iterator returned by <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a>. If <em>value</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this method delegates to the <a class="reference internal" href="expressions.html#generator.send" title="generator.send"><code class="xref py py-meth docutils literal notranslate"><span class="pre">send()</span></code></a> method of the iterator that caused the coroutine to suspend. The result (return value, <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, or other exception) is the same as when iterating over the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code> return value, described above.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="coroutine.throw"> <span class="sig-prename descclassname"><span class="pre">coroutine.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.throw" title="Link to this definition">¶</a></dt> <dt class="sig sig-object py"> <span class="sig-prename descclassname"><span class="pre">coroutine.</span></span><span class="sig-name descname"><span class="pre">throw</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">type</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">value</span></span></em><span class="optional">[</span>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="optional">]</span><span class="optional">]</span><span class="sig-paren">)</span></dt> <dd><p>Raises the specified exception in the coroutine. This method delegates to the <a class="reference internal" href="expressions.html#generator.throw" title="generator.throw"><code class="xref py py-meth docutils literal notranslate"><span class="pre">throw()</span></code></a> method of the iterator that caused the coroutine to suspend, if it has such a method. Otherwise, the exception is raised at the suspension point. The result (return value, <a class="reference internal" href="../library/exceptions.html#StopIteration" title="StopIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopIteration</span></code></a>, or other exception) is the same as when iterating over the <a class="reference internal" href="#object.__await__" title="object.__await__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code></a> return value, described above. If the exception is not caught in the coroutine, it propagates back to the caller.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.</p> </div> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="coroutine.close"> <span class="sig-prename descclassname"><span class="pre">coroutine.</span></span><span class="sig-name descname"><span class="pre">close</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#coroutine.close" title="Link to this definition">¶</a></dt> <dd><p>Causes the coroutine to clean itself up and exit. If the coroutine is suspended, this method first delegates to the <a class="reference internal" href="expressions.html#generator.close" title="generator.close"><code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code></a> method of the iterator that caused the coroutine to suspend, if it has such a method. Then it raises <a class="reference internal" href="../library/exceptions.html#GeneratorExit" title="GeneratorExit"><code class="xref py py-exc docutils literal notranslate"><span class="pre">GeneratorExit</span></code></a> at the suspension point, causing the coroutine to immediately clean itself up. Finally, the coroutine is marked as having finished executing, even if it was never started.</p> <p>Coroutine objects are automatically closed using the above process when they are about to be destroyed.</p> </dd></dl> </section> <section id="asynchronous-iterators"> <span id="async-iterators"></span><h3><span class="section-number">3.4.3. </span>Asynchronous Iterators<a class="headerlink" href="#asynchronous-iterators" title="Link to this heading">¶</a></h3> <p>An <em>asynchronous iterator</em> can call asynchronous code in its <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> method.</p> <p>Asynchronous iterators can be used in an <a class="reference internal" href="compound_stmts.html#async-for"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">for</span></code></a> statement.</p> <p>The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide these methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__aiter__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__aiter__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aiter__" title="Link to this definition">¶</a></dt> <dd><p>Must return an <em>asynchronous iterator</em> object.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__anext__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__anext__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__anext__" title="Link to this definition">¶</a></dt> <dd><p>Must return an <em>awaitable</em> resulting in a next value of the iterator. Should raise a <a class="reference internal" href="../library/exceptions.html#StopAsyncIteration" title="StopAsyncIteration"><code class="xref py py-exc docutils literal notranslate"><span class="pre">StopAsyncIteration</span></code></a> error when the iteration is over.</p> </dd></dl> <p>An example of an asynchronous iterable object:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Reader</span><span class="p">:</span> <span class="k">async</span> <span class="k">def</span> <span class="nf">readline</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="o">...</span> <span class="k">def</span> <span class="fm">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span> <span class="k">async</span> <span class="k">def</span> <span class="fm">__anext__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">val</span> <span class="o">=</span> <span class="k">await</span> <span class="bp">self</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span> <span class="k">if</span> <span class="n">val</span> <span class="o">==</span> <span class="sa">b</span><span class="s1">&#39;&#39;</span><span class="p">:</span> <span class="k">raise</span> <span class="ne">StopAsyncIteration</span> <span class="k">return</span> <span class="n">val</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.5.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Prior to Python 3.7, <a class="reference internal" href="#object.__aiter__" title="object.__aiter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aiter__()</span></code></a> could return an <em>awaitable</em> that would resolve to an <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>.</p> <p>Starting with Python 3.7, <a class="reference internal" href="#object.__aiter__" title="object.__aiter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__aiter__()</span></code></a> must return an asynchronous iterator object. Returning anything else will result in a <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> error.</p> </div> </section> <section id="asynchronous-context-managers"> <span id="async-context-managers"></span><h3><span class="section-number">3.4.4. </span>Asynchronous Context Managers<a class="headerlink" href="#asynchronous-context-managers" title="Link to this heading">¶</a></h3> <p>An <em>asynchronous context manager</em> is a <em>context manager</em> that is able to suspend execution in its <code class="docutils literal notranslate"><span class="pre">__aenter__</span></code> and <code class="docutils literal notranslate"><span class="pre">__aexit__</span></code> methods.</p> <p>Asynchronous context managers can be used in an <a class="reference internal" href="compound_stmts.html#async-with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">with</span></code></a> statement.</p> <p>The <a class="reference internal" href="../library/functions.html#object" title="object"><code class="xref py py-class docutils literal notranslate"><span class="pre">object</span></code></a> class itself does not provide these methods.</p> <dl class="py method"> <dt class="sig sig-object py" id="object.__aenter__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__aenter__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aenter__" title="Link to this definition">¶</a></dt> <dd><p>Semantically similar to <a class="reference internal" href="#object.__enter__" title="object.__enter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__enter__()</span></code></a>, the only difference being that it must return an <em>awaitable</em>.</p> </dd></dl> <dl class="py method"> <dt class="sig sig-object py" id="object.__aexit__"> <span class="sig-prename descclassname"><span class="pre">object.</span></span><span class="sig-name descname"><span class="pre">__aexit__</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">self</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exc_type</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">exc_value</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">traceback</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#object.__aexit__" title="Link to this definition">¶</a></dt> <dd><p>Semantically similar to <a class="reference internal" href="#object.__exit__" title="object.__exit__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__exit__()</span></code></a>, the only difference being that it must return an <em>awaitable</em>.</p> </dd></dl> <p>An example of an asynchronous context manager class:</p> <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">AsyncContextManager</span><span class="p">:</span> <span class="k">async</span> <span class="k">def</span> <span class="fm">__aenter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">&#39;entering context&#39;</span><span class="p">)</span> <span class="k">async</span> <span class="k">def</span> <span class="fm">__aexit__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">exc_type</span><span class="p">,</span> <span class="n">exc</span><span class="p">,</span> <span class="n">tb</span><span class="p">):</span> <span class="k">await</span> <span class="n">log</span><span class="p">(</span><span class="s1">&#39;exiting context&#39;</span><span class="p">)</span> </pre></div> </div> <div class="versionadded"> <p><span class="versionmodified added">Added in version 3.5.</span></p> </div> <p class="rubric">Footnotes</p> <aside class="footnote-list brackets"> <aside class="footnote brackets" id="id19" 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>It <em>is</em> possible in some cases to change an object’s type, under certain controlled conditions. It generally isn’t a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly.</p> </aside> <aside class="footnote brackets" id="id20" role="doc-footnote"> <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id12">2</a><span class="fn-bracket">]</span></span> <p>The <a class="reference internal" href="#object.__hash__" title="object.__hash__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__hash__()</span></code></a>, <a class="reference internal" href="#object.__iter__" title="object.__iter__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code></a>, <a class="reference internal" href="#object.__reversed__" title="object.__reversed__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__reversed__()</span></code></a>, <a class="reference internal" href="#object.__contains__" title="object.__contains__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__contains__()</span></code></a>, <a class="reference internal" href="#object.__class_getitem__" title="object.__class_getitem__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a> and <a class="reference internal" href="../library/os.html#os.PathLike.__fspath__" title="os.PathLike.__fspath__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__fspath__()</span></code></a> methods have special handling for this. Others will still raise a <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>, but may do so by relying on the behavior that <code class="docutils literal notranslate"><span class="pre">None</span></code> is not callable.</p> </aside> <aside class="footnote brackets" id="id21" role="doc-footnote"> <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id16">3</a><span class="fn-bracket">]</span></span> <p>“Does not support” here means that the class has no such method, or the method returns <a class="reference internal" href="../library/constants.html#NotImplemented" title="NotImplemented"><code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code></a>. Do not set the method to <code class="docutils literal notranslate"><span class="pre">None</span></code> if you want to force fallback to the right operand’s reflected method—that will instead have the opposite effect of explicitly <em>blocking</em> such fallback.</p> </aside> <aside class="footnote brackets" id="id22" role="doc-footnote"> <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id17">4</a><span class="fn-bracket">]</span></span> <p>For operands of the same type, it is assumed that if the non-reflected method – such as <a class="reference internal" href="#object.__add__" title="object.__add__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__add__()</span></code></a> – fails then the overall operation is not supported, which is why the reflected method is not called.</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="#">3. Data model</a><ul> <li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li> <li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a><ul> <li><a class="reference internal" href="#none">3.2.1. None</a></li> <li><a class="reference internal" href="#notimplemented">3.2.2. NotImplemented</a></li> <li><a class="reference internal" href="#ellipsis">3.2.3. Ellipsis</a></li> <li><a class="reference internal" href="#numbers-number">3.2.4. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Number</span></code></a><ul> <li><a class="reference internal" href="#numbers-integral">3.2.4.1. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Integral</span></code></a></li> <li><a class="reference internal" href="#numbers-real-float">3.2.4.2. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Real</span></code> (<code class="xref py py-class docutils literal notranslate"><span class="pre">float</span></code>)</a></li> <li><a class="reference internal" href="#numbers-complex-complex">3.2.4.3. <code class="xref py py-class docutils literal notranslate"><span class="pre">numbers.Complex</span></code> (<code class="xref py py-class docutils literal notranslate"><span class="pre">complex</span></code>)</a></li> </ul> </li> <li><a class="reference internal" href="#sequences">3.2.5. Sequences</a><ul> <li><a class="reference internal" href="#immutable-sequences">3.2.5.1. Immutable sequences</a></li> <li><a class="reference internal" href="#mutable-sequences">3.2.5.2. Mutable sequences</a></li> </ul> </li> <li><a class="reference internal" href="#set-types">3.2.6. Set types</a></li> <li><a class="reference internal" href="#mappings">3.2.7. Mappings</a><ul> <li><a class="reference internal" href="#dictionaries">3.2.7.1. Dictionaries</a></li> </ul> </li> <li><a class="reference internal" href="#callable-types">3.2.8. Callable types</a><ul> <li><a class="reference internal" href="#user-defined-functions">3.2.8.1. User-defined functions</a><ul> <li><a class="reference internal" href="#special-read-only-attributes">3.2.8.1.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#function.__globals__"><code class="docutils literal notranslate"><span class="pre">__globals__</span></code></a></li> <li><a class="reference internal" href="#function.__closure__"><code class="docutils literal notranslate"><span class="pre">__closure__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-writable-attributes">3.2.8.1.2. Special writable attributes</a><ul> <li><a class="reference internal" href="#function.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#function.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#function.__qualname__"><code class="docutils literal notranslate"><span class="pre">__qualname__</span></code></a></li> <li><a class="reference internal" href="#function.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> <li><a class="reference internal" href="#function.__defaults__"><code class="docutils literal notranslate"><span class="pre">__defaults__</span></code></a></li> <li><a class="reference internal" href="#function.__code__"><code class="docutils literal notranslate"><span class="pre">__code__</span></code></a></li> <li><a class="reference internal" href="#function.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> <li><a class="reference internal" href="#function.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> <li><a class="reference internal" href="#function.__kwdefaults__"><code class="docutils literal notranslate"><span class="pre">__kwdefaults__</span></code></a></li> <li><a class="reference internal" href="#function.__type_params__"><code class="docutils literal notranslate"><span class="pre">__type_params__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#instance-methods">3.2.8.2. Instance methods</a><ul> <li><a class="reference internal" href="#method.__self__"><code class="docutils literal notranslate"><span class="pre">__self__</span></code></a></li> <li><a class="reference internal" href="#method.__func__"><code class="docutils literal notranslate"><span class="pre">__func__</span></code></a></li> <li><a class="reference internal" href="#method.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#method.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#method.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#generator-functions">3.2.8.3. Generator functions</a></li> <li><a class="reference internal" href="#coroutine-functions">3.2.8.4. Coroutine functions</a></li> <li><a class="reference internal" href="#asynchronous-generator-functions">3.2.8.5. Asynchronous generator functions</a></li> <li><a class="reference internal" href="#built-in-functions">3.2.8.6. Built-in functions</a></li> <li><a class="reference internal" href="#built-in-methods">3.2.8.7. Built-in methods</a></li> <li><a class="reference internal" href="#classes">3.2.8.8. Classes</a></li> <li><a class="reference internal" href="#class-instances">3.2.8.9. Class Instances</a></li> </ul> </li> <li><a class="reference internal" href="#modules">3.2.9. Modules</a><ul> <li><a class="reference internal" href="#import-related-attributes-on-module-objects">3.2.9.1. Import-related attributes on module objects</a><ul> <li><a class="reference internal" href="#module.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#module.__spec__"><code class="docutils literal notranslate"><span class="pre">__spec__</span></code></a></li> <li><a class="reference internal" href="#module.__package__"><code class="docutils literal notranslate"><span class="pre">__package__</span></code></a></li> <li><a class="reference internal" href="#module.__loader__"><code class="docutils literal notranslate"><span class="pre">__loader__</span></code></a></li> <li><a class="reference internal" href="#module.__path__"><code class="docutils literal notranslate"><span class="pre">__path__</span></code></a></li> <li><a class="reference internal" href="#module.__file__"><code class="docutils literal notranslate"><span class="pre">__file__</span></code></a></li> <li><a class="reference internal" href="#module.__cached__"><code class="docutils literal notranslate"><span class="pre">__cached__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#other-writable-attributes-on-module-objects">3.2.9.2. Other writable attributes on module objects</a><ul> <li><a class="reference internal" href="#module.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#module.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#module-dictionaries">3.2.9.3. Module dictionaries</a><ul> <li><a class="reference internal" href="#module.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#custom-classes">3.2.10. Custom classes</a><ul> <li><a class="reference internal" href="#special-attributes">3.2.10.1. Special attributes</a><ul> <li><a class="reference internal" href="#type.__name__"><code class="docutils literal notranslate"><span class="pre">__name__</span></code></a></li> <li><a class="reference internal" href="#type.__qualname__"><code class="docutils literal notranslate"><span class="pre">__qualname__</span></code></a></li> <li><a class="reference internal" href="#type.__module__"><code class="docutils literal notranslate"><span class="pre">__module__</span></code></a></li> <li><a class="reference internal" href="#type.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> <li><a class="reference internal" href="#type.__bases__"><code class="docutils literal notranslate"><span class="pre">__bases__</span></code></a></li> <li><a class="reference internal" href="#type.__doc__"><code class="docutils literal notranslate"><span class="pre">__doc__</span></code></a></li> <li><a class="reference internal" href="#type.__annotations__"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code></a></li> <li><a class="reference internal" href="#type.__type_params__"><code class="docutils literal notranslate"><span class="pre">__type_params__</span></code></a></li> <li><a class="reference internal" href="#type.__static_attributes__"><code class="docutils literal notranslate"><span class="pre">__static_attributes__</span></code></a></li> <li><a class="reference internal" href="#type.__firstlineno__"><code class="docutils literal notranslate"><span class="pre">__firstlineno__</span></code></a></li> <li><a class="reference internal" href="#type.__mro__"><code class="docutils literal notranslate"><span class="pre">__mro__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-methods">3.2.10.2. Special methods</a><ul> <li><a class="reference internal" href="#type.mro"><code class="docutils literal notranslate"><span class="pre">mro()</span></code></a></li> <li><a class="reference internal" href="#type.__subclasses__"><code class="docutils literal notranslate"><span class="pre">__subclasses__()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#id4">3.2.11. Class instances</a><ul> <li><a class="reference internal" href="#id5">3.2.11.1. Special attributes</a><ul> <li><a class="reference internal" href="#object.__class__"><code class="docutils literal notranslate"><span class="pre">__class__</span></code></a></li> <li><a class="reference internal" href="#object.__dict__"><code class="docutils literal notranslate"><span class="pre">__dict__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#i-o-objects-also-known-as-file-objects">3.2.12. I/O objects (also known as file objects)</a></li> <li><a class="reference internal" href="#internal-types">3.2.13. Internal types</a><ul> <li><a class="reference internal" href="#code-objects">3.2.13.1. Code objects</a><ul> <li><a class="reference internal" href="#index-60">3.2.13.1.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#codeobject.co_name"><code class="docutils literal notranslate"><span class="pre">co_name</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_qualname"><code class="docutils literal notranslate"><span class="pre">co_qualname</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_argcount"><code class="docutils literal notranslate"><span class="pre">co_argcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_posonlyargcount"><code class="docutils literal notranslate"><span class="pre">co_posonlyargcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_kwonlyargcount"><code class="docutils literal notranslate"><span class="pre">co_kwonlyargcount</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_nlocals"><code class="docutils literal notranslate"><span class="pre">co_nlocals</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_varnames"><code class="docutils literal notranslate"><span class="pre">co_varnames</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_cellvars"><code class="docutils literal notranslate"><span class="pre">co_cellvars</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_freevars"><code class="docutils literal notranslate"><span class="pre">co_freevars</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_code"><code class="docutils literal notranslate"><span class="pre">co_code</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_consts"><code class="docutils literal notranslate"><span class="pre">co_consts</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_names"><code class="docutils literal notranslate"><span class="pre">co_names</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_filename"><code class="docutils literal notranslate"><span class="pre">co_filename</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_firstlineno"><code class="docutils literal notranslate"><span class="pre">co_firstlineno</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_lnotab"><code class="docutils literal notranslate"><span class="pre">co_lnotab</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_stacksize"><code class="docutils literal notranslate"><span class="pre">co_stacksize</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_flags"><code class="docutils literal notranslate"><span class="pre">co_flags</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#methods-on-code-objects">3.2.13.1.2. Methods on code objects</a><ul> <li><a class="reference internal" href="#codeobject.co_positions"><code class="docutils literal notranslate"><span class="pre">co_positions()</span></code></a></li> <li><a class="reference internal" href="#codeobject.co_lines"><code class="docutils literal notranslate"><span class="pre">co_lines()</span></code></a></li> <li><a class="reference internal" href="#codeobject.replace"><code class="docutils literal notranslate"><span class="pre">replace()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#frame-objects">3.2.13.2. Frame objects</a><ul> <li><a class="reference internal" href="#index-66">3.2.13.2.1. Special read-only attributes</a><ul> <li><a class="reference internal" href="#frame.f_back"><code class="docutils literal notranslate"><span class="pre">f_back</span></code></a></li> <li><a class="reference internal" href="#frame.f_code"><code class="docutils literal notranslate"><span class="pre">f_code</span></code></a></li> <li><a class="reference internal" href="#frame.f_locals"><code class="docutils literal notranslate"><span class="pre">f_locals</span></code></a></li> <li><a class="reference internal" href="#frame.f_globals"><code class="docutils literal notranslate"><span class="pre">f_globals</span></code></a></li> <li><a class="reference internal" href="#frame.f_builtins"><code class="docutils literal notranslate"><span class="pre">f_builtins</span></code></a></li> <li><a class="reference internal" href="#frame.f_lasti"><code class="docutils literal notranslate"><span class="pre">f_lasti</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#index-67">3.2.13.2.2. Special writable attributes</a><ul> <li><a class="reference internal" href="#frame.f_trace"><code class="docutils literal notranslate"><span class="pre">f_trace</span></code></a></li> <li><a class="reference internal" href="#frame.f_trace_lines"><code class="docutils literal notranslate"><span class="pre">f_trace_lines</span></code></a></li> <li><a class="reference internal" href="#frame.f_trace_opcodes"><code class="docutils literal notranslate"><span class="pre">f_trace_opcodes</span></code></a></li> <li><a class="reference internal" href="#frame.f_lineno"><code class="docutils literal notranslate"><span class="pre">f_lineno</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#frame-object-methods">3.2.13.2.3. Frame object methods</a><ul> <li><a class="reference internal" href="#frame.clear"><code class="docutils literal notranslate"><span class="pre">clear()</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#traceback-objects">3.2.13.3. Traceback objects</a><ul> <li><a class="reference internal" href="#traceback.tb_frame"><code class="docutils literal notranslate"><span class="pre">tb_frame</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_lineno"><code class="docutils literal notranslate"><span class="pre">tb_lineno</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_lasti"><code class="docutils literal notranslate"><span class="pre">tb_lasti</span></code></a></li> <li><a class="reference internal" href="#traceback.tb_next"><code class="docutils literal notranslate"><span class="pre">tb_next</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#slice-objects">3.2.13.4. Slice objects</a><ul> <li><a class="reference internal" href="#slice.indices"><code class="docutils literal notranslate"><span class="pre">indices()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#static-method-objects">3.2.13.5. Static method objects</a></li> <li><a class="reference internal" href="#class-method-objects">3.2.13.6. Class method objects</a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul> <li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a><ul> <li><a class="reference internal" href="#object.__new__"><code class="docutils literal notranslate"><span class="pre">__new__()</span></code></a></li> <li><a class="reference internal" href="#object.__init__"><code class="docutils literal notranslate"><span class="pre">__init__()</span></code></a></li> <li><a class="reference internal" href="#object.__del__"><code class="docutils literal notranslate"><span class="pre">__del__()</span></code></a></li> <li><a class="reference internal" href="#object.__repr__"><code class="docutils literal notranslate"><span class="pre">__repr__()</span></code></a></li> <li><a class="reference internal" href="#object.__str__"><code class="docutils literal notranslate"><span class="pre">__str__()</span></code></a></li> <li><a class="reference internal" href="#object.__bytes__"><code class="docutils literal notranslate"><span class="pre">__bytes__()</span></code></a></li> <li><a class="reference internal" href="#object.__format__"><code class="docutils literal notranslate"><span class="pre">__format__()</span></code></a></li> <li><a class="reference internal" href="#object.__lt__"><code class="docutils literal notranslate"><span class="pre">__lt__()</span></code></a></li> <li><a class="reference internal" href="#object.__le__"><code class="docutils literal notranslate"><span class="pre">__le__()</span></code></a></li> <li><a class="reference internal" href="#object.__eq__"><code class="docutils literal notranslate"><span class="pre">__eq__()</span></code></a></li> <li><a class="reference internal" href="#object.__ne__"><code class="docutils literal notranslate"><span class="pre">__ne__()</span></code></a></li> <li><a class="reference internal" href="#object.__gt__"><code class="docutils literal notranslate"><span class="pre">__gt__()</span></code></a></li> <li><a class="reference internal" href="#object.__ge__"><code class="docutils literal notranslate"><span class="pre">__ge__()</span></code></a></li> <li><a class="reference internal" href="#object.__hash__"><code class="docutils literal notranslate"><span class="pre">__hash__()</span></code></a></li> <li><a class="reference internal" href="#object.__bool__"><code class="docutils literal notranslate"><span class="pre">__bool__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul> <li><a class="reference internal" href="#object.__getattr__"><code class="docutils literal notranslate"><span class="pre">__getattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__getattribute__"><code class="docutils literal notranslate"><span class="pre">__getattribute__()</span></code></a></li> <li><a class="reference internal" href="#object.__setattr__"><code class="docutils literal notranslate"><span class="pre">__setattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__delattr__"><code class="docutils literal notranslate"><span class="pre">__delattr__()</span></code></a></li> <li><a class="reference internal" href="#object.__dir__"><code class="docutils literal notranslate"><span class="pre">__dir__()</span></code></a></li> <li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. Customizing module attribute access</a></li> <li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. Implementing Descriptors</a><ul> <li><a class="reference internal" href="#object.__get__"><code class="docutils literal notranslate"><span class="pre">__get__()</span></code></a></li> <li><a class="reference internal" href="#object.__set__"><code class="docutils literal notranslate"><span class="pre">__set__()</span></code></a></li> <li><a class="reference internal" href="#object.__delete__"><code class="docutils literal notranslate"><span class="pre">__delete__()</span></code></a></li> <li><a class="reference internal" href="#object.__objclass__"><code class="docutils literal notranslate"><span class="pre">__objclass__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. Invoking Descriptors</a></li> <li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a><ul> <li><a class="reference internal" href="#object.__slots__"><code class="docutils literal notranslate"><span class="pre">__slots__</span></code></a></li> </ul> </li> </ul> </li> <li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul> <li><a class="reference internal" href="#object.__init_subclass__"><code class="docutils literal notranslate"><span class="pre">__init_subclass__()</span></code></a></li> <li><a class="reference internal" href="#object.__set_name__"><code class="docutils literal notranslate"><span class="pre">__set_name__()</span></code></a></li> <li><a class="reference internal" href="#metaclasses">3.3.3.1. Metaclasses</a></li> <li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. Resolving MRO entries</a><ul> <li><a class="reference internal" href="#object.__mro_entries__"><code class="docutils literal notranslate"><span class="pre">__mro_entries__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. Determining the appropriate metaclass</a></li> <li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. Preparing the class namespace</a></li> <li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. Executing the class body</a></li> <li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. Creating the class object</a></li> <li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. Uses for metaclasses</a></li> </ul> </li> <li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a><ul> <li><a class="reference internal" href="#type.__instancecheck__"><code class="docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a></li> <li><a class="reference internal" href="#type.__subclasscheck__"><code class="docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-generic-types">3.3.5. Emulating generic types</a><ul> <li><a class="reference internal" href="#object.__class_getitem__"><code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code></a></li> <li><a class="reference internal" href="#the-purpose-of-class-getitem">3.3.5.1. The purpose of <em>__class_getitem__</em></a></li> <li><a class="reference internal" href="#class-getitem-versus-getitem">3.3.5.2. <em>__class_getitem__</em> versus <em>__getitem__</em></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-callable-objects">3.3.6. Emulating callable objects</a><ul> <li><a class="reference internal" href="#object.__call__"><code class="docutils literal notranslate"><span class="pre">__call__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-container-types">3.3.7. Emulating container types</a><ul> <li><a class="reference internal" href="#object.__len__"><code class="docutils literal notranslate"><span class="pre">__len__()</span></code></a></li> <li><a class="reference internal" href="#object.__length_hint__"><code class="docutils literal notranslate"><span class="pre">__length_hint__()</span></code></a></li> <li><a class="reference internal" href="#object.__getitem__"><code class="docutils literal notranslate"><span class="pre">__getitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__setitem__"><code class="docutils literal notranslate"><span class="pre">__setitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__delitem__"><code class="docutils literal notranslate"><span class="pre">__delitem__()</span></code></a></li> <li><a class="reference internal" href="#object.__missing__"><code class="docutils literal notranslate"><span class="pre">__missing__()</span></code></a></li> <li><a class="reference internal" href="#object.__iter__"><code class="docutils literal notranslate"><span class="pre">__iter__()</span></code></a></li> <li><a class="reference internal" href="#object.__reversed__"><code class="docutils literal notranslate"><span class="pre">__reversed__()</span></code></a></li> <li><a class="reference internal" href="#object.__contains__"><code class="docutils literal notranslate"><span class="pre">__contains__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-numeric-types">3.3.8. Emulating numeric types</a><ul> <li><a class="reference internal" href="#object.__add__"><code class="docutils literal notranslate"><span class="pre">__add__()</span></code></a></li> <li><a class="reference internal" href="#object.__sub__"><code class="docutils literal notranslate"><span class="pre">__sub__()</span></code></a></li> <li><a class="reference internal" href="#object.__mul__"><code class="docutils literal notranslate"><span class="pre">__mul__()</span></code></a></li> <li><a class="reference internal" href="#object.__matmul__"><code class="docutils literal notranslate"><span class="pre">__matmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__truediv__"><code class="docutils literal notranslate"><span class="pre">__truediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__floordiv__"><code class="docutils literal notranslate"><span class="pre">__floordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__mod__"><code class="docutils literal notranslate"><span class="pre">__mod__()</span></code></a></li> <li><a class="reference internal" href="#object.__divmod__"><code class="docutils literal notranslate"><span class="pre">__divmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__pow__"><code class="docutils literal notranslate"><span class="pre">__pow__()</span></code></a></li> <li><a class="reference internal" href="#object.__lshift__"><code class="docutils literal notranslate"><span class="pre">__lshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rshift__"><code class="docutils literal notranslate"><span class="pre">__rshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__and__"><code class="docutils literal notranslate"><span class="pre">__and__()</span></code></a></li> <li><a class="reference internal" href="#object.__xor__"><code class="docutils literal notranslate"><span class="pre">__xor__()</span></code></a></li> <li><a class="reference internal" href="#object.__or__"><code class="docutils literal notranslate"><span class="pre">__or__()</span></code></a></li> <li><a class="reference internal" href="#object.__radd__"><code class="docutils literal notranslate"><span class="pre">__radd__()</span></code></a></li> <li><a class="reference internal" href="#object.__rsub__"><code class="docutils literal notranslate"><span class="pre">__rsub__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmul__"><code class="docutils literal notranslate"><span class="pre">__rmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmatmul__"><code class="docutils literal notranslate"><span class="pre">__rmatmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__rtruediv__"><code class="docutils literal notranslate"><span class="pre">__rtruediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__rfloordiv__"><code class="docutils literal notranslate"><span class="pre">__rfloordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__rmod__"><code class="docutils literal notranslate"><span class="pre">__rmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__rdivmod__"><code class="docutils literal notranslate"><span class="pre">__rdivmod__()</span></code></a></li> <li><a class="reference internal" href="#object.__rpow__"><code class="docutils literal notranslate"><span class="pre">__rpow__()</span></code></a></li> <li><a class="reference internal" href="#object.__rlshift__"><code class="docutils literal notranslate"><span class="pre">__rlshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rrshift__"><code class="docutils literal notranslate"><span class="pre">__rrshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__rand__"><code class="docutils literal notranslate"><span class="pre">__rand__()</span></code></a></li> <li><a class="reference internal" href="#object.__rxor__"><code class="docutils literal notranslate"><span class="pre">__rxor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ror__"><code class="docutils literal notranslate"><span class="pre">__ror__()</span></code></a></li> <li><a class="reference internal" href="#object.__iadd__"><code class="docutils literal notranslate"><span class="pre">__iadd__()</span></code></a></li> <li><a class="reference internal" href="#object.__isub__"><code class="docutils literal notranslate"><span class="pre">__isub__()</span></code></a></li> <li><a class="reference internal" href="#object.__imul__"><code class="docutils literal notranslate"><span class="pre">__imul__()</span></code></a></li> <li><a class="reference internal" href="#object.__imatmul__"><code class="docutils literal notranslate"><span class="pre">__imatmul__()</span></code></a></li> <li><a class="reference internal" href="#object.__itruediv__"><code class="docutils literal notranslate"><span class="pre">__itruediv__()</span></code></a></li> <li><a class="reference internal" href="#object.__ifloordiv__"><code class="docutils literal notranslate"><span class="pre">__ifloordiv__()</span></code></a></li> <li><a class="reference internal" href="#object.__imod__"><code class="docutils literal notranslate"><span class="pre">__imod__()</span></code></a></li> <li><a class="reference internal" href="#object.__ipow__"><code class="docutils literal notranslate"><span class="pre">__ipow__()</span></code></a></li> <li><a class="reference internal" href="#object.__ilshift__"><code class="docutils literal notranslate"><span class="pre">__ilshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__irshift__"><code class="docutils literal notranslate"><span class="pre">__irshift__()</span></code></a></li> <li><a class="reference internal" href="#object.__iand__"><code class="docutils literal notranslate"><span class="pre">__iand__()</span></code></a></li> <li><a class="reference internal" href="#object.__ixor__"><code class="docutils literal notranslate"><span class="pre">__ixor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ior__"><code class="docutils literal notranslate"><span class="pre">__ior__()</span></code></a></li> <li><a class="reference internal" href="#object.__neg__"><code class="docutils literal notranslate"><span class="pre">__neg__()</span></code></a></li> <li><a class="reference internal" href="#object.__pos__"><code class="docutils literal notranslate"><span class="pre">__pos__()</span></code></a></li> <li><a class="reference internal" href="#object.__abs__"><code class="docutils literal notranslate"><span class="pre">__abs__()</span></code></a></li> <li><a class="reference internal" href="#object.__invert__"><code class="docutils literal notranslate"><span class="pre">__invert__()</span></code></a></li> <li><a class="reference internal" href="#object.__complex__"><code class="docutils literal notranslate"><span class="pre">__complex__()</span></code></a></li> <li><a class="reference internal" href="#object.__int__"><code class="docutils literal notranslate"><span class="pre">__int__()</span></code></a></li> <li><a class="reference internal" href="#object.__float__"><code class="docutils literal notranslate"><span class="pre">__float__()</span></code></a></li> <li><a class="reference internal" href="#object.__index__"><code class="docutils literal notranslate"><span class="pre">__index__()</span></code></a></li> <li><a class="reference internal" href="#object.__round__"><code class="docutils literal notranslate"><span class="pre">__round__()</span></code></a></li> <li><a class="reference internal" href="#object.__trunc__"><code class="docutils literal notranslate"><span class="pre">__trunc__()</span></code></a></li> <li><a class="reference internal" href="#object.__floor__"><code class="docutils literal notranslate"><span class="pre">__floor__()</span></code></a></li> <li><a class="reference internal" href="#object.__ceil__"><code class="docutils literal notranslate"><span class="pre">__ceil__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#with-statement-context-managers">3.3.9. With Statement Context Managers</a><ul> <li><a class="reference internal" href="#object.__enter__"><code class="docutils literal notranslate"><span class="pre">__enter__()</span></code></a></li> <li><a class="reference internal" href="#object.__exit__"><code class="docutils literal notranslate"><span class="pre">__exit__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#customizing-positional-arguments-in-class-pattern-matching">3.3.10. Customizing positional arguments in class pattern matching</a><ul> <li><a class="reference internal" href="#object.__match_args__"><code class="docutils literal notranslate"><span class="pre">__match_args__</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#emulating-buffer-types">3.3.11. Emulating buffer types</a><ul> <li><a class="reference internal" href="#object.__buffer__"><code class="docutils literal notranslate"><span class="pre">__buffer__()</span></code></a></li> <li><a class="reference internal" href="#object.__release_buffer__"><code class="docutils literal notranslate"><span class="pre">__release_buffer__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#special-method-lookup">3.3.12. Special method lookup</a></li> </ul> </li> <li><a class="reference internal" href="#coroutines">3.4. Coroutines</a><ul> <li><a class="reference internal" href="#awaitable-objects">3.4.1. Awaitable Objects</a><ul> <li><a class="reference internal" href="#object.__await__"><code class="docutils literal notranslate"><span class="pre">__await__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#coroutine-objects">3.4.2. Coroutine Objects</a><ul> <li><a class="reference internal" href="#coroutine.send"><code class="docutils literal notranslate"><span class="pre">send()</span></code></a></li> <li><a class="reference internal" href="#coroutine.throw"><code class="docutils literal notranslate"><span class="pre">throw()</span></code></a></li> <li><a class="reference internal" href="#coroutine.close"><code class="docutils literal notranslate"><span class="pre">close()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#asynchronous-iterators">3.4.3. Asynchronous Iterators</a><ul> <li><a class="reference internal" href="#object.__aiter__"><code class="docutils literal notranslate"><span class="pre">__aiter__()</span></code></a></li> <li><a class="reference internal" href="#object.__anext__"><code class="docutils literal notranslate"><span class="pre">__anext__()</span></code></a></li> </ul> </li> <li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. Asynchronous Context Managers</a><ul> <li><a class="reference internal" href="#object.__aenter__"><code class="docutils literal notranslate"><span class="pre">__aenter__()</span></code></a></li> <li><a class="reference internal" href="#object.__aexit__"><code class="docutils literal notranslate"><span class="pre">__aexit__()</span></code></a></li> </ul> </li> </ul> </li> </ul> </li> </ul> </div> <div> <h4>Previous topic</h4> <p class="topless"><a href="lexical_analysis.html" title="previous chapter"><span class="section-number">2. </span>Lexical analysis</a></p> </div> <div> <h4>Next topic</h4> <p class="topless"><a href="executionmodel.html" title="next chapter"><span class="section-number">4. </span>Execution model</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/reference/datamodel.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="executionmodel.html" title="4. Execution model" >next</a> |</li> <li class="right" > <a href="lexical_analysis.html" title="2. Lexical analysis" >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> &#187;</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.0 Documentation</a> &#187; </li> <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li> <li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>Data model</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"> &copy; <a href="../copyright.html"> Copyright </a> 2001-2024, 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 Nov 24, 2024 (17:50 UTC). <a href="/bugs.html">Found a bug</a>? <br /> Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.1.3. </div> <script type="text/javascript" src="../_static/switchers.js"></script> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10