gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3657 line
395KB

  1. <!DOCTYPE html>
  2. <html lang="en" data-content_root="../">
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />
  6. <meta property="og:title" content="3. Data model" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/reference/datamodel.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <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 ..." />
  11. <meta property="og:image" content="https://docs.python.org/3/_static/og-image.png" />
  12. <meta property="og:image:alt" content="Python documentation" />
  13. <meta name="description" content="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 ..." />
  14. <meta property="og:image:width" content="200" />
  15. <meta property="og:image:height" content="200" />
  16. <meta name="theme-color" content="#3776ab" />
  17. <title>3. Data model &#8212; Python 3.12.3 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=80d5e7a1" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=bb723527" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=b20cc3f5" />
  21. <script src="../_static/documentation_options.js?v=2c828074"></script>
  22. <script src="../_static/doctools.js?v=888ff710"></script>
  23. <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>
  24. <script src="../_static/sidebar.js"></script>
  25. <link rel="search" type="application/opensearchdescription+xml"
  26. title="Search within Python 3.12.3 documentation"
  27. href="../_static/opensearch.xml"/>
  28. <link rel="author" title="About these documents" href="../about.html" />
  29. <link rel="index" title="Index" href="../genindex.html" />
  30. <link rel="search" title="Search" href="../search.html" />
  31. <link rel="copyright" title="Copyright" href="../copyright.html" />
  32. <link rel="next" title="4. Execution model" href="executionmodel.html" />
  33. <link rel="prev" title="2. Lexical analysis" href="lexical_analysis.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/reference/datamodel.html" />
  35. <style>
  36. @media only screen {
  37. table.full-width-table {
  38. width: 100%;
  39. }
  40. }
  41. </style>
  42. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  43. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  44. <script type="text/javascript" src="../_static/copybutton.js"></script>
  45. <script type="text/javascript" src="../_static/menu.js"></script>
  46. <script type="text/javascript" src="../_static/search-focus.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Python logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">3. Data model</a><ul>
  86. <li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
  87. <li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a><ul>
  88. <li><a class="reference internal" href="#none">3.2.1. None</a></li>
  89. <li><a class="reference internal" href="#notimplemented">3.2.2. NotImplemented</a></li>
  90. <li><a class="reference internal" href="#ellipsis">3.2.3. Ellipsis</a></li>
  91. <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>
  92. <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>
  93. <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>
  94. <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>
  95. </ul>
  96. </li>
  97. <li><a class="reference internal" href="#sequences">3.2.5. Sequences</a><ul>
  98. <li><a class="reference internal" href="#immutable-sequences">3.2.5.1. Immutable sequences</a></li>
  99. <li><a class="reference internal" href="#mutable-sequences">3.2.5.2. Mutable sequences</a></li>
  100. </ul>
  101. </li>
  102. <li><a class="reference internal" href="#set-types">3.2.6. Set types</a></li>
  103. <li><a class="reference internal" href="#mappings">3.2.7. Mappings</a><ul>
  104. <li><a class="reference internal" href="#dictionaries">3.2.7.1. Dictionaries</a></li>
  105. </ul>
  106. </li>
  107. <li><a class="reference internal" href="#callable-types">3.2.8. Callable types</a><ul>
  108. <li><a class="reference internal" href="#user-defined-functions">3.2.8.1. User-defined functions</a><ul>
  109. <li><a class="reference internal" href="#special-read-only-attributes">3.2.8.1.1. Special read-only attributes</a></li>
  110. <li><a class="reference internal" href="#special-writable-attributes">3.2.8.1.2. Special writable attributes</a></li>
  111. </ul>
  112. </li>
  113. <li><a class="reference internal" href="#instance-methods">3.2.8.2. Instance methods</a></li>
  114. <li><a class="reference internal" href="#generator-functions">3.2.8.3. Generator functions</a></li>
  115. <li><a class="reference internal" href="#coroutine-functions">3.2.8.4. Coroutine functions</a></li>
  116. <li><a class="reference internal" href="#asynchronous-generator-functions">3.2.8.5. Asynchronous generator functions</a></li>
  117. <li><a class="reference internal" href="#built-in-functions">3.2.8.6. Built-in functions</a></li>
  118. <li><a class="reference internal" href="#built-in-methods">3.2.8.7. Built-in methods</a></li>
  119. <li><a class="reference internal" href="#classes">3.2.8.8. Classes</a></li>
  120. <li><a class="reference internal" href="#class-instances">3.2.8.9. Class Instances</a></li>
  121. </ul>
  122. </li>
  123. <li><a class="reference internal" href="#modules">3.2.9. Modules</a></li>
  124. <li><a class="reference internal" href="#custom-classes">3.2.10. Custom classes</a></li>
  125. <li><a class="reference internal" href="#id3">3.2.11. Class instances</a></li>
  126. <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>
  127. <li><a class="reference internal" href="#internal-types">3.2.13. Internal types</a><ul>
  128. <li><a class="reference internal" href="#code-objects">3.2.13.1. Code objects</a><ul>
  129. <li><a class="reference internal" href="#index-58">3.2.13.1.1. Special read-only attributes</a></li>
  130. <li><a class="reference internal" href="#methods-on-code-objects">3.2.13.1.2. Methods on code objects</a></li>
  131. </ul>
  132. </li>
  133. <li><a class="reference internal" href="#frame-objects">3.2.13.2. Frame objects</a><ul>
  134. <li><a class="reference internal" href="#index-64">3.2.13.2.1. Special read-only attributes</a></li>
  135. <li><a class="reference internal" href="#index-65">3.2.13.2.2. Special writable attributes</a></li>
  136. <li><a class="reference internal" href="#frame-object-methods">3.2.13.2.3. Frame object methods</a></li>
  137. </ul>
  138. </li>
  139. <li><a class="reference internal" href="#traceback-objects">3.2.13.3. Traceback objects</a></li>
  140. <li><a class="reference internal" href="#slice-objects">3.2.13.4. Slice objects</a></li>
  141. <li><a class="reference internal" href="#static-method-objects">3.2.13.5. Static method objects</a></li>
  142. <li><a class="reference internal" href="#class-method-objects">3.2.13.6. Class method objects</a></li>
  143. </ul>
  144. </li>
  145. </ul>
  146. </li>
  147. <li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul>
  148. <li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a></li>
  149. <li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul>
  150. <li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. Customizing module attribute access</a></li>
  151. <li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. Implementing Descriptors</a></li>
  152. <li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. Invoking Descriptors</a></li>
  153. <li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a></li>
  154. </ul>
  155. </li>
  156. <li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul>
  157. <li><a class="reference internal" href="#metaclasses">3.3.3.1. Metaclasses</a></li>
  158. <li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. Resolving MRO entries</a></li>
  159. <li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. Determining the appropriate metaclass</a></li>
  160. <li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. Preparing the class namespace</a></li>
  161. <li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. Executing the class body</a></li>
  162. <li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. Creating the class object</a></li>
  163. <li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. Uses for metaclasses</a></li>
  164. </ul>
  165. </li>
  166. <li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a></li>
  167. <li><a class="reference internal" href="#emulating-generic-types">3.3.5. Emulating generic types</a><ul>
  168. <li><a class="reference internal" href="#the-purpose-of-class-getitem">3.3.5.1. The purpose of <em>__class_getitem__</em></a></li>
  169. <li><a class="reference internal" href="#class-getitem-versus-getitem">3.3.5.2. <em>__class_getitem__</em> versus <em>__getitem__</em></a></li>
  170. </ul>
  171. </li>
  172. <li><a class="reference internal" href="#emulating-callable-objects">3.3.6. Emulating callable objects</a></li>
  173. <li><a class="reference internal" href="#emulating-container-types">3.3.7. Emulating container types</a></li>
  174. <li><a class="reference internal" href="#emulating-numeric-types">3.3.8. Emulating numeric types</a></li>
  175. <li><a class="reference internal" href="#with-statement-context-managers">3.3.9. With Statement Context Managers</a></li>
  176. <li><a class="reference internal" href="#customizing-positional-arguments-in-class-pattern-matching">3.3.10. Customizing positional arguments in class pattern matching</a></li>
  177. <li><a class="reference internal" href="#emulating-buffer-types">3.3.11. Emulating buffer types</a></li>
  178. <li><a class="reference internal" href="#special-method-lookup">3.3.12. Special method lookup</a></li>
  179. </ul>
  180. </li>
  181. <li><a class="reference internal" href="#coroutines">3.4. Coroutines</a><ul>
  182. <li><a class="reference internal" href="#awaitable-objects">3.4.1. Awaitable Objects</a></li>
  183. <li><a class="reference internal" href="#coroutine-objects">3.4.2. Coroutine Objects</a></li>
  184. <li><a class="reference internal" href="#asynchronous-iterators">3.4.3. Asynchronous Iterators</a></li>
  185. <li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. Asynchronous Context Managers</a></li>
  186. </ul>
  187. </li>
  188. </ul>
  189. </li>
  190. </ul>
  191. </div>
  192. <div>
  193. <h4>Previous topic</h4>
  194. <p class="topless"><a href="lexical_analysis.html"
  195. title="previous chapter"><span class="section-number">2. </span>Lexical analysis</a></p>
  196. </div>
  197. <div>
  198. <h4>Next topic</h4>
  199. <p class="topless"><a href="executionmodel.html"
  200. title="next chapter"><span class="section-number">4. </span>Execution model</a></p>
  201. </div>
  202. <div role="note" aria-label="source link">
  203. <h3>This Page</h3>
  204. <ul class="this-page-menu">
  205. <li><a href="../bugs.html">Report a Bug</a></li>
  206. <li>
  207. <a href="https://github.com/python/cpython/blob/main/Doc/reference/datamodel.rst"
  208. rel="nofollow">Show Source
  209. </a>
  210. </li>
  211. </ul>
  212. </div>
  213. </nav>
  214. </div>
  215. </div>
  216. <div class="related" role="navigation" aria-label="related navigation">
  217. <h3>Navigation</h3>
  218. <ul>
  219. <li class="right" style="margin-right: 10px">
  220. <a href="../genindex.html" title="General Index"
  221. accesskey="I">index</a></li>
  222. <li class="right" >
  223. <a href="../py-modindex.html" title="Python Module Index"
  224. >modules</a> |</li>
  225. <li class="right" >
  226. <a href="executionmodel.html" title="4. Execution model"
  227. accesskey="N">next</a> |</li>
  228. <li class="right" >
  229. <a href="lexical_analysis.html" title="2. Lexical analysis"
  230. accesskey="P">previous</a> |</li>
  231. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  232. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  233. <li class="switchers">
  234. <div class="language_switcher_placeholder"></div>
  235. <div class="version_switcher_placeholder"></div>
  236. </li>
  237. <li>
  238. </li>
  239. <li id="cpython-language-and-version">
  240. <a href="../index.html">3.12.3 Documentation</a> &#187;
  241. </li>
  242. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">The Python Language Reference</a> &#187;</li>
  243. <li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>Data model</a></li>
  244. <li class="right">
  245. <div class="inline-search" role="search">
  246. <form class="inline-search" action="../search.html" method="get">
  247. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  248. <input type="submit" value="Go" />
  249. </form>
  250. </div>
  251. |
  252. </li>
  253. <li class="right">
  254. <label class="theme-selector-label">
  255. Theme
  256. <select class="theme-selector" oninput="activateTheme(this.value)">
  257. <option value="auto" selected>Auto</option>
  258. <option value="light">Light</option>
  259. <option value="dark">Dark</option>
  260. </select>
  261. </label> |</li>
  262. </ul>
  263. </div>
  264. <div class="document">
  265. <div class="documentwrapper">
  266. <div class="bodywrapper">
  267. <div class="body" role="main">
  268. <section id="data-model">
  269. <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>
  270. <section id="objects-values-and-types">
  271. <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>
  272. <p id="index-0"><em class="dfn">Objects</em> are Python’s abstraction for data. All data in a Python program
  273. is represented by objects or by relations between objects. (In a sense, and in
  274. conformance to Von Neumann’s model of a “stored program computer”, code is also
  275. represented by objects.)</p>
  276. <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
  277. changes once it has been created; you may think of it as the object’s address in
  278. 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
  279. <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>
  280. <div class="impl-detail compound">
  281. <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>
  282. </div>
  283. <p>An object’s type determines the operations that the object supports (e.g., “does
  284. it have a length?”) and also defines the possible values for objects of that
  285. 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
  286. itself). Like its identity, an object’s <em class="dfn">type</em> is also unchangeable.
  287. <a class="footnote-reference brackets" href="#id17" id="id1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a></p>
  288. <p>The <em>value</em> of some objects can change. Objects whose value can
  289. change are said to be <em>mutable</em>; objects whose value is unchangeable once they
  290. are created are called <em>immutable</em>. (The value of an immutable container object
  291. that contains a reference to a mutable object can change when the latter’s value
  292. is changed; however the container is still considered immutable, because the
  293. collection of objects it contains cannot be changed. So, immutability is not
  294. strictly the same as having an unchangeable value, it is more subtle.) An
  295. object’s mutability is determined by its type; for instance, numbers, strings
  296. and tuples are immutable, while dictionaries and lists are mutable.</p>
  297. <p id="index-2">Objects are never explicitly destroyed; however, when they become unreachable
  298. they may be garbage-collected. An implementation is allowed to postpone garbage
  299. collection or omit it altogether — it is a matter of implementation quality
  300. how garbage collection is implemented, as long as no objects are collected that
  301. are still reachable.</p>
  302. <div class="impl-detail compound">
  303. <p><strong>CPython implementation detail:</strong> CPython currently uses a reference-counting scheme with (optional) delayed
  304. detection of cyclically linked garbage, which collects most objects as soon
  305. as they become unreachable, but is not guaranteed to collect garbage
  306. 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>
  307. module for information on controlling the collection of cyclic garbage.
  308. Other implementations act differently and CPython may change.
  309. Do not depend on immediate finalization of objects when they become
  310. unreachable (so you should always close files explicitly).</p>
  311. </div>
  312. <p>Note that the use of the implementation’s tracing or debugging facilities may
  313. keep objects alive that would normally be collectable. Also note that catching
  314. 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
  315. objects alive.</p>
  316. <p>Some objects contain references to “external” resources such as open files or
  317. windows. It is understood that these resources are freed when the object is
  318. garbage-collected, but since garbage collection is not guaranteed to happen,
  319. such objects also provide an explicit way to release the external resource,
  320. usually a <code class="xref py py-meth docutils literal notranslate"><span class="pre">close()</span></code> method. Programs are strongly recommended to explicitly
  321. 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
  322. 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>
  323. <p id="index-3">Some objects contain references to other objects; these are called <em>containers</em>.
  324. Examples of containers are tuples, lists and dictionaries. The references are
  325. part of a container’s value. In most cases, when we talk about the value of a
  326. container, we imply the values, not the identities of the contained objects;
  327. however, when we talk about the mutability of a container, only the identities
  328. of the immediately contained objects are implied. So, if an immutable container
  329. (like a tuple) contains a reference to a mutable object, its value changes if
  330. that mutable object is changed.</p>
  331. <p>Types affect almost all aspects of object behavior. Even the importance of
  332. object identity is affected in some sense: for immutable types, operations that
  333. compute new values may actually return a reference to any existing object with
  334. the same type and value, while for mutable objects this is not allowed. E.g.,
  335. 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>, <code class="docutils literal notranslate"><span class="pre">a</span></code> and <code class="docutils literal notranslate"><span class="pre">b</span></code> may or may not refer to the same object
  336. with the value one, depending on the implementation, but 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>
  337. <span class="pre">[]</span></code>, <code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code> are guaranteed to refer to two different, unique, newly
  338. created empty lists. (Note that <code class="docutils literal notranslate"><span class="pre">c</span> <span class="pre">=</span> <span class="pre">d</span> <span class="pre">=</span> <span class="pre">[]</span></code> assigns the same object to both
  339. <code class="docutils literal notranslate"><span class="pre">c</span></code> and <code class="docutils literal notranslate"><span class="pre">d</span></code>.)</p>
  340. </section>
  341. <section id="the-standard-type-hierarchy">
  342. <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>
  343. <p id="index-4">Below is a list of the types that are built into Python. Extension modules
  344. (written in C, Java, or other languages, depending on the implementation) can
  345. define additional types. Future versions of Python may add types to the type
  346. hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.),
  347. although such additions will often be provided via the standard library instead.</p>
  348. <p id="index-5">Some of the type descriptions below contain a paragraph listing ‘special
  349. attributes.’ These are attributes that provide access to the implementation and
  350. are not intended for general use. Their definition may change in the future.</p>
  351. <section id="none">
  352. <h3><span class="section-number">3.2.1. </span>None<a class="headerlink" href="#none" title="Link to this heading">¶</a></h3>
  353. <p id="index-6">This type has a single value. There is a single object with this value. This
  354. 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
  355. absence of a value in many situations, e.g., it is returned from functions that
  356. don’t explicitly return anything. Its truth value is false.</p>
  357. </section>
  358. <section id="notimplemented">
  359. <h3><span class="section-number">3.2.2. </span>NotImplemented<a class="headerlink" href="#notimplemented" title="Link to this heading">¶</a></h3>
  360. <p id="index-7">This type has a single value. There is a single object with this value. This
  361. 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
  362. and rich comparison methods should return this value if they do not implement the
  363. operation for the operands provided. (The interpreter will then try the
  364. reflected operation, or some other fallback, depending on the operator.) It
  365. should not be evaluated in a boolean context.</p>
  366. <p>See
  367. <a class="reference internal" href="../library/numbers.html#implementing-the-arithmetic-operations"><span class="std std-ref">Implementing the arithmetic operations</span></a>
  368. for more details.</p>
  369. <div class="versionchanged">
  370. <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
  371. 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>.
  372. 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>
  373. </div>
  374. </section>
  375. <section id="ellipsis">
  376. <h3><span class="section-number">3.2.3. </span>Ellipsis<a class="headerlink" href="#ellipsis" title="Link to this heading">¶</a></h3>
  377. <p id="index-8">This type has a single value. There is a single object with this value. This
  378. object is accessed through the literal <code class="docutils literal notranslate"><span class="pre">...</span></code> or the built-in name
  379. <code class="docutils literal notranslate"><span class="pre">Ellipsis</span></code>. Its truth value is true.</p>
  380. </section>
  381. <section id="numbers-number">
  382. <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>
  383. <p id="index-9">These are created by numeric literals and returned as results by arithmetic
  384. operators and arithmetic built-in functions. Numeric objects are immutable;
  385. once created their value never changes. Python numbers are of course strongly
  386. related to mathematical numbers, but subject to the limitations of numerical
  387. representation in computers.</p>
  388. <p>The string representations of the numeric classes, computed by
  389. <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
  390. properties:</p>
  391. <ul class="simple">
  392. <li><p>They are valid numeric literals which, when passed to their
  393. class constructor, produce an object having the value of the
  394. original numeric.</p></li>
  395. <li><p>The representation is in base 10, when possible.</p></li>
  396. <li><p>Leading zeros, possibly excepting a single zero before a
  397. decimal point, are not shown.</p></li>
  398. <li><p>Trailing zeros, possibly excepting a single zero after a
  399. decimal point, are not shown.</p></li>
  400. <li><p>A sign is shown only when the number is negative.</p></li>
  401. </ul>
  402. <p>Python distinguishes between integers, floating point numbers, and complex
  403. numbers:</p>
  404. <section id="numbers-integral">
  405. <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>
  406. <p id="index-10">These represent elements from the mathematical set of integers (positive and
  407. negative).</p>
  408. <div class="admonition note">
  409. <p class="admonition-title">Note</p>
  410. <p id="index-11">The rules for integer representation are intended to give the most meaningful
  411. interpretation of shift and mask operations involving negative integers.</p>
  412. </div>
  413. <p>There are two types of integers:</p>
  414. <dl>
  415. <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)
  416. memory only. For the purpose of shift and mask operations, a binary
  417. representation is assumed, and negative numbers are represented in a variant of
  418. 2’s complement which gives the illusion of an infinite string of sign bits
  419. extending to the left.</p>
  420. </dd>
  421. <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
  422. 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
  423. subtype of the integer type, and Boolean values behave like the values 0 and 1,
  424. respectively, in almost all contexts, the exception being that when converted to
  425. 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>
  426. </dd>
  427. </dl>
  428. </section>
  429. <section id="numbers-real-float">
  430. <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>
  431. <p id="index-13">These represent machine-level double precision floating point numbers. You are
  432. at the mercy of the underlying machine architecture (and C or Java
  433. implementation) for the accepted range and handling of overflow. Python does not
  434. support single-precision floating point numbers; the savings in processor and
  435. memory usage that are usually the reason for using these are dwarfed by the
  436. overhead of using objects in Python, so there is no reason to complicate the
  437. language with two kinds of floating point numbers.</p>
  438. </section>
  439. <section id="numbers-complex-complex">
  440. <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>
  441. <p id="index-14">These represent complex numbers as a pair of machine-level double precision
  442. floating point numbers. The same caveats apply as for floating point numbers.
  443. The real and imaginary parts of a complex number <code class="docutils literal notranslate"><span class="pre">z</span></code> can be retrieved through
  444. 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>
  445. </section>
  446. </section>
  447. <section id="sequences">
  448. <h3><span class="section-number">3.2.5. </span>Sequences<a class="headerlink" href="#sequences" title="Link to this heading">¶</a></h3>
  449. <p id="index-15">These represent finite ordered sets indexed by non-negative numbers. The
  450. 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
  451. the length of a sequence is <em>n</em>, the index set contains the numbers 0, 1,
  452. …, <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,
  453. including built-in sequences, interpret negative subscripts by adding the
  454. 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
  455. item of sequence a with length <code class="docutils literal notranslate"><span class="pre">n</span></code>.</p>
  456. <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
  457. 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
  458. sequence of the same type. The comment above about negative indexes also applies
  459. to negative slice positions.</p>
  460. <p>Some sequences also support “extended slicing” with a third “step” parameter:
  461. <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>
  462. <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>
  463. <p>Sequences are distinguished according to their mutability:</p>
  464. <section id="immutable-sequences">
  465. <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>
  466. <p id="index-17">An object of an immutable sequence type cannot change once it is created. (If
  467. the object contains references to other objects, these other objects may be
  468. mutable and may be changed; however, the collection of objects directly
  469. referenced by an immutable object cannot change.)</p>
  470. <p>The following types are immutable sequences:</p>
  471. <dl id="index-18">
  472. <dt>Strings</dt><dd><p id="index-19">A string is a sequence of values that represent Unicode code points.
  473. 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
  474. represented in a string. Python doesn’t have a <span class="c-expr sig sig-inline c"><span class="kt">char</span></span> type;
  475. instead, every code point in the string is represented as a string
  476. 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>
  477. converts a code point from its string form to an integer in the
  478. 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
  479. <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.
  480. <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
  481. <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
  482. <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>
  483. </dd>
  484. <dt>Tuples</dt><dd><p id="index-20">The items of a tuple are arbitrary Python objects. Tuples of two or
  485. more items are formed by comma-separated lists of expressions. A tuple
  486. of one item (a ‘singleton’) can be formed by affixing a comma to an
  487. expression (an expression by itself does not create a tuple, since
  488. parentheses must be usable for grouping of expressions). An empty
  489. tuple can be formed by an empty pair of parentheses.</p>
  490. </dd>
  491. <dt>Bytes</dt><dd><p id="index-21">A bytes object is an immutable array. The items are 8-bit bytes,
  492. represented by integers in the range 0 &lt;= x &lt; 256. Bytes literals
  493. (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
  494. can be used to create bytes objects. Also, bytes objects can be
  495. 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>
  496. </dd>
  497. </dl>
  498. </section>
  499. <section id="mutable-sequences">
  500. <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>
  501. <p id="index-22">Mutable sequences can be changed after they are created. The subscription and
  502. 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>
  503. (delete) statements.</p>
  504. <div class="admonition note">
  505. <p class="admonition-title">Note</p>
  506. <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
  507. additional examples of mutable sequence types.</p>
  508. </div>
  509. <p>There are currently two intrinsic mutable sequence types:</p>
  510. <dl>
  511. <dt>Lists</dt><dd><p id="index-25">The items of a list are arbitrary Python objects. Lists are formed by
  512. placing a comma-separated list of expressions in square brackets. (Note
  513. that there are no special cases needed to form lists of length 0 or 1.)</p>
  514. </dd>
  515. <dt>Byte Arrays</dt><dd><p id="index-26">A bytearray object is a mutable array. They are created by the built-in
  516. <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
  517. (and hence unhashable), byte arrays otherwise provide the same interface
  518. 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>
  519. </dd>
  520. </dl>
  521. </section>
  522. </section>
  523. <section id="set-types">
  524. <h3><span class="section-number">3.2.6. </span>Set types<a class="headerlink" href="#set-types" title="Link to this heading">¶</a></h3>
  525. <p id="index-27">These represent unordered, finite sets of unique, immutable objects. As such,
  526. they cannot be indexed by any subscript. However, they can be iterated over, and
  527. 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
  528. uses for sets are fast membership testing, removing duplicates from a sequence,
  529. and computing mathematical operations such as intersection, union, difference,
  530. and symmetric difference.</p>
  531. <p>For set elements, the same immutability rules apply as for dictionary keys. Note
  532. that numeric types obey the normal rules for numeric comparison: if two numbers
  533. 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
  534. set.</p>
  535. <p>There are currently two intrinsic set types:</p>
  536. <dl>
  537. <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>
  538. constructor and can be modified afterwards by several methods, such as
  539. <code class="xref py py-meth docutils literal notranslate"><span class="pre">add()</span></code>.</p>
  540. </dd>
  541. <dt>Frozen sets</dt><dd><p id="index-29">These represent an immutable set. They are created by the built-in
  542. <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
  543. <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
  544. a dictionary key.</p>
  545. </dd>
  546. </dl>
  547. </section>
  548. <section id="mappings">
  549. <h3><span class="section-number">3.2.7. </span>Mappings<a class="headerlink" href="#mappings" title="Link to this heading">¶</a></h3>
  550. <p id="index-30">These represent finite sets of objects indexed by arbitrary index sets. The
  551. 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
  552. <code class="docutils literal notranslate"><span class="pre">a</span></code>; this can be used in expressions and as the target of assignments or
  553. <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
  554. of items in a mapping.</p>
  555. <p>There is currently a single intrinsic mapping type:</p>
  556. <section id="dictionaries">
  557. <h4><span class="section-number">3.2.7.1. </span>Dictionaries<a class="headerlink" href="#dictionaries" title="Link to this heading">¶</a></h4>
  558. <p id="index-31">These represent finite sets of objects indexed by nearly arbitrary values. The
  559. only types of values not acceptable as keys are values containing lists or
  560. dictionaries or other mutable types that are compared by value rather than by
  561. object identity, the reason being that the efficient implementation of
  562. dictionaries requires a key’s hash value to remain constant. Numeric types used
  563. for keys obey the normal rules for numeric comparison: if two numbers compare
  564. 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
  565. the same dictionary entry.</p>
  566. <p>Dictionaries preserve insertion order, meaning that keys will be produced
  567. in the same order they were added sequentially over the dictionary.
  568. Replacing an existing key does not change the order, however removing a key
  569. and re-inserting it will add it to the end instead of keeping its old place.</p>
  570. <p>Dictionaries are mutable; they can be created by the <code class="docutils literal notranslate"><span class="pre">{...}</span></code> notation (see
  571. section <a class="reference internal" href="expressions.html#dict"><span class="std std-ref">Dictionary displays</span></a>).</p>
  572. <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
  573. 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>
  574. module.</p>
  575. <div class="versionchanged">
  576. <p><span class="versionmodified changed">Changed in version 3.7: </span>Dictionaries did not preserve insertion order in versions of Python before 3.6.
  577. In CPython 3.6, insertion order was preserved, but it was considered
  578. an implementation detail at that time rather than a language guarantee.</p>
  579. </div>
  580. </section>
  581. </section>
  582. <section id="callable-types">
  583. <h3><span class="section-number">3.2.8. </span>Callable types<a class="headerlink" href="#callable-types" title="Link to this heading">¶</a></h3>
  584. <p id="index-33">These are the types to which the function call operation (see section
  585. <a class="reference internal" href="expressions.html#calls"><span class="std std-ref">Calls</span></a>) can be applied:</p>
  586. <section id="user-defined-functions">
  587. <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>
  588. <p id="index-34">A user-defined function object is created by a function definition (see
  589. 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
  590. containing the same number of items as the function’s formal parameter
  591. list.</p>
  592. <section id="special-read-only-attributes">
  593. <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>
  594. <table class="docutils align-default" id="index-35">
  595. <thead>
  596. <tr class="row-odd"><th class="head"><p>Attribute</p></th>
  597. <th class="head"><p>Meaning</p></th>
  598. </tr>
  599. </thead>
  600. <tbody>
  601. <tr class="row-even"><td><dl class="py attribute">
  602. <dt class="sig sig-object py" id="function.__globals__">
  603. <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>
  604. <dd></dd></dl>
  605. </td>
  606. <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
  607. <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">global variables</span></a> – the global namespace of the module
  608. in which the function was defined.</p></td>
  609. </tr>
  610. <tr class="row-odd"><td><dl class="py attribute">
  611. <dt class="sig sig-object py" id="function.__closure__">
  612. <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>
  613. <dd></dd></dl>
  614. </td>
  615. <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
  616. function’s free variables.</p>
  617. <p>A cell object has the attribute <code class="docutils literal notranslate"><span class="pre">cell_contents</span></code>.
  618. This can be used to get the value of the cell, as well as set the value.</p>
  619. </td>
  620. </tr>
  621. </tbody>
  622. </table>
  623. </section>
  624. <section id="special-writable-attributes">
  625. <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>
  626. <p id="index-36">Most of these attributes check the type of the assigned value:</p>
  627. <table class="docutils align-default">
  628. <thead>
  629. <tr class="row-odd"><th class="head"><p>Attribute</p></th>
  630. <th class="head"><p>Meaning</p></th>
  631. </tr>
  632. </thead>
  633. <tbody>
  634. <tr class="row-even"><td><dl class="py attribute">
  635. <dt class="sig sig-object py" id="function.__doc__">
  636. <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>
  637. <dd></dd></dl>
  638. </td>
  639. <td><p>The function’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.
  640. Not inherited by subclasses.</p></td>
  641. </tr>
  642. <tr class="row-odd"><td><dl class="py attribute">
  643. <dt class="sig sig-object py" id="function.__name__">
  644. <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>
  645. <dd></dd></dl>
  646. </td>
  647. <td><p>The function’s name.
  648. 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>
  649. </tr>
  650. <tr class="row-even"><td><dl class="py attribute">
  651. <dt class="sig sig-object py" id="function.__qualname__">
  652. <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>
  653. <dd></dd></dl>
  654. </td>
  655. <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>.
  656. 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>
  657. <div class="versionadded">
  658. <p><span class="versionmodified added">New in version 3.3.</span></p>
  659. </div>
  660. </td>
  661. </tr>
  662. <tr class="row-odd"><td><dl class="py attribute">
  663. <dt class="sig sig-object py" id="function.__module__">
  664. <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>
  665. <dd></dd></dl>
  666. </td>
  667. <td><p>The name of the module the function was defined in,
  668. or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.</p></td>
  669. </tr>
  670. <tr class="row-even"><td><dl class="py attribute">
  671. <dt class="sig sig-object py" id="function.__defaults__">
  672. <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>
  673. <dd></dd></dl>
  674. </td>
  675. <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
  676. for those parameters that have defaults,
  677. or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no parameters have a default value.</p></td>
  678. </tr>
  679. <tr class="row-odd"><td><dl class="py attribute">
  680. <dt class="sig sig-object py" id="function.__code__">
  681. <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>
  682. <dd></dd></dl>
  683. </td>
  684. <td><p>The <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a> representing
  685. the compiled function body.</p></td>
  686. </tr>
  687. <tr class="row-even"><td><dl class="py attribute">
  688. <dt class="sig sig-object py" id="function.__dict__">
  689. <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>
  690. <dd></dd></dl>
  691. </td>
  692. <td><p>The namespace supporting arbitrary function attributes.
  693. See also: <a class="reference internal" href="../library/stdtypes.html#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>
  694. </tr>
  695. <tr class="row-odd"><td><dl class="py attribute">
  696. <dt class="sig sig-object py" id="function.__annotations__">
  697. <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>
  698. <dd></dd></dl>
  699. </td>
  700. <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
  701. <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a>.
  702. The keys of the dictionary are the parameter names,
  703. and <code class="docutils literal notranslate"><span class="pre">'return'</span></code> for the return annotation, if provided.
  704. See also: <a class="reference internal" href="../howto/annotations.html#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a>.</p></td>
  705. </tr>
  706. <tr class="row-even"><td><dl class="py attribute">
  707. <dt class="sig sig-object py" id="function.__kwdefaults__">
  708. <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>
  709. <dd></dd></dl>
  710. </td>
  711. <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
  712. <a class="reference internal" href="../glossary.html#term-parameter"><span class="xref std std-term">parameters</span></a>.</p></td>
  713. </tr>
  714. <tr class="row-odd"><td><dl class="py attribute">
  715. <dt class="sig sig-object py" id="function.__type_params__">
  716. <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>
  717. <dd></dd></dl>
  718. </td>
  719. <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
  720. a <a class="reference internal" href="compound_stmts.html#generic-functions"><span class="std std-ref">generic function</span></a>.</p>
  721. <div class="versionadded">
  722. <p><span class="versionmodified added">New in version 3.12.</span></p>
  723. </div>
  724. </td>
  725. </tr>
  726. </tbody>
  727. </table>
  728. <p>Function objects also support getting and setting arbitrary attributes, which
  729. can be used, for example, to attach metadata to functions. Regular attribute
  730. dot-notation is used to get and set such attributes.</p>
  731. <div class="impl-detail compound">
  732. <p><strong>CPython implementation detail:</strong> CPython’s current implementation only supports function attributes
  733. on user-defined functions. Function attributes on
  734. <a class="reference internal" href="#builtin-functions"><span class="std std-ref">built-in functions</span></a> may be supported in the
  735. future.</p>
  736. </div>
  737. <p>Additional information about a function’s definition can be retrieved from its
  738. <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a>
  739. (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>
  740. </section>
  741. </section>
  742. <section id="instance-methods">
  743. <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>
  744. <p id="index-37">An instance method object combines a class, a class instance and any
  745. callable object (normally a user-defined function).</p>
  746. <p id="index-38">Special read-only attributes:</p>
  747. <table class="docutils align-default">
  748. <tbody>
  749. <tr class="row-odd"><td><dl class="py attribute">
  750. <dt class="sig sig-object py" id="method.__self__">
  751. <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>
  752. <dd></dd></dl>
  753. </td>
  754. <td><p>Refers to the class instance object to which the method is
  755. <a class="reference internal" href="#method-binding"><span class="std std-ref">bound</span></a></p></td>
  756. </tr>
  757. <tr class="row-even"><td><dl class="py attribute">
  758. <dt class="sig sig-object py" id="method.__func__">
  759. <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>
  760. <dd></dd></dl>
  761. </td>
  762. <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>
  763. </tr>
  764. <tr class="row-odd"><td><dl class="py attribute">
  765. <dt class="sig sig-object py" id="method.__doc__">
  766. <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>
  767. <dd></dd></dl>
  768. </td>
  769. <td><p>The method’s documentation
  770. (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>).
  771. 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
  772. <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p></td>
  773. </tr>
  774. <tr class="row-even"><td><dl class="py attribute">
  775. <dt class="sig sig-object py" id="method.__name__">
  776. <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>
  777. <dd></dd></dl>
  778. </td>
  779. <td><p>The name of the method
  780. (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>
  781. </tr>
  782. <tr class="row-odd"><td><dl class="py attribute">
  783. <dt class="sig sig-object py" id="method.__module__">
  784. <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>
  785. <dd></dd></dl>
  786. </td>
  787. <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
  788. unavailable.</p></td>
  789. </tr>
  790. </tbody>
  791. </table>
  792. <p>Methods also support accessing (but not setting) the arbitrary function
  793. attributes on the underlying <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a>.</p>
  794. <p>User-defined method objects may be created when getting an attribute of a
  795. class (perhaps via an instance of that class), if that attribute is a
  796. user-defined <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a> or a
  797. <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>
  798. <p id="method-binding">When an instance method object is created by retrieving a user-defined
  799. <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a> from a class via one of its
  800. 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
  801. 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>
  802. attribute is the original function object.</p>
  803. <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>
  804. 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
  805. 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
  806. underlying the class method.</p>
  807. <p>When an instance method object is called, the underlying function
  808. (<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
  809. (<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
  810. <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
  811. <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
  812. equivalent to calling <code class="docutils literal notranslate"><span class="pre">C.f(x,</span> <span class="pre">1)</span></code>.</p>
  813. <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
  814. “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
  815. 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
  816. 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>
  817. <p>Note that the transformation from <a class="reference internal" href="#user-defined-funcs"><span class="std std-ref">function object</span></a>
  818. to instance method
  819. object happens each time the attribute is retrieved from the instance. In
  820. some cases, a fruitful optimization is to assign the attribute to a local
  821. variable and call that local variable. Also notice that this
  822. transformation only happens for user-defined functions; other callable
  823. objects (and all non-callable objects) are retrieved without
  824. transformation. It is also important to note that user-defined functions
  825. which are attributes of a class instance are not converted to bound
  826. methods; this <em>only</em> happens when the function is an attribute of the
  827. class.</p>
  828. </section>
  829. <section id="generator-functions">
  830. <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>
  831. <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
  832. <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
  833. 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
  834. execute the body of the function: calling the iterator’s
  835. <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
  836. it provides a value using the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span></code> statement. When the
  837. 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
  838. <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
  839. reached the end of the set of values to be returned.</p>
  840. </section>
  841. <section id="coroutine-functions">
  842. <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>
  843. <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
  844. a <em class="dfn">coroutine function</em>. Such a function, when called, returns a
  845. <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,
  846. 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
  847. also the <a class="reference internal" href="#coroutine-objects"><span class="std std-ref">Coroutine Objects</span></a> section.</p>
  848. </section>
  849. <section id="asynchronous-generator-functions">
  850. <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>
  851. <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
  852. 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
  853. <em class="dfn">asynchronous generator function</em>. Such a function, when called,
  854. 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
  855. <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>
  856. <p>Calling the asynchronous iterator’s
  857. <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
  858. will return an <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> which when awaited
  859. 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>
  860. 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>
  861. 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
  862. is raised and the asynchronous iterator will have reached the end of
  863. the set of values to be yielded.</p>
  864. </section>
  865. <section id="built-in-functions">
  866. <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>
  867. <p id="index-42">A built-in function object is a wrapper around a C function. Examples of
  868. 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
  869. standard built-in module). The number and type of the arguments are
  870. determined by the C function. Special read-only attributes:</p>
  871. <ul class="simple">
  872. <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
  873. 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>
  874. <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>
  875. <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>
  876. <li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code> is the name of
  877. the module the function was defined in or <code class="docutils literal notranslate"><span class="pre">None</span></code> if unavailable.
  878. 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>
  879. </ul>
  880. </section>
  881. <section id="built-in-methods">
  882. <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>
  883. <p id="index-43">This is really a different disguise of a built-in function, this time containing
  884. an object passed to the C function as an implicit extra argument. An example of
  885. 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
  886. 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
  887. denoted by <em>alist</em>. (The attribute has the same semantics as it does with
  888. <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>
  889. </section>
  890. <section id="classes">
  891. <h4><span class="section-number">3.2.8.8. </span>Classes<a class="headerlink" href="#classes" title="Link to this heading">¶</a></h4>
  892. <p>Classes are callable. These objects normally act as factories for new
  893. instances of themselves, but variations are possible for class types that
  894. 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
  895. <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
  896. initialize the new instance.</p>
  897. </section>
  898. <section id="class-instances">
  899. <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>
  900. <p>Instances of arbitrary classes can be made callable by defining a
  901. <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>
  902. </section>
  903. </section>
  904. <section id="modules">
  905. <h3><span class="section-number">3.2.9. </span>Modules<a class="headerlink" href="#modules" title="Link to this heading">¶</a></h3>
  906. <p id="index-44">Modules are a basic organizational unit of Python code, and are created by
  907. the <a class="reference internal" href="import.html#importsystem"><span class="std std-ref">import system</span></a> as invoked either by the
  908. <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
  909. 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
  910. <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
  911. <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
  912. <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>
  913. attribute of functions defined in the module). Attribute references are
  914. translated to lookups in this dictionary, e.g., <code class="docutils literal notranslate"><span class="pre">m.x</span></code> is equivalent to
  915. <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
  916. to initialize the module (since it isn’t needed once the initialization is
  917. done).</p>
  918. <p>Attribute assignment updates the module’s namespace dictionary, e.g.,
  919. <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>
  920. <p id="index-45">Predefined (writable) attributes:</p>
  921. <blockquote>
  922. <div><dl class="simple">
  923. <dt><a class="reference internal" href="import.html#name__" title="__name__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__name__</span></code></a></dt><dd><p>The module’s name.</p>
  924. </dd>
  925. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></dt><dd><p>The module’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
  926. unavailable.</p>
  927. </dd>
  928. <dt><a class="reference internal" href="import.html#file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a></dt><dd><p>The pathname of the file from which the
  929. module was loaded, if it was loaded from a file.
  930. The <a class="reference internal" href="import.html#file__" title="__file__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__file__</span></code></a>
  931. attribute may be missing for certain types of modules, such as C modules
  932. that are statically linked into the interpreter. For extension modules
  933. loaded dynamically from a shared library, it’s the pathname of the shared
  934. library file.</p>
  935. </dd>
  936. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code></dt><dd><p>A dictionary containing
  937. <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a> collected during
  938. module body execution. For best practices on working
  939. 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>
  940. </dd>
  941. </dl>
  942. </div></blockquote>
  943. <p id="index-46">Special read-only attribute: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the module’s
  944. namespace as a dictionary object.</p>
  945. <div class="impl-detail compound">
  946. <p><strong>CPython implementation detail:</strong> Because of the way CPython clears module dictionaries, the module
  947. dictionary will be cleared when the module falls out of scope even if the
  948. dictionary still has live references. To avoid this, copy the dictionary
  949. or keep the module around while using its dictionary directly.</p>
  950. </div>
  951. </section>
  952. <section id="custom-classes">
  953. <h3><span class="section-number">3.2.10. </span>Custom classes<a class="headerlink" href="#custom-classes" title="Link to this heading">¶</a></h3>
  954. <p>Custom class types are typically created by class definitions (see section
  955. <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.
  956. Class attribute references are translated to lookups in this dictionary, e.g.,
  957. <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
  958. hooks which allow for other means of locating attributes). When the attribute
  959. name is not found there, the attribute search continues in the base classes.
  960. This search of the base classes uses the C3 method resolution order which
  961. behaves correctly even in the presence of ‘diamond’ inheritance structures
  962. where there are multiple inheritance paths leading back to a common ancestor.
  963. Additional details on the C3 MRO used by Python can be found in the
  964. documentation accompanying the 2.3 release at
  965. <a class="reference external" href="https://www.python.org/download/releases/2.3/mro/">https://www.python.org/download/releases/2.3/mro/</a>.</p>
  966. <p id="index-47">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
  967. class method object, it is transformed into an instance method object whose
  968. <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>.
  969. 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,
  970. it is transformed into the object wrapped by the static method
  971. object. See section <a class="reference internal" href="#descriptors"><span class="std std-ref">Implementing Descriptors</span></a> for another way in which attributes
  972. retrieved from a class may differ from those actually contained in its
  973. <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
  974. <p id="index-48">Class attribute assignments update the class’s dictionary, never the dictionary
  975. of a base class.</p>
  976. <p id="index-49">A class object can be called (see above) to yield a class instance (see below).</p>
  977. <p id="index-50">Special attributes:</p>
  978. <blockquote>
  979. <div><dl class="simple">
  980. <dt><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></code></a></dt><dd><p>The class name.</p>
  981. </dd>
  982. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__module__</span></code></dt><dd><p>The name of the module in which the class was defined.</p>
  983. </dd>
  984. <dt><a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a></dt><dd><p>The dictionary containing the class’s namespace.</p>
  985. </dd>
  986. <dt><a class="reference internal" href="../library/stdtypes.html#class.__bases__" title="class.__bases__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__bases__</span></code></a></dt><dd><p>A tuple containing the base classes, in the order of
  987. their occurrence in the base class list.</p>
  988. </dd>
  989. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__doc__</span></code></dt><dd><p>The class’s documentation string, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p>
  990. </dd>
  991. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code></dt><dd><p>A dictionary containing
  992. <a class="reference internal" href="../glossary.html#term-variable-annotation"><span class="xref std std-term">variable annotations</span></a>
  993. collected during class body execution. For best practices on
  994. working with <code class="xref py py-attr docutils literal notranslate"><span class="pre">__annotations__</span></code>, please see
  995. <a class="reference internal" href="../howto/annotations.html#annotations-howto"><span class="std std-ref">Annotations Best Practices</span></a>.</p>
  996. </dd>
  997. <dt><code class="xref py py-attr docutils literal notranslate"><span class="pre">__type_params__</span></code></dt><dd><p>A tuple containing the <a class="reference internal" href="compound_stmts.html#type-params"><span class="std std-ref">type parameters</span></a> of
  998. a <a class="reference internal" href="compound_stmts.html#generic-classes"><span class="std std-ref">generic class</span></a>.</p>
  999. </dd>
  1000. </dl>
  1001. </div></blockquote>
  1002. </section>
  1003. <section id="id3">
  1004. <h3><span class="section-number">3.2.11. </span>Class instances<a class="headerlink" href="#id3" title="Link to this heading">¶</a></h3>
  1005. <p id="index-51">A class instance is created by calling a class object (see above). A class
  1006. instance has a namespace implemented as a dictionary which is the first place
  1007. in which attribute references are searched. When an attribute is not found
  1008. there, and the instance’s class has an attribute by that name, the search
  1009. continues with the class attributes. If a class attribute is found that is a
  1010. user-defined function object, it is transformed into an instance method
  1011. 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
  1012. class method objects are also transformed; see above under “Classes”. See
  1013. 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
  1014. retrieved via its instances may differ from the objects actually stored in
  1015. the class’s <a class="reference internal" href="../library/stdtypes.html#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
  1016. 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
  1017. the lookup.</p>
  1018. <p id="index-52">Attribute assignments and deletions update the instance’s dictionary, never a
  1019. 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
  1020. <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
  1021. dictionary directly.</p>
  1022. <p id="index-53">Class instances can pretend to be numbers, sequences, or mappings if they have
  1023. methods with certain special names. See section <a class="reference internal" href="#specialnames"><span class="std std-ref">Special method names</span></a>.</p>
  1024. <p id="index-54">Special attributes: <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> is the attribute dictionary;
  1025. <a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__class__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__class__</span></code></a> is the instance’s class.</p>
  1026. </section>
  1027. <section id="i-o-objects-also-known-as-file-objects">
  1028. <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>
  1029. <p id="index-55">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
  1030. 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
  1031. 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
  1032. <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
  1033. other functions or methods provided by extension modules).</p>
  1034. <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
  1035. initialized to file objects corresponding to the interpreter’s standard
  1036. input, output and error streams; they are all open in text mode and
  1037. 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>
  1038. abstract class.</p>
  1039. </section>
  1040. <section id="internal-types">
  1041. <h3><span class="section-number">3.2.13. </span>Internal types<a class="headerlink" href="#internal-types" title="Link to this heading">¶</a></h3>
  1042. <p id="index-56">A few types used internally by the interpreter are exposed to the user. Their
  1043. definitions may change with future versions of the interpreter, but they are
  1044. mentioned here for completeness.</p>
  1045. <section id="code-objects">
  1046. <span id="id4"></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>
  1047. <p id="index-57">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>.
  1048. The difference between a code object and a function object is that the function
  1049. object contains an explicit reference to the function’s globals (the module in
  1050. which it was defined), while a code object contains no context; also the default
  1051. argument values are stored in the function object, not in the code object
  1052. (because they represent values calculated at run-time). Unlike function
  1053. objects, code objects are immutable and contain no references (directly or
  1054. indirectly) to mutable objects.</p>
  1055. <section id="index-58">
  1056. <span id="id5"></span><h5><span class="section-number">3.2.13.1.1. </span>Special read-only attributes<a class="headerlink" href="#index-58" title="Link to this heading">¶</a></h5>
  1057. <table class="docutils align-default">
  1058. <tbody>
  1059. <tr class="row-odd"><td><dl class="py attribute">
  1060. <dt class="sig sig-object py" id="codeobject.co_name">
  1061. <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>
  1062. <dd></dd></dl>
  1063. </td>
  1064. <td><p>The function name</p></td>
  1065. </tr>
  1066. <tr class="row-even"><td><dl class="py attribute">
  1067. <dt class="sig sig-object py" id="codeobject.co_qualname">
  1068. <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>
  1069. <dd></dd></dl>
  1070. </td>
  1071. <td><p>The fully qualified function name</p>
  1072. <div class="versionadded">
  1073. <p><span class="versionmodified added">New in version 3.11.</span></p>
  1074. </div>
  1075. </td>
  1076. </tr>
  1077. <tr class="row-odd"><td><dl class="py attribute">
  1078. <dt class="sig sig-object py" id="codeobject.co_argcount">
  1079. <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>
  1080. <dd></dd></dl>
  1081. </td>
  1082. <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>
  1083. (including positional-only parameters and parameters with default values)
  1084. that the function has</p></td>
  1085. </tr>
  1086. <tr class="row-even"><td><dl class="py attribute">
  1087. <dt class="sig sig-object py" id="codeobject.co_posonlyargcount">
  1088. <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>
  1089. <dd></dd></dl>
  1090. </td>
  1091. <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>
  1092. (including arguments with default values) that the function has</p></td>
  1093. </tr>
  1094. <tr class="row-odd"><td><dl class="py attribute">
  1095. <dt class="sig sig-object py" id="codeobject.co_kwonlyargcount">
  1096. <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>
  1097. <dd></dd></dl>
  1098. </td>
  1099. <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>
  1100. (including arguments with default values) that the function has</p></td>
  1101. </tr>
  1102. <tr class="row-even"><td><dl class="py attribute">
  1103. <dt class="sig sig-object py" id="codeobject.co_nlocals">
  1104. <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>
  1105. <dd></dd></dl>
  1106. </td>
  1107. <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
  1108. (including parameters)</p></td>
  1109. </tr>
  1110. <tr class="row-odd"><td><dl class="py attribute">
  1111. <dt class="sig sig-object py" id="codeobject.co_varnames">
  1112. <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>
  1113. <dd></dd></dl>
  1114. </td>
  1115. <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
  1116. function (starting with the parameter names)</p></td>
  1117. </tr>
  1118. <tr class="row-even"><td><dl class="py attribute">
  1119. <dt class="sig sig-object py" id="codeobject.co_cellvars">
  1120. <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>
  1121. <dd></dd></dl>
  1122. </td>
  1123. <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>
  1124. that are referenced by nested functions inside the function</p></td>
  1125. </tr>
  1126. <tr class="row-odd"><td><dl class="py attribute">
  1127. <dt class="sig sig-object py" id="codeobject.co_freevars">
  1128. <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>
  1129. <dd></dd></dl>
  1130. </td>
  1131. <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 free variables in the function</p></td>
  1132. </tr>
  1133. <tr class="row-even"><td><dl class="py attribute">
  1134. <dt class="sig sig-object py" id="codeobject.co_code">
  1135. <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>
  1136. <dd></dd></dl>
  1137. </td>
  1138. <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
  1139. the function</p></td>
  1140. </tr>
  1141. <tr class="row-odd"><td><dl class="py attribute">
  1142. <dt class="sig sig-object py" id="codeobject.co_consts">
  1143. <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>
  1144. <dd></dd></dl>
  1145. </td>
  1146. <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
  1147. the function</p></td>
  1148. </tr>
  1149. <tr class="row-even"><td><dl class="py attribute">
  1150. <dt class="sig sig-object py" id="codeobject.co_names">
  1151. <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>
  1152. <dd></dd></dl>
  1153. </td>
  1154. <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
  1155. the function</p></td>
  1156. </tr>
  1157. <tr class="row-odd"><td><dl class="py attribute">
  1158. <dt class="sig sig-object py" id="codeobject.co_filename">
  1159. <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>
  1160. <dd></dd></dl>
  1161. </td>
  1162. <td><p>The name of the file from which the code was compiled</p></td>
  1163. </tr>
  1164. <tr class="row-even"><td><dl class="py attribute">
  1165. <dt class="sig sig-object py" id="codeobject.co_firstlineno">
  1166. <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>
  1167. <dd></dd></dl>
  1168. </td>
  1169. <td><p>The line number of the first line of the function</p></td>
  1170. </tr>
  1171. <tr class="row-odd"><td><dl class="py attribute">
  1172. <dt class="sig sig-object py" id="codeobject.co_lnotab">
  1173. <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>
  1174. <dd></dd></dl>
  1175. </td>
  1176. <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
  1177. numbers. For details, see the source code of the interpreter.</p>
  1178. <div class="deprecated">
  1179. <p><span class="versionmodified deprecated">Deprecated since version 3.12: </span>This attribute of code objects is deprecated, and may be removed in
  1180. Python 3.14.</p>
  1181. </div>
  1182. </td>
  1183. </tr>
  1184. <tr class="row-even"><td><dl class="py attribute">
  1185. <dt class="sig sig-object py" id="codeobject.co_stacksize">
  1186. <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>
  1187. <dd></dd></dl>
  1188. </td>
  1189. <td><p>The required stack size of the code object</p></td>
  1190. </tr>
  1191. <tr class="row-odd"><td><dl class="py attribute">
  1192. <dt class="sig sig-object py" id="codeobject.co_flags">
  1193. <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>
  1194. <dd></dd></dl>
  1195. </td>
  1196. <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
  1197. interpreter.</p></td>
  1198. </tr>
  1199. </tbody>
  1200. </table>
  1201. <p id="index-59">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>:
  1202. bit <code class="docutils literal notranslate"><span class="pre">0x04</span></code> is set if
  1203. the function uses the <code class="docutils literal notranslate"><span class="pre">*arguments</span></code> syntax to accept an arbitrary number of
  1204. positional arguments; bit <code class="docutils literal notranslate"><span class="pre">0x08</span></code> is set if the function uses the
  1205. <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
  1206. 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
  1207. on the semantics of each flags that might be present.</p>
  1208. <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
  1209. 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
  1210. particular feature enabled: bit <code class="docutils literal notranslate"><span class="pre">0x2000</span></code> is set if the function was compiled
  1211. 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
  1212. versions of Python.</p>
  1213. <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>
  1214. <p id="index-60">If a code object represents a function, the first item in
  1215. <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
  1216. the documentation string of the function, or <code class="docutils literal notranslate"><span class="pre">None</span></code> if undefined.</p>
  1217. </section>
  1218. <section id="methods-on-code-objects">
  1219. <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>
  1220. <dl class="py method">
  1221. <dt class="sig sig-object py" id="codeobject.co_positions">
  1222. <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>
  1223. <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>
  1224. instruction in the code object.</p>
  1225. <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>
  1226. <span class="pre">start_column,</span> <span class="pre">end_column)</span></code>. The <em>i-th</em> tuple corresponds to the
  1227. position of the source code that compiled to the <em>i-th</em> instruction.
  1228. Column information is 0-indexed utf-8 byte offsets on the given source
  1229. line.</p>
  1230. <p>This positional information can be missing. A non-exhaustive lists of
  1231. cases where this may happen:</p>
  1232. <ul class="simple">
  1233. <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>
  1234. <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>
  1235. <li><p>Position tuples corresponding to artificial instructions.</p></li>
  1236. <li><p>Line and column numbers that can’t be represented due to
  1237. implementation specific limitations.</p></li>
  1238. </ul>
  1239. <p>When this occurs, some or all of the tuple elements can be
  1240. <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>
  1241. <div class="versionadded">
  1242. <p><span class="versionmodified added">New in version 3.11.</span></p>
  1243. </div>
  1244. <div class="admonition note">
  1245. <p class="admonition-title">Note</p>
  1246. <p>This feature requires storing column positions in code objects which may
  1247. result in a small increase of disk usage of compiled Python files or
  1248. interpreter memory usage. To avoid storing the extra information and/or
  1249. deactivate printing the extra traceback information, the
  1250. <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-61"></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>
  1251. environment variable can be used.</p>
  1252. </div>
  1253. </dd></dl>
  1254. <dl class="py method">
  1255. <dt class="sig sig-object py" id="codeobject.co_lines">
  1256. <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>
  1257. <dd><p>Returns an iterator that yields information about successive ranges of
  1258. <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>
  1259. <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>
  1260. <ul class="simple">
  1261. <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
  1262. of the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> range</p></li>
  1263. <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
  1264. the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> range</p></li>
  1265. <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
  1266. <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
  1267. have no line number</p></li>
  1268. </ul>
  1269. <p>The items yielded will have the following properties:</p>
  1270. <ul class="simple">
  1271. <li><p>The first range yielded will have a <code class="docutils literal notranslate"><span class="pre">start</span></code> of 0.</p></li>
  1272. <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
  1273. 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
  1274. equal to the <code class="docutils literal notranslate"><span class="pre">end</span></code> of the first.</p></li>
  1275. <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>
  1276. <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
  1277. <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a>.</p></li>
  1278. </ul>
  1279. <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
  1280. are used for lines that are present in the source code, but have been
  1281. eliminated by the <a class="reference internal" href="../glossary.html#term-bytecode"><span class="xref std std-term">bytecode</span></a> compiler.</p>
  1282. <div class="versionadded">
  1283. <p><span class="versionmodified added">New in version 3.10.</span></p>
  1284. </div>
  1285. <div class="admonition seealso">
  1286. <p class="admonition-title">See also</p>
  1287. <dl class="simple">
  1288. <dt><span class="target" id="index-62"></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>
  1289. </dd>
  1290. </dl>
  1291. </div>
  1292. </dd></dl>
  1293. <dl class="py method">
  1294. <dt class="sig sig-object py" id="codeobject.replace">
  1295. <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>
  1296. <dd><p>Return a copy of the code object with new values for the specified fields.</p>
  1297. <div class="versionadded">
  1298. <p><span class="versionmodified added">New in version 3.8.</span></p>
  1299. </div>
  1300. </dd></dl>
  1301. </section>
  1302. </section>
  1303. <section id="frame-objects">
  1304. <span id="id6"></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>
  1305. <p id="index-63">Frame objects represent execution frames. They may occur in
  1306. <a class="reference internal" href="#traceback-objects"><span class="std std-ref">traceback objects</span></a>,
  1307. and are also passed to registered trace functions.</p>
  1308. <section id="index-64">
  1309. <span id="id7"></span><h5><span class="section-number">3.2.13.2.1. </span>Special read-only attributes<a class="headerlink" href="#index-64" title="Link to this heading">¶</a></h5>
  1310. <table class="docutils align-default">
  1311. <tbody>
  1312. <tr class="row-odd"><td><dl class="py attribute">
  1313. <dt class="sig sig-object py" id="frame.f_back">
  1314. <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>
  1315. <dd></dd></dl>
  1316. </td>
  1317. <td><p>Points to the previous stack frame (towards the caller),
  1318. or <code class="docutils literal notranslate"><span class="pre">None</span></code> if this is the bottom stack frame</p></td>
  1319. </tr>
  1320. <tr class="row-even"><td><dl class="py attribute">
  1321. <dt class="sig sig-object py" id="frame.f_code">
  1322. <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>
  1323. <dd></dd></dl>
  1324. </td>
  1325. <td><p>The <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a> being executed in this frame.
  1326. Accessing this attribute raises an <a class="reference internal" href="../library/sys.html#auditing"><span class="std std-ref">auditing event</span></a>
  1327. <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>
  1328. </tr>
  1329. <tr class="row-odd"><td><dl class="py attribute">
  1330. <dt class="sig sig-object py" id="frame.f_locals">
  1331. <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>
  1332. <dd></dd></dl>
  1333. </td>
  1334. <td><p>The dictionary used by the frame to look up
  1335. <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">local variables</span></a></p></td>
  1336. </tr>
  1337. <tr class="row-even"><td><dl class="py attribute">
  1338. <dt class="sig sig-object py" id="frame.f_globals">
  1339. <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>
  1340. <dd></dd></dl>
  1341. </td>
  1342. <td><p>The dictionary used by the frame to look up
  1343. <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">global variables</span></a></p></td>
  1344. </tr>
  1345. <tr class="row-odd"><td><dl class="py attribute">
  1346. <dt class="sig sig-object py" id="frame.f_builtins">
  1347. <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>
  1348. <dd></dd></dl>
  1349. </td>
  1350. <td><p>The dictionary used by the frame to look up
  1351. <a class="reference internal" href="executionmodel.html#naming"><span class="std std-ref">built-in (intrinsic) names</span></a></p></td>
  1352. </tr>
  1353. <tr class="row-even"><td><dl class="py attribute">
  1354. <dt class="sig sig-object py" id="frame.f_lasti">
  1355. <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>
  1356. <dd></dd></dl>
  1357. </td>
  1358. <td><p>The “precise instruction” of the frame object
  1359. (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
  1360. <a class="reference internal" href="#code-objects"><span class="std std-ref">code object</span></a>)</p></td>
  1361. </tr>
  1362. </tbody>
  1363. </table>
  1364. </section>
  1365. <section id="index-65">
  1366. <span id="id8"></span><h5><span class="section-number">3.2.13.2.2. </span>Special writable attributes<a class="headerlink" href="#index-65" title="Link to this heading">¶</a></h5>
  1367. <table class="docutils align-default">
  1368. <tbody>
  1369. <tr class="row-odd"><td><dl class="py attribute">
  1370. <dt class="sig sig-object py" id="frame.f_trace">
  1371. <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>
  1372. <dd></dd></dl>
  1373. </td>
  1374. <td><p>If not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this is a function called for various events during
  1375. code execution (this is used by debuggers). Normally an event is
  1376. 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>
  1377. </tr>
  1378. <tr class="row-even"><td><dl class="py attribute">
  1379. <dt class="sig sig-object py" id="frame.f_trace_lines">
  1380. <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>
  1381. <dd></dd></dl>
  1382. </td>
  1383. <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
  1384. event for each source line.</p></td>
  1385. </tr>
  1386. <tr class="row-odd"><td><dl class="py attribute">
  1387. <dt class="sig sig-object py" id="frame.f_trace_opcodes">
  1388. <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>
  1389. <dd></dd></dl>
  1390. </td>
  1391. <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
  1392. requested. Note that this may lead to
  1393. undefined interpreter behaviour if exceptions raised by the trace
  1394. function escape to the function being traced.</p></td>
  1395. </tr>
  1396. <tr class="row-even"><td><dl class="py attribute">
  1397. <dt class="sig sig-object py" id="frame.f_lineno">
  1398. <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>
  1399. <dd></dd></dl>
  1400. </td>
  1401. <td><p>The current line number of the frame – writing to this
  1402. from within a trace function jumps to the given line (only for the bottom-most
  1403. frame). A debugger can implement a Jump command (aka Set Next Statement)
  1404. by writing to this attribute.</p></td>
  1405. </tr>
  1406. </tbody>
  1407. </table>
  1408. </section>
  1409. <section id="frame-object-methods">
  1410. <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>
  1411. <p>Frame objects support one method:</p>
  1412. <dl class="py method">
  1413. <dt class="sig sig-object py" id="frame.clear">
  1414. <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>
  1415. <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
  1416. 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
  1417. is finalized. This helps break reference cycles involving frame
  1418. objects (for example when catching an <a class="reference internal" href="../library/exceptions.html#bltin-exceptions"><span class="std std-ref">exception</span></a>
  1419. and storing its <a class="reference internal" href="#traceback-objects"><span class="std std-ref">traceback</span></a> for later use).</p>
  1420. <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.</p>
  1421. <div class="versionadded">
  1422. <p><span class="versionmodified added">New in version 3.4.</span></p>
  1423. </div>
  1424. </dd></dl>
  1425. </section>
  1426. </section>
  1427. <section id="traceback-objects">
  1428. <span id="id9"></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>
  1429. <p id="index-66">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>.
  1430. A traceback object
  1431. is implicitly created when an exception occurs, and may also be explicitly
  1432. 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>
  1433. <div class="versionchanged">
  1434. <p><span class="versionmodified changed">Changed in version 3.7: </span>Traceback objects can now be explicitly instantiated from Python code.</p>
  1435. </div>
  1436. <p>For implicitly created tracebacks, when the search for an exception handler
  1437. unwinds the execution stack, at each unwound level a traceback object is
  1438. inserted in front of the current traceback. When an exception handler is
  1439. entered, the stack trace is made available to the program. (See section
  1440. <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
  1441. 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
  1442. <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
  1443. of the caught exception.</p>
  1444. <p>When the program contains no suitable
  1445. handler, the stack trace is written (nicely formatted) to the standard error
  1446. stream; if the interpreter is interactive, it is also made available to the user
  1447. 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>
  1448. <p>For explicitly created tracebacks, it is up to the creator of the traceback
  1449. 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
  1450. form a full stack trace.</p>
  1451. <p id="index-67">Special read-only attributes:</p>
  1452. <table class="docutils align-default">
  1453. <tbody>
  1454. <tr class="row-odd"><td><dl class="py attribute">
  1455. <dt class="sig sig-object py" id="traceback.tb_frame">
  1456. <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>
  1457. <dd></dd></dl>
  1458. </td>
  1459. <td><p>Points to the execution <a class="reference internal" href="#frame-objects"><span class="std std-ref">frame</span></a> of the current
  1460. level.</p>
  1461. <p>Accessing this attribute raises an
  1462. <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
  1463. <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>
  1464. </td>
  1465. </tr>
  1466. <tr class="row-even"><td><dl class="py attribute">
  1467. <dt class="sig sig-object py" id="traceback.tb_lineno">
  1468. <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>
  1469. <dd></dd></dl>
  1470. </td>
  1471. <td><p>Gives the line number where the exception occurred</p></td>
  1472. </tr>
  1473. <tr class="row-odd"><td><dl class="py attribute">
  1474. <dt class="sig sig-object py" id="traceback.tb_lasti">
  1475. <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>
  1476. <dd></dd></dl>
  1477. </td>
  1478. <td><p>Indicates the “precise instruction”.</p></td>
  1479. </tr>
  1480. </tbody>
  1481. </table>
  1482. <p>The line number and last instruction in the traceback may differ from the
  1483. line number of its <a class="reference internal" href="#frame-objects"><span class="std std-ref">frame object</span></a> if the exception
  1484. occurred in a
  1485. <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
  1486. <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>
  1487. <dl class="py attribute" id="index-68">
  1488. <dt class="sig sig-object py" id="traceback.tb_next">
  1489. <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>
  1490. <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
  1491. stack trace (towards the frame where the exception occurred), or <code class="docutils literal notranslate"><span class="pre">None</span></code> if
  1492. there is no next level.</p>
  1493. <div class="versionchanged">
  1494. <p><span class="versionmodified changed">Changed in version 3.7: </span>This attribute is now writable</p>
  1495. </div>
  1496. </dd></dl>
  1497. </section>
  1498. <section id="slice-objects">
  1499. <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>
  1500. <p id="index-69">Slice objects are used to represent slices for
  1501. <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>
  1502. 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>
  1503. <p id="index-70">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;
  1504. <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
  1505. value; each is <code class="docutils literal notranslate"><span class="pre">None</span></code> if omitted. These attributes can have any type.</p>
  1506. <p>Slice objects support one method:</p>
  1507. <dl class="py method">
  1508. <dt class="sig sig-object py" id="slice.indices">
  1509. <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>
  1510. <dd><p>This method takes a single integer argument <em>length</em> and computes
  1511. information about the slice that the slice object would describe if
  1512. applied to a sequence of <em>length</em> items. It returns a tuple of three
  1513. integers; respectively these are the <em>start</em> and <em>stop</em> indices and the
  1514. <em>step</em> or stride length of the slice. Missing or out-of-bounds indices
  1515. are handled in a manner consistent with regular slices.</p>
  1516. </dd></dl>
  1517. </section>
  1518. <section id="static-method-objects">
  1519. <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>
  1520. <p>Static method objects provide a way of defeating the transformation of function
  1521. objects to method objects described above. A static method object is a wrapper
  1522. around any other object, usually a user-defined method object. When a static
  1523. method object is retrieved from a class or a class instance, the object actually
  1524. returned is the wrapped object, which is not subject to any further
  1525. transformation. Static method objects are also callable. Static method
  1526. 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>
  1527. </section>
  1528. <section id="class-method-objects">
  1529. <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>
  1530. <p>A class method object, like a static method object, is a wrapper around another
  1531. object that alters the way in which that object is retrieved from classes and
  1532. class instances. The behaviour of class method objects upon such retrieval is
  1533. described above, under <a class="reference internal" href="#instance-methods"><span class="std std-ref">“instance methods”</span></a>. Class method objects are created
  1534. 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>
  1535. </section>
  1536. </section>
  1537. </section>
  1538. <section id="special-method-names">
  1539. <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>
  1540. <p id="index-71">A class can implement certain operations that are invoked by special syntax
  1541. (such as arithmetic operations or subscripting and slicing) by defining methods
  1542. with special names. This is Python’s approach to <em class="dfn">operator overloading</em>,
  1543. allowing classes to define their own behavior with respect to language
  1544. operators. For instance, if a class defines a method named
  1545. <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>,
  1546. 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
  1547. 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
  1548. operation raise an exception when no appropriate method is defined (typically
  1549. <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>
  1550. <p>Setting a special method to <code class="docutils literal notranslate"><span class="pre">None</span></code> indicates that the corresponding
  1551. operation is not available. For example, if a class sets
  1552. <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
  1553. <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
  1554. 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="#id18" id="id10" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a></p>
  1555. <p>When implementing a class that emulates any built-in type, it is important that
  1556. the emulation only be implemented to the degree that it makes sense for the
  1557. object being modelled. For example, some sequences may work well with retrieval
  1558. of individual elements, but extracting a slice may not make sense. (One example
  1559. 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
  1560. Object Model.)</p>
  1561. <section id="basic-customization">
  1562. <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>
  1563. <dl class="py method">
  1564. <dt class="sig sig-object py" id="object.__new__">
  1565. <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>
  1566. <dd><p id="index-72">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
  1567. method (special-cased so you need not declare it as such) that takes the class
  1568. of which an instance was requested as its first argument. The remaining
  1569. arguments are those passed to the object constructor expression (the call to the
  1570. 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
  1571. (usually an instance of <em>cls</em>).</p>
  1572. <p>Typical implementations create a new instance of the class by invoking the
  1573. 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>
  1574. with appropriate arguments and then modifying the newly created instance
  1575. as necessary before returning it.</p>
  1576. <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
  1577. 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
  1578. 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
  1579. and the remaining arguments are the same as were passed to the object constructor.</p>
  1580. <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
  1581. <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>
  1582. <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
  1583. int, str, or tuple) to customize instance creation. It is also commonly
  1584. overridden in custom metaclasses in order to customize class creation.</p>
  1585. </dd></dl>
  1586. <dl class="py method">
  1587. <dt class="sig sig-object py" id="object.__init__">
  1588. <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>
  1589. <dd><p id="index-73">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
  1590. it is returned to the caller. The arguments are those passed to the
  1591. 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>
  1592. 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
  1593. call it to ensure proper initialization of the base class part of the
  1594. instance; for example: <code class="docutils literal notranslate"><span class="pre">super().__init__([args...])</span></code>.</p>
  1595. <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
  1596. 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),
  1597. 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
  1598. 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>
  1599. </dd></dl>
  1600. <dl class="py method">
  1601. <dt class="sig sig-object py" id="object.__del__">
  1602. <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>
  1603. <dd><p id="index-74">Called when the instance is about to be destroyed. This is also called a
  1604. finalizer or (improperly) a destructor. If a base class has a
  1605. <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,
  1606. if any, must explicitly call it to ensure proper deletion of the base
  1607. class part of the instance.</p>
  1608. <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
  1609. to postpone destruction of the instance by creating a new reference to
  1610. it. This is called object <em>resurrection</em>. It is implementation-dependent
  1611. 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
  1612. 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
  1613. only calls it once.</p>
  1614. <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
  1615. that still exist when the interpreter exits.</p>
  1616. <div class="admonition note">
  1617. <p class="admonition-title">Note</p>
  1618. <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
  1619. the reference count for <code class="docutils literal notranslate"><span class="pre">x</span></code> by one, and the latter is only called when
  1620. <code class="docutils literal notranslate"><span class="pre">x</span></code>’s reference count reaches zero.</p>
  1621. </div>
  1622. <div class="impl-detail compound">
  1623. <p><strong>CPython implementation detail:</strong> It is possible for a reference cycle to prevent the reference count
  1624. of an object from going to zero. In this case, the cycle will be
  1625. 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
  1626. an exception has been caught in a local variable. The frame’s
  1627. locals then reference the exception, which references its own
  1628. traceback, which references the locals of all frames caught in the
  1629. traceback.</p>
  1630. <div class="admonition seealso">
  1631. <p class="admonition-title">See also</p>
  1632. <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>
  1633. </div>
  1634. </div>
  1635. <div class="admonition warning">
  1636. <p class="admonition-title">Warning</p>
  1637. <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
  1638. invoked, exceptions that occur during their execution are ignored, and a warning
  1639. is printed to <code class="docutils literal notranslate"><span class="pre">sys.stderr</span></code> instead. In particular:</p>
  1640. <ul class="simple">
  1641. <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,
  1642. 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
  1643. a lock or invoke any other blocking resource, it may deadlock as
  1644. the resource may already be taken by the code that gets interrupted
  1645. 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>
  1646. <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
  1647. consequence, the global variables it needs to access (including other
  1648. modules) may already have been deleted or set to <code class="docutils literal notranslate"><span class="pre">None</span></code>. Python
  1649. guarantees that globals whose name begins with a single underscore
  1650. are deleted from their module before other globals are deleted; if
  1651. no other references to such globals exist, this may help in assuring
  1652. that imported modules are still available at the time when the
  1653. <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>
  1654. </ul>
  1655. </div>
  1656. <span class="target" id="index-75"></span></dd></dl>
  1657. <dl class="py method">
  1658. <dt class="sig sig-object py" id="object.__repr__">
  1659. <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>
  1660. <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
  1661. representation of an object. If at all possible, this should look like a
  1662. valid Python expression that could be used to recreate an object with the
  1663. same value (given an appropriate environment). If this is not possible, a
  1664. 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.
  1665. 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>
  1666. 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
  1667. “informal” string representation of instances of that class is required.</p>
  1668. <p>This is typically used for debugging, so it is important that the representation
  1669. is information-rich and unambiguous.</p>
  1670. <span class="target" id="index-76"></span></dd></dl>
  1671. <dl class="py method">
  1672. <dt class="sig sig-object py" id="object.__str__">
  1673. <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>
  1674. <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> and the built-in functions
  1675. <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> and <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
  1676. printable string representation of an object. The return value must be a
  1677. <a class="reference internal" href="../library/stdtypes.html#textseq"><span class="std std-ref">string</span></a> object.</p>
  1678. <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
  1679. 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
  1680. convenient or concise representation can be used.</p>
  1681. <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>
  1682. 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>
  1683. </dd></dl>
  1684. <dl class="py method">
  1685. <dt class="sig sig-object py" id="object.__bytes__">
  1686. <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>
  1687. <dd><p id="index-77">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
  1688. 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.</p>
  1689. <span class="target" id="index-78"></span></dd></dl>
  1690. <dl class="py method">
  1691. <dt class="sig sig-object py" id="object.__format__">
  1692. <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>
  1693. <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,
  1694. 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”
  1695. string representation of an object. The <em>format_spec</em> argument is
  1696. a string that contains a description of the formatting options desired.
  1697. The interpretation of the <em>format_spec</em> argument is up to the type
  1698. 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
  1699. delegate formatting to one of the built-in types, or use a similar
  1700. formatting option syntax.</p>
  1701. <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>
  1702. <p>The return value must be a string object.</p>
  1703. <div class="versionchanged">
  1704. <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>
  1705. if passed any non-empty string.</p>
  1706. </div>
  1707. <div class="versionchanged">
  1708. <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
  1709. than <code class="docutils literal notranslate"><span class="pre">format(str(x),</span> <span class="pre">'')</span></code>.</p>
  1710. </div>
  1711. </dd></dl>
  1712. <dl class="py method" id="richcmpfuncs">
  1713. <dt class="sig sig-object py" id="object.__lt__">
  1714. <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>
  1715. <dt class="sig sig-object py" id="object.__le__">
  1716. <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>
  1717. <dt class="sig sig-object py" id="object.__eq__">
  1718. <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>
  1719. <dt class="sig sig-object py" id="object.__ne__">
  1720. <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>
  1721. <dt class="sig sig-object py" id="object.__gt__">
  1722. <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>
  1723. <dt class="sig sig-object py" id="object.__ge__">
  1724. <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>
  1725. <dd><p id="index-79">These are the so-called “rich comparison” methods. The correspondence between
  1726. 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>,
  1727. <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
  1728. <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
  1729. <code class="docutils literal notranslate"><span class="pre">x.__ge__(y)</span></code>.</p>
  1730. <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
  1731. not implement the operation for a given pair of arguments. By convention,
  1732. <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
  1733. methods can return any value, so if the comparison operator is used in a Boolean
  1734. context (e.g., in the condition of an <code class="docutils literal notranslate"><span class="pre">if</span></code> statement), Python will call
  1735. <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>
  1736. <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
  1737. <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:
  1738. <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
  1739. 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
  1740. <code class="xref py py-data docutils literal notranslate"><span class="pre">NotImplemented</span></code>. There are no other implied relationships among the
  1741. comparison operators or default implementations; for example, the truth of
  1742. <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
  1743. 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>
  1744. <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
  1745. 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
  1746. custom comparison operations and are usable as dictionary keys.</p>
  1747. <p>There are no swapped-argument versions of these methods (to be used when the
  1748. left argument does not support the operation but the right argument does);
  1749. 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,
  1750. <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
  1751. <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.
  1752. If the operands are of different types, and the right operand’s type is
  1753. a direct or indirect subclass of the left operand’s type,
  1754. the reflected method of the right operand has priority, otherwise
  1755. the left operand’s method has priority. Virtual subclassing is
  1756. not considered.</p>
  1757. <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
  1758. <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>
  1759. </dd></dl>
  1760. <dl class="py method">
  1761. <dt class="sig sig-object py" id="object.__hash__">
  1762. <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>
  1763. <dd><p id="index-80">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
  1764. 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
  1765. <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
  1766. property is that objects which compare equal have the same hash value; it is
  1767. advised to mix together the hash values of the components of the object that
  1768. also play a part in comparison of objects by packing them into a tuple and
  1769. hashing the tuple. Example:</p>
  1770. <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>
  1771. <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>
  1772. </pre></div>
  1773. </div>
  1774. <div class="admonition note">
  1775. <p class="admonition-title">Note</p>
  1776. <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
  1777. <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
  1778. typically 8 bytes on 64-bit builds and 4 bytes on 32-bit builds. If an
  1779. 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
  1780. sizes, be sure to check the width on all supported builds. An easy way
  1781. to do this is with
  1782. <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>
  1783. </div>
  1784. <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
  1785. <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
  1786. <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
  1787. collections. If a class defines mutable objects and implements an
  1788. <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
  1789. 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
  1790. immutable (if the object’s hash value changes, it will be in the wrong hash
  1791. bucket).</p>
  1792. <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
  1793. by default; with them, all objects compare unequal (except with themselves)
  1794. 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>
  1795. 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>
  1796. <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>
  1797. 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
  1798. <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
  1799. 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
  1800. their hash value, and will also be correctly identified as unhashable when
  1801. checking <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code>.</p>
  1802. <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
  1803. 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
  1804. 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>
  1805. <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
  1806. 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.
  1807. 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
  1808. 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
  1809. an <code class="docutils literal notranslate"><span class="pre">isinstance(obj,</span> <span class="pre">collections.abc.Hashable)</span></code> call.</p>
  1810. <div class="admonition note">
  1811. <p class="admonition-title">Note</p>
  1812. <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
  1813. “salted” with an unpredictable random value. Although they
  1814. remain constant within an individual Python process, they are not
  1815. predictable between repeated invocations of Python.</p>
  1816. <p>This is intended to provide protection against a denial-of-service caused
  1817. by carefully chosen inputs that exploit the worst case performance of a
  1818. dict insertion, <em>O</em>(<em>n</em><sup>2</sup>) complexity. See
  1819. <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>
  1820. <p>Changing hash values affects the iteration order of sets.
  1821. Python has never made guarantees about this ordering
  1822. (and it typically varies between 32-bit and 64-bit builds).</p>
  1823. <p>See also <span class="target" id="index-81"></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>
  1824. </div>
  1825. <div class="versionchanged">
  1826. <p><span class="versionmodified changed">Changed in version 3.3: </span>Hash randomization is enabled by default.</p>
  1827. </div>
  1828. </dd></dl>
  1829. <dl class="py method">
  1830. <dt class="sig sig-object py" id="object.__bool__">
  1831. <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>
  1832. <dd><p id="index-82">Called to implement truth value testing and the built-in operation
  1833. <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
  1834. 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
  1835. considered true if its result is nonzero. If a class defines neither
  1836. <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>, all its instances are considered
  1837. true.</p>
  1838. </dd></dl>
  1839. </section>
  1840. <section id="customizing-attribute-access">
  1841. <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>
  1842. <p>The following methods can be defined to customize the meaning of attribute
  1843. access (use of, assignment to, or deletion of <code class="docutils literal notranslate"><span class="pre">x.name</span></code>) for class instances.</p>
  1844. <dl class="py method">
  1845. <dt class="sig sig-object py" id="object.__getattr__">
  1846. <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>
  1847. <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>
  1848. (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
  1849. <em>name</em> is not an instance attribute or an attribute in the class tree
  1850. 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
  1851. <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)
  1852. 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>
  1853. <p>Note that if the attribute is found through the normal mechanism,
  1854. <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
  1855. <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
  1856. 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
  1857. other attributes of the instance. Note that at least for instance variables,
  1858. you can fake total control by not inserting any values in the instance attribute
  1859. dictionary (but instead inserting them in another object). See the
  1860. <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
  1861. over attribute access.</p>
  1862. </dd></dl>
  1863. <dl class="py method">
  1864. <dt class="sig sig-object py" id="object.__getattribute__">
  1865. <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>
  1866. <dd><p>Called unconditionally to implement attribute accesses for instances of the
  1867. 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
  1868. 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
  1869. <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
  1870. 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
  1871. recursion in this method, its implementation should always call the base class
  1872. method with the same name to access any attributes it needs, for example,
  1873. <code class="docutils literal notranslate"><span class="pre">object.__getattribute__(self,</span> <span class="pre">name)</span></code>.</p>
  1874. <div class="admonition note">
  1875. <p class="admonition-title">Note</p>
  1876. <p>This method may still be bypassed when looking up special methods as the
  1877. result of implicit invocation via language syntax or
  1878. <a class="reference internal" href="#builtin-functions"><span class="std std-ref">built-in functions</span></a>.
  1879. See <a class="reference internal" href="#special-lookup"><span class="std std-ref">Special method lookup</span></a>.</p>
  1880. </div>
  1881. <p class="audit-hook"><p>For certain sensitive attribute accesses, raises an
  1882. <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
  1883. <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">name</span></code>.</p>
  1884. </p>
  1885. </dd></dl>
  1886. <dl class="py method">
  1887. <dt class="sig sig-object py" id="object.__setattr__">
  1888. <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>
  1889. <dd><p>Called when an attribute assignment is attempted. This is called instead of
  1890. the normal mechanism (i.e. store the value in the instance dictionary).
  1891. <em>name</em> is the attribute name, <em>value</em> is the value to be assigned to it.</p>
  1892. <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
  1893. call the base class method with the same name, for example,
  1894. <code class="docutils literal notranslate"><span class="pre">object.__setattr__(self,</span> <span class="pre">name,</span> <span class="pre">value)</span></code>.</p>
  1895. <p class="audit-hook"><p>For certain sensitive attribute assignments, raises an
  1896. <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
  1897. <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>
  1898. </p>
  1899. </dd></dl>
  1900. <dl class="py method">
  1901. <dt class="sig sig-object py" id="object.__delattr__">
  1902. <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>
  1903. <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
  1904. 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>
  1905. <p class="audit-hook"><p>For certain sensitive attribute deletions, raises an
  1906. <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
  1907. <code class="docutils literal notranslate"><span class="pre">obj</span></code> and <code class="docutils literal notranslate"><span class="pre">name</span></code>.</p>
  1908. </p>
  1909. </dd></dl>
  1910. <dl class="py method">
  1911. <dt class="sig sig-object py" id="object.__dir__">
  1912. <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>
  1913. <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
  1914. 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>
  1915. </dd></dl>
  1916. <section id="customizing-module-attribute-access">
  1917. <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>
  1918. <p id="index-83">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
  1919. access to module attributes. The <code class="docutils literal notranslate"><span class="pre">__getattr__</span></code> function at the module level
  1920. should accept one argument which is the name of an attribute and return the
  1921. 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
  1922. not found on a module object through the normal lookup, i.e.
  1923. <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
  1924. 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,
  1925. it is called with the attribute name and the result is returned.</p>
  1926. <p>The <code class="docutils literal notranslate"><span class="pre">__dir__</span></code> function should accept no arguments, and return an iterable of
  1927. strings that represents the names accessible on module. If present, this
  1928. 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>
  1929. <p>For a more fine grained customization of the module behavior (setting
  1930. attributes, properties, etc.), one can set the <code class="docutils literal notranslate"><span class="pre">__class__</span></code> attribute of
  1931. 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>
  1932. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">sys</span>
  1933. <span class="kn">from</span> <span class="nn">types</span> <span class="kn">import</span> <span class="n">ModuleType</span>
  1934. <span class="k">class</span> <span class="nc">VerboseModule</span><span class="p">(</span><span class="n">ModuleType</span><span class="p">):</span>
  1935. <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  1936. <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>
  1937. <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>
  1938. <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>
  1939. <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>
  1940. <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>
  1941. </pre></div>
  1942. </div>
  1943. <div class="admonition note">
  1944. <p class="admonition-title">Note</p>
  1945. <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
  1946. affect lookups made using the attribute access syntax – directly accessing
  1947. the module globals (whether by code within the module, or via a reference
  1948. to the module’s globals dictionary) is unaffected.</p>
  1949. </div>
  1950. <div class="versionchanged">
  1951. <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>
  1952. </div>
  1953. <div class="versionadded">
  1954. <p><span class="versionmodified added">New 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>
  1955. </div>
  1956. <div class="admonition seealso">
  1957. <p class="admonition-title">See also</p>
  1958. <dl class="simple">
  1959. <dt><span class="target" id="index-84"></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>
  1960. </dd>
  1961. </dl>
  1962. </div>
  1963. </section>
  1964. <section id="implementing-descriptors">
  1965. <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>
  1966. <p>The following methods only apply when an instance of the class containing the
  1967. method (a so-called <em>descriptor</em> class) appears in an <em>owner</em> class (the
  1968. descriptor must be in either the owner’s class dictionary or in the class
  1969. dictionary for one of its parents). In the examples below, “the attribute”
  1970. refers to the attribute whose name is the key of the property in the owner
  1971. class’ <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>.</p>
  1972. <dl class="py method">
  1973. <dt class="sig sig-object py" id="object.__get__">
  1974. <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>
  1975. <dd><p>Called to get the attribute of the owner class (class attribute access) or
  1976. of an instance of that class (instance attribute access). The optional
  1977. <em>owner</em> argument is the owner class, while <em>instance</em> is the instance that
  1978. the attribute was accessed through, or <code class="docutils literal notranslate"><span class="pre">None</span></code> when the attribute is
  1979. accessed through the <em>owner</em>.</p>
  1980. <p>This method should return the computed attribute value or raise an
  1981. <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>
  1982. <p><span class="target" id="index-85"></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
  1983. arguments. Python’s own built-in descriptors support this specification;
  1984. however, it is likely that some third-party tools have descriptors
  1985. 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>
  1986. implementation always passes in both arguments whether they are required
  1987. or not.</p>
  1988. </dd></dl>
  1989. <dl class="py method">
  1990. <dt class="sig sig-object py" id="object.__set__">
  1991. <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>
  1992. <dd><p>Called to set the attribute on an instance <em>instance</em> of the owner class to a
  1993. new value, <em>value</em>.</p>
  1994. <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
  1995. descriptor to a “data descriptor”. See <a class="reference internal" href="#descriptor-invocation"><span class="std std-ref">Invoking Descriptors</span></a> for
  1996. more details.</p>
  1997. </dd></dl>
  1998. <dl class="py method">
  1999. <dt class="sig sig-object py" id="object.__delete__">
  2000. <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>
  2001. <dd><p>Called to delete the attribute on an instance <em>instance</em> of the owner class.</p>
  2002. </dd></dl>
  2003. <p>Instances of descriptors may also have the <code class="xref py py-attr docutils literal notranslate"><span class="pre">__objclass__</span></code> attribute
  2004. present:</p>
  2005. <dl class="py attribute">
  2006. <dt class="sig sig-object py" id="object.__objclass__">
  2007. <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>
  2008. <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
  2009. as specifying the class where this object was defined (setting this
  2010. appropriately can assist in runtime introspection of dynamic class attributes).
  2011. For callables, it may indicate that an instance of the given type (or a
  2012. subclass) is expected or required as the first positional argument (for example,
  2013. CPython sets this attribute for unbound methods that are implemented in C).</p>
  2014. </dd></dl>
  2015. </section>
  2016. <section id="invoking-descriptors">
  2017. <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>
  2018. <p>In general, a descriptor is an object attribute with “binding behavior”, one
  2019. whose attribute access has been overridden by methods in the descriptor
  2020. 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
  2021. <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
  2022. those methods are defined for an object, it is said to be a descriptor.</p>
  2023. <p>The default behavior for attribute access is to get, set, or delete the
  2024. attribute from an object’s dictionary. For instance, <code class="docutils literal notranslate"><span class="pre">a.x</span></code> has a lookup chain
  2025. 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
  2026. continuing through the base classes of <code class="docutils literal notranslate"><span class="pre">type(a)</span></code> excluding metaclasses.</p>
  2027. <p>However, if the looked-up value is an object defining one of the descriptor
  2028. methods, then Python may override the default behavior and invoke the descriptor
  2029. method instead. Where this occurs in the precedence chain depends on which
  2030. descriptor methods were defined and how they were called.</p>
  2031. <p>The starting point for descriptor invocation is a binding, <code class="docutils literal notranslate"><span class="pre">a.x</span></code>. How the
  2032. arguments are assembled depends on <code class="docutils literal notranslate"><span class="pre">a</span></code>:</p>
  2033. <dl class="simple">
  2034. <dt>Direct Call</dt><dd><p>The simplest and least common call is when user code directly invokes a
  2035. descriptor method: <code class="docutils literal notranslate"><span class="pre">x.__get__(a)</span></code>.</p>
  2036. </dd>
  2037. <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:
  2038. <code class="docutils literal notranslate"><span class="pre">type(a).__dict__['x'].__get__(a,</span> <span class="pre">type(a))</span></code>.</p>
  2039. </dd>
  2040. <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:
  2041. <code class="docutils literal notranslate"><span class="pre">A.__dict__['x'].__get__(None,</span> <span class="pre">A)</span></code>.</p>
  2042. </dd>
  2043. <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
  2044. <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
  2045. 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
  2046. returned unchanged.</p>
  2047. </dd>
  2048. </dl>
  2049. <p>For instance bindings, the precedence of descriptor invocation depends on
  2050. which descriptor methods are defined. A descriptor can define any combination
  2051. 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
  2052. <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
  2053. define <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code>, then accessing the attribute will return the descriptor
  2054. object itself unless there is a value in the object’s instance dictionary. If
  2055. 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
  2056. descriptor; if it defines neither, it is a non-data descriptor. Normally, data
  2057. 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
  2058. descriptors have just the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__get__()</span></code> method. Data descriptors with
  2059. <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
  2060. always override a redefinition in an
  2061. instance dictionary. In contrast, non-data descriptors can be overridden by
  2062. instances.</p>
  2063. <p>Python methods (including those decorated with
  2064. <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
  2065. implemented as non-data descriptors. Accordingly, instances can redefine and
  2066. override methods. This allows individual instances to acquire behaviors that
  2067. differ from other instances of the same class.</p>
  2068. <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,
  2069. instances cannot override the behavior of a property.</p>
  2070. </section>
  2071. <section id="slots">
  2072. <span id="id11"></span><h4><span class="section-number">3.3.2.4. </span>__slots__<a class="headerlink" href="#slots" title="Link to this heading">¶</a></h4>
  2073. <p><em>__slots__</em> allow us to explicitly declare data members (like
  2074. properties) and deny the creation of <a class="reference internal" href="../library/stdtypes.html#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>
  2075. (unless explicitly declared in <em>__slots__</em> or available in a parent.)</p>
  2076. <p>The space saved over using <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> can be significant.
  2077. Attribute lookup speed can be significantly improved as well.</p>
  2078. <dl class="py data">
  2079. <dt class="sig sig-object py" id="object.__slots__">
  2080. <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>
  2081. <dd><p>This class variable can be assigned a string, iterable, or sequence of
  2082. strings with variable names used by instances. <em>__slots__</em> reserves space
  2083. for the declared variables and prevents the automatic creation of
  2084. <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a>
  2085. and <em>__weakref__</em> for each instance.</p>
  2086. </dd></dl>
  2087. <p id="datamodel-note-slots">Notes on using <em>__slots__</em>:</p>
  2088. <ul class="simple">
  2089. <li><p>When inheriting from a class without <em>__slots__</em>, the
  2090. <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and
  2091. <em>__weakref__</em> attribute of the instances will always be accessible.</p></li>
  2092. <li><p>Without a <a class="reference internal" href="../library/stdtypes.html#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
  2093. variables not
  2094. listed in the <em>__slots__</em> definition. Attempts to assign to an unlisted
  2095. 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
  2096. variables is desired, then add <code class="docutils literal notranslate"><span class="pre">'__dict__'</span></code> to the sequence of strings in
  2097. the <em>__slots__</em> declaration.</p></li>
  2098. <li><p>Without a <em>__weakref__</em> variable for each instance, classes defining
  2099. <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.
  2100. If weak reference
  2101. support is needed, then add <code class="docutils literal notranslate"><span class="pre">'__weakref__'</span></code> to the sequence of strings in the
  2102. <em>__slots__</em> declaration.</p></li>
  2103. <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>
  2104. for each variable name. As a result, class attributes
  2105. cannot be used to set default values for instance variables defined by
  2106. <em>__slots__</em>; otherwise, the class attribute would overwrite the descriptor
  2107. assignment.</p></li>
  2108. <li><p>The action of a <em>__slots__</em> declaration is not limited to the class
  2109. where it is defined. <em>__slots__</em> declared in parents are available in
  2110. child classes. However, child subclasses will get a <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> and
  2111. <em>__weakref__</em> unless they also define <em>__slots__</em> (which should only
  2112. contain names of any <em>additional</em> slots).</p></li>
  2113. <li><p>If a class defines a slot also defined in a base class, the instance variable
  2114. defined by the base class slot is inaccessible (except by retrieving its
  2115. descriptor directly from the base class). This renders the meaning of the
  2116. program undefined. In the future, a check may be added to prevent this.</p></li>
  2117. <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
  2118. class derived from a
  2119. <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
  2120. <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>
  2121. <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>
  2122. <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
  2123. keys will be used as the slot names. The values of the dictionary can be used
  2124. to provide per-attribute docstrings that will be recognised by
  2125. <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>
  2126. <li><p><a class="reference internal" href="../library/stdtypes.html#instance.__class__" title="instance.__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
  2127. same <em>__slots__</em>.</p></li>
  2128. <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
  2129. classes can be used,
  2130. but only one parent is allowed to have attributes created by slots
  2131. (the other bases must have empty slot layouts) - violations raise
  2132. <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>
  2133. <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
  2134. created for each
  2135. of the iterator’s values. However, the <em>__slots__</em> attribute will be an empty
  2136. iterator.</p></li>
  2137. </ul>
  2138. </section>
  2139. </section>
  2140. <section id="customizing-class-creation">
  2141. <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>
  2142. <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
  2143. called on the parent class. This way, it is possible to write classes which
  2144. change the behavior of subclasses. This is closely related to class
  2145. decorators, but where class decorators only affect the specific class they’re
  2146. applied to, <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> solely applies to future subclasses of the
  2147. class defining the method.</p>
  2148. <dl class="py method">
  2149. <dt class="sig sig-object py" id="object.__init_subclass__">
  2150. <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>
  2151. <dd><p>This method is called whenever the containing class is subclassed.
  2152. <em>cls</em> is then the new subclass. If defined as a normal instance method,
  2153. this method is implicitly converted to a class method.</p>
  2154. <p>Keyword arguments which are given to a new class are passed to
  2155. the parent class’s <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code>. For compatibility with
  2156. other classes using <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code>, one should take out the
  2157. needed keyword arguments and pass the others over to the base
  2158. class, as in:</p>
  2159. <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>
  2160. <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>
  2161. <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>
  2162. <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>
  2163. <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>
  2164. <span class="k">pass</span>
  2165. </pre></div>
  2166. </div>
  2167. <p>The default implementation <code class="docutils literal notranslate"><span class="pre">object.__init_subclass__</span></code> does
  2168. nothing, but raises an error if it is called with any arguments.</p>
  2169. <div class="admonition note">
  2170. <p class="admonition-title">Note</p>
  2171. <p>The metaclass hint <code class="docutils literal notranslate"><span class="pre">metaclass</span></code> is consumed by the rest of the type
  2172. machinery, and is never passed to <code class="docutils literal notranslate"><span class="pre">__init_subclass__</span></code> implementations.
  2173. The actual metaclass (rather than the explicit hint) can be accessed as
  2174. <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code>.</p>
  2175. </div>
  2176. <div class="versionadded">
  2177. <p><span class="versionmodified added">New in version 3.6.</span></p>
  2178. </div>
  2179. </dd></dl>
  2180. <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
  2181. 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>
  2182. <dl class="py method">
  2183. <dt class="sig sig-object py" id="object.__set_name__">
  2184. <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>
  2185. <dd><p>Automatically called at the time the owning class <em>owner</em> is
  2186. created. The object has been assigned to <em>name</em> in that class:</p>
  2187. <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>
  2188. <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>
  2189. </pre></div>
  2190. </div>
  2191. <p>If the class variable is assigned after the class is created,
  2192. <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.
  2193. 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>
  2194. <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>
  2195. <span class="k">pass</span>
  2196. <span class="n">c</span> <span class="o">=</span> <span class="n">C</span><span class="p">()</span>
  2197. <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>
  2198. <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>
  2199. </pre></div>
  2200. </div>
  2201. <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>
  2202. <div class="versionadded">
  2203. <p><span class="versionmodified added">New in version 3.6.</span></p>
  2204. </div>
  2205. </dd></dl>
  2206. <section id="metaclasses">
  2207. <span id="id12"></span><h4><span class="section-number">3.3.3.1. </span>Metaclasses<a class="headerlink" href="#metaclasses" title="Link to this heading">¶</a></h4>
  2208. <p id="index-86">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
  2209. executed in a new namespace and the class name is bound locally to the
  2210. 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>
  2211. <p>The class creation process can be customized by passing the <code class="docutils literal notranslate"><span class="pre">metaclass</span></code>
  2212. keyword argument in the class definition line, or by inheriting from an
  2213. existing class that included such an argument. In the following example,
  2214. 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>
  2215. <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>
  2216. <span class="k">pass</span>
  2217. <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>
  2218. <span class="k">pass</span>
  2219. <span class="k">class</span> <span class="nc">MySubclass</span><span class="p">(</span><span class="n">MyClass</span><span class="p">):</span>
  2220. <span class="k">pass</span>
  2221. </pre></div>
  2222. </div>
  2223. <p>Any other keyword arguments that are specified in the class definition are
  2224. passed through to all metaclass operations described below.</p>
  2225. <p>When a class definition is executed, the following steps occur:</p>
  2226. <ul class="simple">
  2227. <li><p>MRO entries are resolved;</p></li>
  2228. <li><p>the appropriate metaclass is determined;</p></li>
  2229. <li><p>the class namespace is prepared;</p></li>
  2230. <li><p>the class body is executed;</p></li>
  2231. <li><p>the class object is created.</p></li>
  2232. </ul>
  2233. </section>
  2234. <section id="resolving-mro-entries">
  2235. <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>
  2236. <dl class="py method">
  2237. <dt class="sig sig-object py" id="object.__mro_entries__">
  2238. <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>
  2239. <dd><p>If a base that appears in a class definition is not an instance of
  2240. <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.
  2241. 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
  2242. 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.
  2243. The method is called with the original bases tuple
  2244. passed to the <em>bases</em> parameter, and must return a tuple
  2245. of classes that will be used instead of the base. The returned tuple may be
  2246. empty: in these cases, the original base is ignored.</p>
  2247. </dd></dl>
  2248. <div class="admonition seealso">
  2249. <p class="admonition-title">See also</p>
  2250. <dl class="simple">
  2251. <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>
  2252. </dd>
  2253. <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
  2254. <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>
  2255. </dd>
  2256. <dt><span class="target" id="index-87"></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>
  2257. </dd>
  2258. </dl>
  2259. </div>
  2260. </section>
  2261. <section id="determining-the-appropriate-metaclass">
  2262. <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>
  2263. <p id="index-88">The appropriate metaclass for a class definition is determined as follows:</p>
  2264. <ul class="simple">
  2265. <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>
  2266. <li><p>if an explicit metaclass is given and it is <em>not</em> an instance of
  2267. <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>
  2268. <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
  2269. bases are defined, then the most derived metaclass is used.</p></li>
  2270. </ul>
  2271. <p>The most derived metaclass is selected from the explicitly specified
  2272. metaclass (if any) and the metaclasses (i.e. <code class="docutils literal notranslate"><span class="pre">type(cls)</span></code>) of all specified
  2273. base classes. The most derived metaclass is one which is a subtype of <em>all</em>
  2274. of these candidate metaclasses. If none of the candidate metaclasses meets
  2275. that criterion, then the class definition will fail with <code class="docutils literal notranslate"><span class="pre">TypeError</span></code>.</p>
  2276. </section>
  2277. <section id="preparing-the-class-namespace">
  2278. <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>
  2279. <p id="index-89">Once the appropriate metaclass has been identified, then the class namespace
  2280. is prepared. If the metaclass has a <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> attribute, it is called
  2281. 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
  2282. additional keyword arguments, if any, come from the class definition). The
  2283. <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> method should be implemented as a
  2284. <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
  2285. 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
  2286. 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>
  2287. <p>If the metaclass has no <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code> attribute, then the class namespace
  2288. is initialised as an empty ordered mapping.</p>
  2289. <div class="admonition seealso">
  2290. <p class="admonition-title">See also</p>
  2291. <dl class="simple">
  2292. <dt><span class="target" id="index-90"></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>
  2293. </dd>
  2294. </dl>
  2295. </div>
  2296. </section>
  2297. <section id="executing-the-class-body">
  2298. <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>
  2299. <p id="index-91">The class body is executed (approximately) as
  2300. <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
  2301. 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
  2302. any methods) to reference names from the current and outer scopes when the
  2303. class definition occurs inside a function.</p>
  2304. <p>However, even when the class definition occurs inside the function, methods
  2305. defined inside the class still cannot see names defined at the class scope.
  2306. Class variables must be accessed through the first parameter of instance or
  2307. class methods, or through the implicit lexically scoped <code class="docutils literal notranslate"><span class="pre">__class__</span></code> reference
  2308. described in the next section.</p>
  2309. </section>
  2310. <section id="creating-the-class-object">
  2311. <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>
  2312. <p id="index-92">Once the class namespace has been populated by executing the class body,
  2313. the class object is created by calling
  2314. <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
  2315. passed here are the same as those passed to <code class="docutils literal notranslate"><span class="pre">__prepare__</span></code>).</p>
  2316. <p>This class object is the one that will be referenced by the zero-argument
  2317. 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
  2318. created by the compiler if any methods in a class body refer to either
  2319. <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
  2320. <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
  2321. lexical scoping, while the class or instance that was used to make the
  2322. current call is identified based on the first argument passed to the method.</p>
  2323. <div class="impl-detail compound">
  2324. <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
  2325. as a <code class="docutils literal notranslate"><span class="pre">__classcell__</span></code> entry in the class namespace. If present, this must
  2326. 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
  2327. initialised correctly.
  2328. 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>
  2329. </div>
  2330. <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
  2331. calls <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code>, the following additional customization steps are
  2332. invoked after creating the class object:</p>
  2333. <ol class="arabic simple">
  2334. <li><p>The <code class="docutils literal notranslate"><span class="pre">type.__new__</span></code> method collects all of the attributes in the class
  2335. 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>
  2336. <li><p>Those <code class="docutils literal notranslate"><span class="pre">__set_name__</span></code> methods are called with the class
  2337. being defined and the assigned name of that particular attribute;</p></li>
  2338. <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
  2339. immediate parent of the new class in its method resolution order.</p></li>
  2340. </ol>
  2341. <p>After the class object is created, it is passed to the class decorators
  2342. included in the class definition (if any) and the resulting object is bound
  2343. in the local namespace as the defined class.</p>
  2344. <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
  2345. namespace parameter is copied to a new ordered mapping and the original
  2346. object is discarded. The new copy is wrapped in a read-only proxy, which
  2347. becomes the <a class="reference internal" href="../library/stdtypes.html#object.__dict__" title="object.__dict__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">__dict__</span></code></a> attribute of the class object.</p>
  2348. <div class="admonition seealso">
  2349. <p class="admonition-title">See also</p>
  2350. <dl class="simple">
  2351. <dt><span class="target" id="index-93"></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>
  2352. </dd>
  2353. </dl>
  2354. </div>
  2355. </section>
  2356. <section id="uses-for-metaclasses">
  2357. <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>
  2358. <p>The potential uses for metaclasses are boundless. Some ideas that have been
  2359. explored include enum, logging, interface checking, automatic delegation,
  2360. automatic property creation, proxies, frameworks, and automatic resource
  2361. locking/synchronization.</p>
  2362. </section>
  2363. </section>
  2364. <section id="customizing-instance-and-subclass-checks">
  2365. <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>
  2366. <p>The following methods are used to override the default behavior of the
  2367. <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>
  2368. <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
  2369. order to allow the addition of Abstract Base Classes (ABCs) as “virtual base
  2370. classes” to any class or type (including built-in types), including other
  2371. ABCs.</p>
  2372. <dl class="py method">
  2373. <dt class="sig sig-object py" id="class.__instancecheck__">
  2374. <span class="sig-prename descclassname"><span class="pre">class.</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="#class.__instancecheck__" title="Link to this definition">¶</a></dt>
  2375. <dd><p>Return true if <em>instance</em> should be considered a (direct or indirect)
  2376. instance of <em>class</em>. If defined, called to implement <code class="docutils literal notranslate"><span class="pre">isinstance(instance,</span>
  2377. <span class="pre">class)</span></code>.</p>
  2378. </dd></dl>
  2379. <dl class="py method">
  2380. <dt class="sig sig-object py" id="class.__subclasscheck__">
  2381. <span class="sig-prename descclassname"><span class="pre">class.</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="#class.__subclasscheck__" title="Link to this definition">¶</a></dt>
  2382. <dd><p>Return true if <em>subclass</em> should be considered a (direct or indirect)
  2383. subclass of <em>class</em>. If defined, called to implement <code class="docutils literal notranslate"><span class="pre">issubclass(subclass,</span>
  2384. <span class="pre">class)</span></code>.</p>
  2385. </dd></dl>
  2386. <p>Note that these methods are looked up on the type (metaclass) of a class. They
  2387. cannot be defined as class methods in the actual class. This is consistent with
  2388. the lookup of special methods that are called on instances, only in this
  2389. case the instance is itself a class.</p>
  2390. <div class="admonition seealso">
  2391. <p class="admonition-title">See also</p>
  2392. <dl class="simple">
  2393. <dt><span class="target" id="index-94"></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
  2394. <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="#class.__instancecheck__" title="class.__instancecheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__instancecheck__()</span></code></a> and
  2395. <a class="reference internal" href="#class.__subclasscheck__" title="class.__subclasscheck__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">__subclasscheck__()</span></code></a>, with motivation for this functionality
  2396. 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>
  2397. module) to the language.</p>
  2398. </dd>
  2399. </dl>
  2400. </div>
  2401. </section>
  2402. <section id="emulating-generic-types">
  2403. <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>
  2404. <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
  2405. <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.
  2406. For example, the annotation <code class="docutils literal notranslate"><span class="pre">list[int]</span></code> might be used to signify a
  2407. <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>
  2408. <div class="admonition seealso">
  2409. <p class="admonition-title">See also</p>
  2410. <dl class="simple">
  2411. <dt><span class="target" id="index-95"></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>
  2412. </dd>
  2413. <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>
  2414. </dd>
  2415. <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
  2416. parameterized at runtime and understood by static type-checkers.</p>
  2417. </dd>
  2418. </dl>
  2419. </div>
  2420. <p>A class can <em>generally</em> only be parameterized if it defines the special
  2421. class method <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code>.</p>
  2422. <dl class="py method">
  2423. <dt class="sig sig-object py" id="object.__class_getitem__">
  2424. <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>
  2425. <dd><p>Return an object representing the specialization of a generic class
  2426. by type arguments found in <em>key</em>.</p>
  2427. <p>When defined on a class, <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> is automatically a class
  2428. method. As such, there is no need for it to be decorated with
  2429. <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>
  2430. </dd></dl>
  2431. <section id="the-purpose-of-class-getitem">
  2432. <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>
  2433. <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
  2434. parameterization of standard-library generic classes in order to more easily
  2435. 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>
  2436. <p>To implement custom generic classes that can be parameterized at runtime and
  2437. understood by static type-checkers, users should either inherit from a standard
  2438. 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
  2439. 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
  2440. <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code>.</p>
  2441. <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
  2442. outside of the standard library may not be understood by third-party
  2443. type-checkers such as mypy. Using <code class="docutils literal notranslate"><span class="pre">__class_getitem__()</span></code> on any class for
  2444. purposes other than type hinting is discouraged.</p>
  2445. </section>
  2446. <section id="class-getitem-versus-getitem">
  2447. <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>
  2448. <p>Usually, the <a class="reference internal" href="expressions.html#subscriptions"><span class="std std-ref">subscription</span></a> of an object using square
  2449. 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
  2450. the object’s class. However, if the object being subscribed is itself a class,
  2451. 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.
  2452. <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>
  2453. object if it is properly defined.</p>
  2454. <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
  2455. follows something like the following process to decide whether
  2456. <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
  2457. called:</p>
  2458. <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>
  2459. <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>
  2460. <span class="w"> </span><span class="sd">&quot;&quot;&quot;Return the result of the expression &#39;obj[x]&#39;&quot;&quot;&quot;</span>
  2461. <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>
  2462. <span class="c1"># If the class of obj defines __getitem__,</span>
  2463. <span class="c1"># call class_of_obj.__getitem__(obj, x)</span>
  2464. <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>
  2465. <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>
  2466. <span class="c1"># Else, if obj is a class and defines __class_getitem__,</span>
  2467. <span class="c1"># call obj.__class_getitem__(x)</span>
  2468. <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>
  2469. <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>
  2470. <span class="c1"># Else, raise an exception</span>
  2471. <span class="k">else</span><span class="p">:</span>
  2472. <span class="k">raise</span> <span class="ne">TypeError</span><span class="p">(</span>
  2473. <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>
  2474. <span class="p">)</span>
  2475. </pre></div>
  2476. </div>
  2477. <p>In Python, all classes are themselves instances of other classes. The class of
  2478. 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
  2479. <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
  2480. <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>,
  2481. <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
  2482. <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>
  2483. <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>
  2484. <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>
  2485. <span class="go">&lt;class &#39;type&#39;&gt;</span>
  2486. <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>
  2487. <span class="go">True</span>
  2488. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># &quot;list[int]&quot; calls &quot;list.__class_getitem__(int)&quot;</span>
  2489. <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>
  2490. <span class="go">list[int]</span>
  2491. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># list.__class_getitem__ returns a GenericAlias object:</span>
  2492. <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>
  2493. <span class="go">&lt;class &#39;types.GenericAlias&#39;&gt;</span>
  2494. </pre></div>
  2495. </div>
  2496. <p>However, if a class has a custom metaclass that defines
  2497. <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
  2498. 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>
  2499. <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>
  2500. <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>
  2501. <span class="gp">... </span><span class="w"> </span><span class="sd">&quot;&quot;&quot;A breakfast menu&quot;&quot;&quot;</span>
  2502. <span class="gp">... </span> <span class="n">SPAM</span> <span class="o">=</span> <span class="s1">&#39;spam&#39;</span>
  2503. <span class="gp">... </span> <span class="n">BACON</span> <span class="o">=</span> <span class="s1">&#39;bacon&#39;</span>
  2504. <span class="gp">...</span>
  2505. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># Enum classes have a custom metaclass:</span>
  2506. <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>
  2507. <span class="go">&lt;class &#39;enum.EnumMeta&#39;&gt;</span>
  2508. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># EnumMeta defines __getitem__,</span>
  2509. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># so __class_getitem__ is not called,</span>
  2510. <span class="gp">&gt;&gt;&gt; </span><span class="c1"># and the result is not a GenericAlias object:</span>
  2511. <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>
  2512. <span class="go">&lt;Menu.SPAM: &#39;spam&#39;&gt;</span>
  2513. <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>
  2514. <span class="go">&lt;enum &#39;Menu&#39;&gt;</span>
  2515. </pre></div>
  2516. </div>
  2517. <div class="admonition seealso">
  2518. <p class="admonition-title">See also</p>
  2519. <dl class="simple">
  2520. <dt><span class="target" id="index-96"></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
  2521. <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>
  2522. 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>
  2523. </dd>
  2524. </dl>
  2525. </div>
  2526. </section>
  2527. </section>
  2528. <section id="emulating-callable-objects">
  2529. <span id="id13"></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>
  2530. <dl class="py method">
  2531. <dt class="sig sig-object py" id="object.__call__">
  2532. <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>
  2533. <dd><p id="index-97">Called when the instance is “called” as a function; if this method is defined,
  2534. <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>.</p>
  2535. </dd></dl>
  2536. </section>
  2537. <section id="emulating-container-types">
  2538. <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>
  2539. <p>The following methods can be defined to implement container objects. Containers
  2540. 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
  2541. <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
  2542. <a class="reference internal" href="../library/stdtypes.html#dict" title="dict"><code class="xref py py-class docutils literal notranslate"><span class="pre">dictionaries</span></code></a>),
  2543. but can represent other containers as well. The first set of methods is used
  2544. either to emulate a sequence or to emulate a mapping; the difference is that for
  2545. 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>
  2546. <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
  2547. range of items. It is also recommended that mappings provide the methods
  2548. <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>,
  2549. <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
  2550. <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>
  2551. 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
  2552. <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>
  2553. <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
  2554. <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>,
  2555. <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>.
  2556. 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>,
  2557. <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>,
  2558. <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>
  2559. objects. Finally,
  2560. sequence types should implement addition (meaning concatenation) and
  2561. multiplication (meaning repetition) by defining the methods
  2562. <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>,
  2563. <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>
  2564. described below; they should not define other numerical
  2565. operators. It is recommended that both mappings and sequences implement the
  2566. <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>
  2567. operator; for
  2568. mappings, <code class="docutils literal notranslate"><span class="pre">in</span></code> should search the mapping’s keys; for sequences, it should
  2569. search through the values. It is further recommended that both mappings and
  2570. 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
  2571. through the container; for mappings, <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> should iterate
  2572. through the object’s keys; for sequences, it should iterate through the values.</p>
  2573. <dl class="py method">
  2574. <dt class="sig sig-object py" id="object.__len__">
  2575. <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>
  2576. <dd><p id="index-98">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
  2577. 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
  2578. <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
  2579. considered to be false in a Boolean context.</p>
  2580. <div class="impl-detail compound">
  2581. <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>.
  2582. 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
  2583. <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
  2584. <code class="xref py py-exc docutils literal notranslate"><span class="pre">OverflowError</span></code> by truth value testing, an object must define a
  2585. <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>
  2586. </div>
  2587. </dd></dl>
  2588. <dl class="py method">
  2589. <dt class="sig sig-object py" id="object.__length_hint__">
  2590. <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>
  2591. <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
  2592. length for the object (which may be greater or less than the actual length).
  2593. The length must be an integer <code class="docutils literal notranslate"><span class="pre">&gt;=</span></code> 0. The return value may also be
  2594. <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
  2595. <code class="docutils literal notranslate"><span class="pre">__length_hint__</span></code> method didn’t exist at all. This method is purely an
  2596. optimization and is never required for correctness.</p>
  2597. <div class="versionadded">
  2598. <p><span class="versionmodified added">New in version 3.4.</span></p>
  2599. </div>
  2600. </dd></dl>
  2601. <div class="admonition note" id="index-99">
  2602. <p class="admonition-title">Note</p>
  2603. <p>Slicing is done exclusively with the following three methods. A call like</p>
  2604. <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>
  2605. </pre></div>
  2606. </div>
  2607. <p>is translated to</p>
  2608. <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>
  2609. </pre></div>
  2610. </div>
  2611. <p>and so forth. Missing slice items are always filled in with <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
  2612. </div>
  2613. <dl class="py method">
  2614. <dt class="sig sig-object py" id="object.__getitem__">
  2615. <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>
  2616. <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,
  2617. the accepted keys should be integers. Optionally, they may support
  2618. <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.
  2619. If <em>key</em> is
  2620. 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
  2621. outside the set of indexes for the sequence (after any special
  2622. 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
  2623. <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),
  2624. <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>
  2625. <div class="admonition note">
  2626. <p class="admonition-title">Note</p>
  2627. <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
  2628. illegal indexes to allow proper detection of the end of the sequence.</p>
  2629. </div>
  2630. <div class="admonition note">
  2631. <p class="admonition-title">Note</p>
  2632. <p>When <a class="reference internal" href="expressions.html#subscriptions"><span class="std std-ref">subscripting</span></a> a <em>class</em>, the special
  2633. 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
  2634. <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
  2635. details.</p>
  2636. </div>
  2637. </dd></dl>
  2638. <dl class="py method">
  2639. <dt class="sig sig-object py" id="object.__setitem__">
  2640. <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>
  2641. <dd><p>Called to implement assignment to <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. Same note as for
  2642. <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
  2643. objects support changes to the values for keys, or if new keys can be added, or
  2644. for sequences if elements can be replaced. The same exceptions should be raised
  2645. 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>
  2646. </dd></dl>
  2647. <dl class="py method">
  2648. <dt class="sig sig-object py" id="object.__delitem__">
  2649. <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>
  2650. <dd><p>Called to implement deletion of <code class="docutils literal notranslate"><span class="pre">self[key]</span></code>. Same note as for
  2651. <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
  2652. objects support removal of keys, or for sequences if elements can be removed
  2653. from the sequence. The same exceptions should be raised for improper <em>key</em>
  2654. 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>
  2655. </dd></dl>
  2656. <dl class="py method">
  2657. <dt class="sig sig-object py" id="object.__missing__">
  2658. <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>
  2659. <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
  2660. when key is not in the dictionary.</p>
  2661. </dd></dl>
  2662. <dl class="py method">
  2663. <dt class="sig sig-object py" id="object.__iter__">
  2664. <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>
  2665. <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.
  2666. This method should return a new iterator object that can iterate over all the
  2667. objects in the container. For mappings, it should iterate over the keys of
  2668. the container.</p>
  2669. </dd></dl>
  2670. <dl class="py method">
  2671. <dt class="sig sig-object py" id="object.__reversed__">
  2672. <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>
  2673. <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
  2674. reverse iteration. It should return a new iterator object that iterates
  2675. over all the objects in the container in reverse order.</p>
  2676. <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>
  2677. 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
  2678. <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
  2679. 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
  2680. 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>
  2681. </dd></dl>
  2682. <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
  2683. implemented as an iteration through a container. However, container objects can
  2684. supply the following special method with a more efficient implementation, which
  2685. also does not require the object be iterable.</p>
  2686. <dl class="py method">
  2687. <dt class="sig sig-object py" id="object.__contains__">
  2688. <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>
  2689. <dd><p>Called to implement membership test operators. Should return true if <em>item</em>
  2690. is in <em>self</em>, false otherwise. For mapping objects, this should consider the
  2691. keys of the mapping rather than the values or the key-item pairs.</p>
  2692. <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
  2693. 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
  2694. 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
  2695. reference</span></a>.</p>
  2696. </dd></dl>
  2697. </section>
  2698. <section id="emulating-numeric-types">
  2699. <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>
  2700. <p>The following methods can be defined to emulate numeric objects. Methods
  2701. corresponding to operations that are not supported by the particular kind of
  2702. number implemented (e.g., bitwise operations for non-integral numbers) should be
  2703. left undefined.</p>
  2704. <dl class="py method">
  2705. <dt class="sig sig-object py" id="object.__add__">
  2706. <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>
  2707. <dt class="sig sig-object py" id="object.__sub__">
  2708. <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>
  2709. <dt class="sig sig-object py" id="object.__mul__">
  2710. <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>
  2711. <dt class="sig sig-object py" id="object.__matmul__">
  2712. <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>
  2713. <dt class="sig sig-object py" id="object.__truediv__">
  2714. <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>
  2715. <dt class="sig sig-object py" id="object.__floordiv__">
  2716. <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>
  2717. <dt class="sig sig-object py" id="object.__mod__">
  2718. <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>
  2719. <dt class="sig sig-object py" id="object.__divmod__">
  2720. <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>
  2721. <dt class="sig sig-object py" id="object.__pow__">
  2722. <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>
  2723. <dt class="sig sig-object py" id="object.__lshift__">
  2724. <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>
  2725. <dt class="sig sig-object py" id="object.__rshift__">
  2726. <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>
  2727. <dt class="sig sig-object py" id="object.__and__">
  2728. <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>
  2729. <dt class="sig sig-object py" id="object.__xor__">
  2730. <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>
  2731. <dt class="sig sig-object py" id="object.__or__">
  2732. <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>
  2733. <dd><p id="index-100">These methods are called to implement the binary arithmetic operations
  2734. (<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>,
  2735. <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
  2736. 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
  2737. 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
  2738. <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
  2739. <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
  2740. <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
  2741. 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>
  2742. function is to be supported.</p>
  2743. <p>If one of those methods does not support the operation with the supplied
  2744. 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>
  2745. </dd></dl>
  2746. <dl class="py method">
  2747. <dt class="sig sig-object py" id="object.__radd__">
  2748. <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>
  2749. <dt class="sig sig-object py" id="object.__rsub__">
  2750. <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>
  2751. <dt class="sig sig-object py" id="object.__rmul__">
  2752. <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>
  2753. <dt class="sig sig-object py" id="object.__rmatmul__">
  2754. <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>
  2755. <dt class="sig sig-object py" id="object.__rtruediv__">
  2756. <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>
  2757. <dt class="sig sig-object py" id="object.__rfloordiv__">
  2758. <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>
  2759. <dt class="sig sig-object py" id="object.__rmod__">
  2760. <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>
  2761. <dt class="sig sig-object py" id="object.__rdivmod__">
  2762. <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>
  2763. <dt class="sig sig-object py" id="object.__rpow__">
  2764. <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>
  2765. <dt class="sig sig-object py" id="object.__rlshift__">
  2766. <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>
  2767. <dt class="sig sig-object py" id="object.__rrshift__">
  2768. <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>
  2769. <dt class="sig sig-object py" id="object.__rand__">
  2770. <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>
  2771. <dt class="sig sig-object py" id="object.__rxor__">
  2772. <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>
  2773. <dt class="sig sig-object py" id="object.__ror__">
  2774. <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>
  2775. <dd><p id="index-101">These methods are called to implement the binary arithmetic operations
  2776. (<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>,
  2777. <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
  2778. (swapped) operands. These functions are only called if the left operand does
  2779. not support the corresponding operation <a class="footnote-reference brackets" href="#id19" id="id14" role="doc-noteref"><span class="fn-bracket">[</span>3<span class="fn-bracket">]</span></a> and the operands are of different
  2780. types. <a class="footnote-reference brackets" href="#id20" id="id15" 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
  2781. 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,
  2782. <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
  2783. <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>
  2784. <p id="index-102">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
  2785. coercion rules would become too complicated).</p>
  2786. <div class="admonition note">
  2787. <p class="admonition-title">Note</p>
  2788. <p>If the right operand’s type is a subclass of the left operand’s type and
  2789. that subclass provides a different implementation of the reflected method
  2790. for the operation, this method will be called before the left operand’s
  2791. non-reflected method. This behavior allows subclasses to override their
  2792. ancestors’ operations.</p>
  2793. </div>
  2794. </dd></dl>
  2795. <dl class="py method">
  2796. <dt class="sig sig-object py" id="object.__iadd__">
  2797. <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>
  2798. <dt class="sig sig-object py" id="object.__isub__">
  2799. <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>
  2800. <dt class="sig sig-object py" id="object.__imul__">
  2801. <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>
  2802. <dt class="sig sig-object py" id="object.__imatmul__">
  2803. <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>
  2804. <dt class="sig sig-object py" id="object.__itruediv__">
  2805. <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>
  2806. <dt class="sig sig-object py" id="object.__ifloordiv__">
  2807. <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>
  2808. <dt class="sig sig-object py" id="object.__imod__">
  2809. <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>
  2810. <dt class="sig sig-object py" id="object.__ipow__">
  2811. <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>
  2812. <dt class="sig sig-object py" id="object.__ilshift__">
  2813. <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>
  2814. <dt class="sig sig-object py" id="object.__irshift__">
  2815. <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>
  2816. <dt class="sig sig-object py" id="object.__iand__">
  2817. <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>
  2818. <dt class="sig sig-object py" id="object.__ixor__">
  2819. <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>
  2820. <dt class="sig sig-object py" id="object.__ior__">
  2821. <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>
  2822. <dd><p>These methods are called to implement the augmented arithmetic assignments
  2823. (<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>,
  2824. <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
  2825. operation in-place (modifying <em>self</em>) and return the result (which could be,
  2826. but does not have to be, <em>self</em>). If a specific method is not defined, or if
  2827. 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
  2828. augmented assignment falls back to the normal methods. For instance, if <em>x</em>
  2829. 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
  2830. 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>
  2831. 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
  2832. <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
  2833. certain situations, augmented assignment can result in unexpected errors (see
  2834. <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
  2835. part of the data model.</p>
  2836. </dd></dl>
  2837. <dl class="py method">
  2838. <dt class="sig sig-object py" id="object.__neg__">
  2839. <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>
  2840. <dt class="sig sig-object py" id="object.__pos__">
  2841. <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>
  2842. <dt class="sig sig-object py" id="object.__abs__">
  2843. <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>
  2844. <dt class="sig sig-object py" id="object.__invert__">
  2845. <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>
  2846. <dd><p id="index-103">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>
  2847. and <code class="docutils literal notranslate"><span class="pre">~</span></code>).</p>
  2848. </dd></dl>
  2849. <dl class="py method">
  2850. <dt class="sig sig-object py" id="object.__complex__">
  2851. <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>
  2852. <dt class="sig sig-object py" id="object.__int__">
  2853. <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>
  2854. <dt class="sig sig-object py" id="object.__float__">
  2855. <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>
  2856. <dd><p id="index-104">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>,
  2857. <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
  2858. of the appropriate type.</p>
  2859. </dd></dl>
  2860. <dl class="py method">
  2861. <dt class="sig sig-object py" id="object.__index__">
  2862. <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>
  2863. <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
  2864. losslessly convert the numeric object to an integer object (such as in
  2865. 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>
  2866. functions). Presence of this method indicates that the numeric object is
  2867. an integer type. Must return an integer.</p>
  2868. <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
  2869. 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>
  2870. 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>
  2871. </dd></dl>
  2872. <dl class="py method">
  2873. <dt class="sig sig-object py" id="object.__round__">
  2874. <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>
  2875. <dt class="sig sig-object py" id="object.__trunc__">
  2876. <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>
  2877. <dt class="sig sig-object py" id="object.__floor__">
  2878. <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>
  2879. <dt class="sig sig-object py" id="object.__ceil__">
  2880. <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>
  2881. <dd><p id="index-105">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>
  2882. 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>.
  2883. 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
  2884. 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>
  2885. (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>
  2886. <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
  2887. <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>
  2888. <div class="versionchanged">
  2889. <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>
  2890. </div>
  2891. </dd></dl>
  2892. </section>
  2893. <section id="with-statement-context-managers">
  2894. <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>
  2895. <p>A <em class="dfn">context manager</em> is an object that defines the runtime context to be
  2896. 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
  2897. handles the entry into, and the exit from, the desired runtime context for the
  2898. execution of the block of code. Context managers are normally invoked using the
  2899. <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
  2900. used by directly invoking their methods.</p>
  2901. <p id="index-106">Typical uses of context managers include saving and restoring various kinds of
  2902. global state, locking and unlocking resources, closing opened files, etc.</p>
  2903. <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>.</p>
  2904. <dl class="py method">
  2905. <dt class="sig sig-object py" id="object.__enter__">
  2906. <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>
  2907. <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
  2908. will bind this method’s return value to the target(s) specified in the
  2909. <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause of the statement, if any.</p>
  2910. </dd></dl>
  2911. <dl class="py method">
  2912. <dt class="sig sig-object py" id="object.__exit__">
  2913. <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>
  2914. <dd><p>Exit the runtime context related to this object. The parameters describe the
  2915. exception that caused the context to be exited. If the context was exited
  2916. 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>
  2917. <p>If an exception is supplied, and the method wishes to suppress the exception
  2918. (i.e., prevent it from being propagated), it should return a true value.
  2919. Otherwise, the exception will be processed normally upon exit from this method.</p>
  2920. <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;
  2921. this is the caller’s responsibility.</p>
  2922. </dd></dl>
  2923. <div class="admonition seealso">
  2924. <p class="admonition-title">See also</p>
  2925. <dl class="simple">
  2926. <dt><span class="target" id="index-107"></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>
  2927. statement.</p>
  2928. </dd>
  2929. </dl>
  2930. </div>
  2931. </section>
  2932. <section id="customizing-positional-arguments-in-class-pattern-matching">
  2933. <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>
  2934. <p>When using a class name in a pattern, positional arguments in the pattern are not
  2935. 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
  2936. 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
  2937. define a <em>__match_args__</em> attribute.</p>
  2938. <dl class="py data">
  2939. <dt class="sig sig-object py" id="object.__match_args__">
  2940. <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>
  2941. <dd><p>This class variable can be assigned a tuple of strings. When this class is
  2942. used in a class pattern with positional arguments, each positional argument will
  2943. be converted into a keyword argument, using the corresponding value in
  2944. <em>__match_args__</em> as the keyword. The absence of this attribute is equivalent to
  2945. setting it to <code class="docutils literal notranslate"><span class="pre">()</span></code>.</p>
  2946. </dd></dl>
  2947. <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
  2948. 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
  2949. that the number of arguments in the pattern must be smaller than or equal to the number
  2950. of elements in <em>__match_args__</em>; if it is larger, the pattern match attempt will raise
  2951. 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>
  2952. <div class="versionadded">
  2953. <p><span class="versionmodified added">New in version 3.10.</span></p>
  2954. </div>
  2955. <div class="admonition seealso">
  2956. <p class="admonition-title">See also</p>
  2957. <dl class="simple">
  2958. <dt><span class="target" id="index-108"></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>
  2959. </dd>
  2960. </dl>
  2961. </div>
  2962. </section>
  2963. <section id="emulating-buffer-types">
  2964. <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>
  2965. <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
  2966. objects to expose efficient access to a low-level memory array. This protocol
  2967. 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>,
  2968. and third-party libraries may define additional buffer types.</p>
  2969. <p>While buffer types are usually implemented in C, it is also possible to
  2970. implement the protocol in Python.</p>
  2971. <dl class="py method">
  2972. <dt class="sig sig-object py" id="object.__buffer__">
  2973. <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>
  2974. <dd><p>Called when a buffer is requested from <em>self</em> (for example, by the
  2975. <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
  2976. representing the kind of buffer requested, affecting for example whether
  2977. 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>
  2978. provides a convenient way to interpret the flags. The method must return
  2979. 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>
  2980. </dd></dl>
  2981. <dl class="py method">
  2982. <dt class="sig sig-object py" id="object.__release_buffer__">
  2983. <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>
  2984. <dd><p>Called when a buffer is no longer needed. The <em>buffer</em> argument is a
  2985. <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
  2986. <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
  2987. with the buffer. This method should return <code class="docutils literal notranslate"><span class="pre">None</span></code>.
  2988. Buffer objects that do not need to perform any cleanup are not required
  2989. to implement this method.</p>
  2990. </dd></dl>
  2991. <div class="versionadded">
  2992. <p><span class="versionmodified added">New in version 3.12.</span></p>
  2993. </div>
  2994. <div class="admonition seealso">
  2995. <p class="admonition-title">See also</p>
  2996. <dl class="simple">
  2997. <dt><span class="target" id="index-109"></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>
  2998. </dd>
  2999. <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>
  3000. </dd>
  3001. </dl>
  3002. </div>
  3003. </section>
  3004. <section id="special-method-lookup">
  3005. <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>
  3006. <p>For custom classes, implicit invocations of special methods are only guaranteed
  3007. to work correctly if defined on an object’s type, not in the object’s instance
  3008. dictionary. That behaviour is the reason why the following code raises an
  3009. exception:</p>
  3010. <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>
  3011. <span class="gp">... </span> <span class="k">pass</span>
  3012. <span class="gp">...</span>
  3013. <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>
  3014. <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>
  3015. <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>
  3016. <span class="gt">Traceback (most recent call last):</span>
  3017. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  3018. <span class="gr">TypeError</span>: <span class="n">object of type &#39;C&#39; has no len()</span>
  3019. </pre></div>
  3020. </div>
  3021. <p>The rationale behind this behaviour lies with a number of special methods such
  3022. 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
  3023. by all objects,
  3024. including type objects. If the implicit lookup of these methods used the
  3025. conventional lookup process, they would fail when invoked on the type object
  3026. itself:</p>
  3027. <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>
  3028. <span class="go">True</span>
  3029. <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>
  3030. <span class="gt">Traceback (most recent call last):</span>
  3031. File <span class="nb">&quot;&lt;stdin&gt;&quot;</span>, line <span class="m">1</span>, in <span class="n">&lt;module&gt;</span>
  3032. <span class="gr">TypeError</span>: <span class="n">descriptor &#39;__hash__&#39; of &#39;int&#39; object needs an argument</span>
  3033. </pre></div>
  3034. </div>
  3035. <p>Incorrectly attempting to invoke an unbound method of a class in this way is
  3036. sometimes referred to as ‘metaclass confusion’, and is avoided by bypassing
  3037. the instance when looking up special methods:</p>
  3038. <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>
  3039. <span class="go">True</span>
  3040. <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>
  3041. <span class="go">True</span>
  3042. </pre></div>
  3043. </div>
  3044. <p>In addition to bypassing any instance attributes in the interest of
  3045. correctness, implicit special method lookup generally also bypasses the
  3046. <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>
  3047. <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>
  3048. <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>
  3049. <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>
  3050. <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>
  3051. <span class="gp">...</span>
  3052. <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>
  3053. <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>
  3054. <span class="gp">... </span> <span class="k">return</span> <span class="mi">10</span>
  3055. <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>
  3056. <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>
  3057. <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>
  3058. <span class="gp">...</span>
  3059. <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>
  3060. <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>
  3061. <span class="go">Class getattribute invoked</span>
  3062. <span class="go">10</span>
  3063. <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>
  3064. <span class="go">Metaclass getattribute invoked</span>
  3065. <span class="go">10</span>
  3066. <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>
  3067. <span class="go">10</span>
  3068. </pre></div>
  3069. </div>
  3070. <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
  3071. provides significant scope for speed optimisations within the
  3072. interpreter, at the cost of some flexibility in the handling of
  3073. special methods (the special method <em>must</em> be set on the class
  3074. object itself in order to be consistently invoked by the interpreter).</p>
  3075. </section>
  3076. </section>
  3077. <section id="coroutines">
  3078. <span id="index-110"></span><h2><span class="section-number">3.4. </span>Coroutines<a class="headerlink" href="#coroutines" title="Link to this heading">¶</a></h2>
  3079. <section id="awaitable-objects">
  3080. <h3><span class="section-number">3.4.1. </span>Awaitable Objects<a class="headerlink" href="#awaitable-objects" title="Link to this heading">¶</a></h3>
  3081. <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.
  3082. <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
  3083. are awaitable.</p>
  3084. <div class="admonition note">
  3085. <p class="admonition-title">Note</p>
  3086. <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
  3087. 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>
  3088. 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>
  3089. </div>
  3090. <dl class="py method">
  3091. <dt class="sig sig-object py" id="object.__await__">
  3092. <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>
  3093. <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
  3094. <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
  3095. 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.</p>
  3096. <div class="admonition note">
  3097. <p class="admonition-title">Note</p>
  3098. <p>The language doesn’t place any restriction on the type or value of the
  3099. objects yielded by the iterator returned by <code class="docutils literal notranslate"><span class="pre">__await__</span></code>, as this is
  3100. specific to the implementation of the asynchronous execution framework
  3101. (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>
  3102. </div>
  3103. </dd></dl>
  3104. <div class="versionadded">
  3105. <p><span class="versionmodified added">New in version 3.5.</span></p>
  3106. </div>
  3107. <div class="admonition seealso">
  3108. <p class="admonition-title">See also</p>
  3109. <p><span class="target" id="index-111"></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>
  3110. </div>
  3111. </section>
  3112. <section id="coroutine-objects">
  3113. <span id="id16"></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>
  3114. <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.
  3115. 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
  3116. iterating over the result. When the coroutine has finished executing and
  3117. 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
  3118. <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
  3119. coroutine raises an exception, it is propagated by the iterator. Coroutines
  3120. 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>
  3121. <p>Coroutines also have the methods listed below, which are analogous to
  3122. 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
  3123. generators, coroutines do not directly support iteration.</p>
  3124. <div class="versionchanged">
  3125. <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>
  3126. </div>
  3127. <dl class="py method">
  3128. <dt class="sig sig-object py" id="coroutine.send">
  3129. <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>
  3130. <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>,
  3131. this is equivalent to advancing the iterator returned by
  3132. <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
  3133. 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
  3134. the coroutine to suspend. The result (return value,
  3135. <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
  3136. iterating over the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__await__()</span></code> return value, described above.</p>
  3137. </dd></dl>
  3138. <dl class="py method">
  3139. <dt class="sig sig-object py" id="coroutine.throw">
  3140. <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>
  3141. <dt class="sig sig-object py">
  3142. <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>
  3143. <dd><p>Raises the specified exception in the coroutine. This method delegates
  3144. 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
  3145. the coroutine to suspend, if it has such a method. Otherwise,
  3146. the exception is raised at the suspension point. The result
  3147. (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
  3148. 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
  3149. above. If the exception is not caught in the coroutine, it propagates
  3150. back to the caller.</p>
  3151. <div class="versionchanged">
  3152. <p><span class="versionmodified changed">Changed in version 3.12: </span>The second signature (type[, value[, traceback]]) is deprecated and
  3153. may be removed in a future version of Python.</p>
  3154. </div>
  3155. </dd></dl>
  3156. <dl class="py method">
  3157. <dt class="sig sig-object py" id="coroutine.close">
  3158. <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>
  3159. <dd><p>Causes the coroutine to clean itself up and exit. If the coroutine
  3160. 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>
  3161. method of the iterator that caused the coroutine to suspend, if it
  3162. 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
  3163. suspension point, causing the coroutine to immediately clean itself up.
  3164. Finally, the coroutine is marked as having finished executing, even if
  3165. it was never started.</p>
  3166. <p>Coroutine objects are automatically closed using the above process when
  3167. they are about to be destroyed.</p>
  3168. </dd></dl>
  3169. </section>
  3170. <section id="asynchronous-iterators">
  3171. <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>
  3172. <p>An <em>asynchronous iterator</em> can call asynchronous code in
  3173. its <code class="docutils literal notranslate"><span class="pre">__anext__</span></code> method.</p>
  3174. <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>
  3175. <dl class="py method">
  3176. <dt class="sig sig-object py" id="object.__aiter__">
  3177. <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>
  3178. <dd><p>Must return an <em>asynchronous iterator</em> object.</p>
  3179. </dd></dl>
  3180. <dl class="py method">
  3181. <dt class="sig sig-object py" id="object.__anext__">
  3182. <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>
  3183. <dd><p>Must return an <em>awaitable</em> resulting in a next value of the iterator. Should
  3184. 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>
  3185. </dd></dl>
  3186. <p>An example of an asynchronous iterable object:</p>
  3187. <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>
  3188. <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>
  3189. <span class="o">...</span>
  3190. <span class="k">def</span> <span class="fm">__aiter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  3191. <span class="k">return</span> <span class="bp">self</span>
  3192. <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>
  3193. <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>
  3194. <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>
  3195. <span class="k">raise</span> <span class="ne">StopAsyncIteration</span>
  3196. <span class="k">return</span> <span class="n">val</span>
  3197. </pre></div>
  3198. </div>
  3199. <div class="versionadded">
  3200. <p><span class="versionmodified added">New in version 3.5.</span></p>
  3201. </div>
  3202. <div class="versionchanged">
  3203. <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>
  3204. that would resolve to an
  3205. <a class="reference internal" href="../glossary.html#term-asynchronous-iterator"><span class="xref std std-term">asynchronous iterator</span></a>.</p>
  3206. <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
  3207. asynchronous iterator object. Returning anything else
  3208. 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>
  3209. </div>
  3210. </section>
  3211. <section id="asynchronous-context-managers">
  3212. <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>
  3213. <p>An <em>asynchronous context manager</em> is a <em>context manager</em> that is able to
  3214. 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>
  3215. <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>
  3216. <dl class="py method">
  3217. <dt class="sig sig-object py" id="object.__aenter__">
  3218. <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>
  3219. <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
  3220. difference being that it must return an <em>awaitable</em>.</p>
  3221. </dd></dl>
  3222. <dl class="py method">
  3223. <dt class="sig sig-object py" id="object.__aexit__">
  3224. <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>
  3225. <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
  3226. difference being that it must return an <em>awaitable</em>.</p>
  3227. </dd></dl>
  3228. <p>An example of an asynchronous context manager class:</p>
  3229. <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>
  3230. <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>
  3231. <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>
  3232. <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>
  3233. <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>
  3234. </pre></div>
  3235. </div>
  3236. <div class="versionadded">
  3237. <p><span class="versionmodified added">New in version 3.5.</span></p>
  3238. </div>
  3239. <p class="rubric">Footnotes</p>
  3240. <aside class="footnote-list brackets">
  3241. <aside class="footnote brackets" id="id17" role="doc-footnote">
  3242. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id1">1</a><span class="fn-bracket">]</span></span>
  3243. <p>It <em>is</em> possible in some cases to change an object’s type, under certain
  3244. controlled conditions. It generally isn’t a good idea though, since it can
  3245. lead to some very strange behaviour if it is handled incorrectly.</p>
  3246. </aside>
  3247. <aside class="footnote brackets" id="id18" role="doc-footnote">
  3248. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id10">2</a><span class="fn-bracket">]</span></span>
  3249. <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>,
  3250. <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>, and <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> methods have
  3251. special handling for this; others
  3252. 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
  3253. the behavior that <code class="docutils literal notranslate"><span class="pre">None</span></code> is not callable.</p>
  3254. </aside>
  3255. <aside class="footnote brackets" id="id19" role="doc-footnote">
  3256. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id14">3</a><span class="fn-bracket">]</span></span>
  3257. <p>“Does not support” here means that the class has no such method, or
  3258. 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
  3259. <code class="docutils literal notranslate"><span class="pre">None</span></code> if you want to force fallback to the right operand’s reflected
  3260. method—that will instead have the opposite effect of explicitly
  3261. <em>blocking</em> such fallback.</p>
  3262. </aside>
  3263. <aside class="footnote brackets" id="id20" role="doc-footnote">
  3264. <span class="label"><span class="fn-bracket">[</span><a role="doc-backlink" href="#id15">4</a><span class="fn-bracket">]</span></span>
  3265. <p>For operands of the same type, it is assumed that if the non-reflected
  3266. 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
  3267. operation is not
  3268. supported, which is why the reflected method is not called.</p>
  3269. </aside>
  3270. </aside>
  3271. </section>
  3272. </section>
  3273. </section>
  3274. <div class="clearer"></div>
  3275. </div>
  3276. </div>
  3277. </div>
  3278. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  3279. <div class="sphinxsidebarwrapper">
  3280. <div>
  3281. <h3><a href="../contents.html">Table of Contents</a></h3>
  3282. <ul>
  3283. <li><a class="reference internal" href="#">3. Data model</a><ul>
  3284. <li><a class="reference internal" href="#objects-values-and-types">3.1. Objects, values and types</a></li>
  3285. <li><a class="reference internal" href="#the-standard-type-hierarchy">3.2. The standard type hierarchy</a><ul>
  3286. <li><a class="reference internal" href="#none">3.2.1. None</a></li>
  3287. <li><a class="reference internal" href="#notimplemented">3.2.2. NotImplemented</a></li>
  3288. <li><a class="reference internal" href="#ellipsis">3.2.3. Ellipsis</a></li>
  3289. <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>
  3290. <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>
  3291. <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>
  3292. <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>
  3293. </ul>
  3294. </li>
  3295. <li><a class="reference internal" href="#sequences">3.2.5. Sequences</a><ul>
  3296. <li><a class="reference internal" href="#immutable-sequences">3.2.5.1. Immutable sequences</a></li>
  3297. <li><a class="reference internal" href="#mutable-sequences">3.2.5.2. Mutable sequences</a></li>
  3298. </ul>
  3299. </li>
  3300. <li><a class="reference internal" href="#set-types">3.2.6. Set types</a></li>
  3301. <li><a class="reference internal" href="#mappings">3.2.7. Mappings</a><ul>
  3302. <li><a class="reference internal" href="#dictionaries">3.2.7.1. Dictionaries</a></li>
  3303. </ul>
  3304. </li>
  3305. <li><a class="reference internal" href="#callable-types">3.2.8. Callable types</a><ul>
  3306. <li><a class="reference internal" href="#user-defined-functions">3.2.8.1. User-defined functions</a><ul>
  3307. <li><a class="reference internal" href="#special-read-only-attributes">3.2.8.1.1. Special read-only attributes</a></li>
  3308. <li><a class="reference internal" href="#special-writable-attributes">3.2.8.1.2. Special writable attributes</a></li>
  3309. </ul>
  3310. </li>
  3311. <li><a class="reference internal" href="#instance-methods">3.2.8.2. Instance methods</a></li>
  3312. <li><a class="reference internal" href="#generator-functions">3.2.8.3. Generator functions</a></li>
  3313. <li><a class="reference internal" href="#coroutine-functions">3.2.8.4. Coroutine functions</a></li>
  3314. <li><a class="reference internal" href="#asynchronous-generator-functions">3.2.8.5. Asynchronous generator functions</a></li>
  3315. <li><a class="reference internal" href="#built-in-functions">3.2.8.6. Built-in functions</a></li>
  3316. <li><a class="reference internal" href="#built-in-methods">3.2.8.7. Built-in methods</a></li>
  3317. <li><a class="reference internal" href="#classes">3.2.8.8. Classes</a></li>
  3318. <li><a class="reference internal" href="#class-instances">3.2.8.9. Class Instances</a></li>
  3319. </ul>
  3320. </li>
  3321. <li><a class="reference internal" href="#modules">3.2.9. Modules</a></li>
  3322. <li><a class="reference internal" href="#custom-classes">3.2.10. Custom classes</a></li>
  3323. <li><a class="reference internal" href="#id3">3.2.11. Class instances</a></li>
  3324. <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>
  3325. <li><a class="reference internal" href="#internal-types">3.2.13. Internal types</a><ul>
  3326. <li><a class="reference internal" href="#code-objects">3.2.13.1. Code objects</a><ul>
  3327. <li><a class="reference internal" href="#index-58">3.2.13.1.1. Special read-only attributes</a></li>
  3328. <li><a class="reference internal" href="#methods-on-code-objects">3.2.13.1.2. Methods on code objects</a></li>
  3329. </ul>
  3330. </li>
  3331. <li><a class="reference internal" href="#frame-objects">3.2.13.2. Frame objects</a><ul>
  3332. <li><a class="reference internal" href="#index-64">3.2.13.2.1. Special read-only attributes</a></li>
  3333. <li><a class="reference internal" href="#index-65">3.2.13.2.2. Special writable attributes</a></li>
  3334. <li><a class="reference internal" href="#frame-object-methods">3.2.13.2.3. Frame object methods</a></li>
  3335. </ul>
  3336. </li>
  3337. <li><a class="reference internal" href="#traceback-objects">3.2.13.3. Traceback objects</a></li>
  3338. <li><a class="reference internal" href="#slice-objects">3.2.13.4. Slice objects</a></li>
  3339. <li><a class="reference internal" href="#static-method-objects">3.2.13.5. Static method objects</a></li>
  3340. <li><a class="reference internal" href="#class-method-objects">3.2.13.6. Class method objects</a></li>
  3341. </ul>
  3342. </li>
  3343. </ul>
  3344. </li>
  3345. <li><a class="reference internal" href="#special-method-names">3.3. Special method names</a><ul>
  3346. <li><a class="reference internal" href="#basic-customization">3.3.1. Basic customization</a></li>
  3347. <li><a class="reference internal" href="#customizing-attribute-access">3.3.2. Customizing attribute access</a><ul>
  3348. <li><a class="reference internal" href="#customizing-module-attribute-access">3.3.2.1. Customizing module attribute access</a></li>
  3349. <li><a class="reference internal" href="#implementing-descriptors">3.3.2.2. Implementing Descriptors</a></li>
  3350. <li><a class="reference internal" href="#invoking-descriptors">3.3.2.3. Invoking Descriptors</a></li>
  3351. <li><a class="reference internal" href="#slots">3.3.2.4. __slots__</a></li>
  3352. </ul>
  3353. </li>
  3354. <li><a class="reference internal" href="#customizing-class-creation">3.3.3. Customizing class creation</a><ul>
  3355. <li><a class="reference internal" href="#metaclasses">3.3.3.1. Metaclasses</a></li>
  3356. <li><a class="reference internal" href="#resolving-mro-entries">3.3.3.2. Resolving MRO entries</a></li>
  3357. <li><a class="reference internal" href="#determining-the-appropriate-metaclass">3.3.3.3. Determining the appropriate metaclass</a></li>
  3358. <li><a class="reference internal" href="#preparing-the-class-namespace">3.3.3.4. Preparing the class namespace</a></li>
  3359. <li><a class="reference internal" href="#executing-the-class-body">3.3.3.5. Executing the class body</a></li>
  3360. <li><a class="reference internal" href="#creating-the-class-object">3.3.3.6. Creating the class object</a></li>
  3361. <li><a class="reference internal" href="#uses-for-metaclasses">3.3.3.7. Uses for metaclasses</a></li>
  3362. </ul>
  3363. </li>
  3364. <li><a class="reference internal" href="#customizing-instance-and-subclass-checks">3.3.4. Customizing instance and subclass checks</a></li>
  3365. <li><a class="reference internal" href="#emulating-generic-types">3.3.5. Emulating generic types</a><ul>
  3366. <li><a class="reference internal" href="#the-purpose-of-class-getitem">3.3.5.1. The purpose of <em>__class_getitem__</em></a></li>
  3367. <li><a class="reference internal" href="#class-getitem-versus-getitem">3.3.5.2. <em>__class_getitem__</em> versus <em>__getitem__</em></a></li>
  3368. </ul>
  3369. </li>
  3370. <li><a class="reference internal" href="#emulating-callable-objects">3.3.6. Emulating callable objects</a></li>
  3371. <li><a class="reference internal" href="#emulating-container-types">3.3.7. Emulating container types</a></li>
  3372. <li><a class="reference internal" href="#emulating-numeric-types">3.3.8. Emulating numeric types</a></li>
  3373. <li><a class="reference internal" href="#with-statement-context-managers">3.3.9. With Statement Context Managers</a></li>
  3374. <li><a class="reference internal" href="#customizing-positional-arguments-in-class-pattern-matching">3.3.10. Customizing positional arguments in class pattern matching</a></li>
  3375. <li><a class="reference internal" href="#emulating-buffer-types">3.3.11. Emulating buffer types</a></li>
  3376. <li><a class="reference internal" href="#special-method-lookup">3.3.12. Special method lookup</a></li>
  3377. </ul>
  3378. </li>
  3379. <li><a class="reference internal" href="#coroutines">3.4. Coroutines</a><ul>
  3380. <li><a class="reference internal" href="#awaitable-objects">3.4.1. Awaitable Objects</a></li>
  3381. <li><a class="reference internal" href="#coroutine-objects">3.4.2. Coroutine Objects</a></li>
  3382. <li><a class="reference internal" href="#asynchronous-iterators">3.4.3. Asynchronous Iterators</a></li>
  3383. <li><a class="reference internal" href="#asynchronous-context-managers">3.4.4. Asynchronous Context Managers</a></li>
  3384. </ul>
  3385. </li>
  3386. </ul>
  3387. </li>
  3388. </ul>
  3389. </div>
  3390. <div>
  3391. <h4>Previous topic</h4>
  3392. <p class="topless"><a href="lexical_analysis.html"
  3393. title="previous chapter"><span class="section-number">2. </span>Lexical analysis</a></p>
  3394. </div>
  3395. <div>
  3396. <h4>Next topic</h4>
  3397. <p class="topless"><a href="executionmodel.html"
  3398. title="next chapter"><span class="section-number">4. </span>Execution model</a></p>
  3399. </div>
  3400. <div role="note" aria-label="source link">
  3401. <h3>This Page</h3>
  3402. <ul class="this-page-menu">
  3403. <li><a href="../bugs.html">Report a Bug</a></li>
  3404. <li>
  3405. <a href="https://github.com/python/cpython/blob/main/Doc/reference/datamodel.rst"
  3406. rel="nofollow">Show Source
  3407. </a>
  3408. </li>
  3409. </ul>
  3410. </div>
  3411. </div>
  3412. <div id="sidebarbutton" title="Collapse sidebar">
  3413. <span>«</span>
  3414. </div>
  3415. </div>
  3416. <div class="clearer"></div>
  3417. </div>
  3418. <div class="related" role="navigation" aria-label="related navigation">
  3419. <h3>Navigation</h3>
  3420. <ul>
  3421. <li class="right" style="margin-right: 10px">
  3422. <a href="../genindex.html" title="General Index"
  3423. >index</a></li>
  3424. <li class="right" >
  3425. <a href="../py-modindex.html" title="Python Module Index"
  3426. >modules</a> |</li>
  3427. <li class="right" >
  3428. <a href="executionmodel.html" title="4. Execution model"
  3429. >next</a> |</li>
  3430. <li class="right" >
  3431. <a href="lexical_analysis.html" title="2. Lexical analysis"
  3432. >previous</a> |</li>
  3433. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  3434. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  3435. <li class="switchers">
  3436. <div class="language_switcher_placeholder"></div>
  3437. <div class="version_switcher_placeholder"></div>
  3438. </li>
  3439. <li>
  3440. </li>
  3441. <li id="cpython-language-and-version">
  3442. <a href="../index.html">3.12.3 Documentation</a> &#187;
  3443. </li>
  3444. <li class="nav-item nav-item-1"><a href="index.html" >The Python Language Reference</a> &#187;</li>
  3445. <li class="nav-item nav-item-this"><a href=""><span class="section-number">3. </span>Data model</a></li>
  3446. <li class="right">
  3447. <div class="inline-search" role="search">
  3448. <form class="inline-search" action="../search.html" method="get">
  3449. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  3450. <input type="submit" value="Go" />
  3451. </form>
  3452. </div>
  3453. |
  3454. </li>
  3455. <li class="right">
  3456. <label class="theme-selector-label">
  3457. Theme
  3458. <select class="theme-selector" oninput="activateTheme(this.value)">
  3459. <option value="auto" selected>Auto</option>
  3460. <option value="light">Light</option>
  3461. <option value="dark">Dark</option>
  3462. </select>
  3463. </label> |</li>
  3464. </ul>
  3465. </div>
  3466. <div class="footer">
  3467. &copy;
  3468. <a href="../copyright.html">
  3469. Copyright
  3470. </a>
  3471. 2001-2024, Python Software Foundation.
  3472. <br />
  3473. This page is licensed under the Python Software Foundation License Version 2.
  3474. <br />
  3475. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  3476. <br />
  3477. See <a href="/license.html">History and License</a> for more information.<br />
  3478. <br />
  3479. The Python Software Foundation is a non-profit corporation.
  3480. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  3481. <br />
  3482. <br />
  3483. Last updated on Apr 09, 2024 (13:47 UTC).
  3484. <a href="/bugs.html">Found a bug</a>?
  3485. <br />
  3486. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  3487. </div>
  3488. </body>
  3489. </html>
上海开阖软件有限公司 沪ICP备12045867号-1