annotations.html 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="generator" content="Docutils 0.17.1: http://docutils.sourceforge.net/" />
  6. <meta property="og:title" content="Annotations Best Practices" />
  7. <meta property="og:type" content="website" />
  8. <meta property="og:url" content="https://docs.python.org/3/howto/annotations.html" />
  9. <meta property="og:site_name" content="Python documentation" />
  10. <meta property="og:description" content="author, Larry Hastings,. Abstract: This document is designed to encapsulate the best practices for working with annotations dicts. If you write Python code that examines__annotations__ on Python ob..." />
  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="author, Larry Hastings,. Abstract: This document is designed to encapsulate the best practices for working with annotations dicts. If you write Python code that examines__annotations__ on Python ob..." />
  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>Annotations Best Practices &#8212; Python 3.12.0 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">
  18. <link rel="stylesheet" type="text/css" href="../_static/pygments.css" />
  19. <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?digest=b37c26da2f7529d09fe70b41c4b2133fe4931a90" />
  20. <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css" />
  21. <script data-url_root="../" id="documentation_options" src="../_static/documentation_options.js"></script>
  22. <script src="../_static/jquery.js"></script>
  23. <script src="../_static/underscore.js"></script>
  24. <script src="../_static/doctools.js"></script>
  25. <script src="../_static/sidebar.js"></script>
  26. <link rel="search" type="application/opensearchdescription+xml"
  27. title="Search within Python 3.12.0 documentation"
  28. href="../_static/opensearch.xml"/>
  29. <link rel="author" title="About these documents" href="../about.html" />
  30. <link rel="index" title="Index" href="../genindex.html" />
  31. <link rel="search" title="Search" href="../search.html" />
  32. <link rel="copyright" title="Copyright" href="../copyright.html" />
  33. <link rel="next" title="Isolating Extension Modules" href="isolating-extensions.html" />
  34. <link rel="prev" title="Python support for the Linux perf profiler" href="perf_profiling.html" />
  35. <link rel="canonical" href="https://docs.python.org/3/howto/annotations.html" />
  36. <style>
  37. @media only screen {
  38. table.full-width-table {
  39. width: 100%;
  40. }
  41. }
  42. </style>
  43. <link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">
  44. <link rel="shortcut icon" type="image/png" href="../_static/py.svg" />
  45. <script type="text/javascript" src="../_static/copybutton.js"></script>
  46. <script type="text/javascript" src="../_static/menu.js"></script>
  47. <script type="text/javascript" src="../_static/themetoggle.js"></script>
  48. </head>
  49. <body>
  50. <div class="mobile-nav">
  51. <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"
  52. aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu" />
  53. <nav class="nav-content" role="navigation">
  54. <label for="menuToggler" class="toggler__label">
  55. <span></span>
  56. </label>
  57. <span class="nav-items-wrapper">
  58. <a href="https://www.python.org/" class="nav-logo">
  59. <img src="../_static/py.svg" alt="Logo"/>
  60. </a>
  61. <span class="version_switcher_placeholder"></span>
  62. <form role="search" class="search" action="../search.html" method="get">
  63. <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">
  64. <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
  65. </svg>
  66. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  67. <input type="submit" value="Go"/>
  68. </form>
  69. </span>
  70. </nav>
  71. <div class="menu-wrapper">
  72. <nav class="menu" role="navigation" aria-label="main navigation">
  73. <div class="language_switcher_placeholder"></div>
  74. <label class="theme-selector-label">
  75. Theme
  76. <select class="theme-selector" oninput="activateTheme(this.value)">
  77. <option value="auto" selected>Auto</option>
  78. <option value="light">Light</option>
  79. <option value="dark">Dark</option>
  80. </select>
  81. </label>
  82. <div>
  83. <h3><a href="../contents.html">Table of Contents</a></h3>
  84. <ul>
  85. <li><a class="reference internal" href="#">Annotations Best Practices</a><ul>
  86. <li><a class="reference internal" href="#accessing-the-annotations-dict-of-an-object-in-python-3-10-and-newer">Accessing The Annotations Dict Of An Object In Python 3.10 And Newer</a></li>
  87. <li><a class="reference internal" href="#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older">Accessing The Annotations Dict Of An Object In Python 3.9 And Older</a></li>
  88. <li><a class="reference internal" href="#manually-un-stringizing-stringized-annotations">Manually Un-Stringizing Stringized Annotations</a></li>
  89. <li><a class="reference internal" href="#best-practices-for-annotations-in-any-python-version">Best Practices For <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> In Any Python Version</a></li>
  90. <li><a class="reference internal" href="#annotations-quirks"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> Quirks</a></li>
  91. </ul>
  92. </li>
  93. </ul>
  94. </div>
  95. <div>
  96. <h4>Previous topic</h4>
  97. <p class="topless"><a href="perf_profiling.html"
  98. title="previous chapter">Python support for the Linux <code class="docutils literal notranslate"><span class="pre">perf</span></code> profiler</a></p>
  99. </div>
  100. <div>
  101. <h4>Next topic</h4>
  102. <p class="topless"><a href="isolating-extensions.html"
  103. title="next chapter">Isolating Extension Modules</a></p>
  104. </div>
  105. <div role="note" aria-label="source link">
  106. <h3>This Page</h3>
  107. <ul class="this-page-menu">
  108. <li><a href="../bugs.html">Report a Bug</a></li>
  109. <li>
  110. <a href="https://github.com/python/cpython/blob/main/Doc/howto/annotations.rst"
  111. rel="nofollow">Show Source
  112. </a>
  113. </li>
  114. </ul>
  115. </div>
  116. </nav>
  117. </div>
  118. </div>
  119. <div class="related" role="navigation" aria-label="related navigation">
  120. <h3>Navigation</h3>
  121. <ul>
  122. <li class="right" style="margin-right: 10px">
  123. <a href="../genindex.html" title="General Index"
  124. accesskey="I">index</a></li>
  125. <li class="right" >
  126. <a href="../py-modindex.html" title="Python Module Index"
  127. >modules</a> |</li>
  128. <li class="right" >
  129. <a href="isolating-extensions.html" title="Isolating Extension Modules"
  130. accesskey="N">next</a> |</li>
  131. <li class="right" >
  132. <a href="perf_profiling.html" title="Python support for the Linux perf profiler"
  133. accesskey="P">previous</a> |</li>
  134. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  135. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  136. <li class="switchers">
  137. <div class="language_switcher_placeholder"></div>
  138. <div class="version_switcher_placeholder"></div>
  139. </li>
  140. <li>
  141. </li>
  142. <li id="cpython-language-and-version">
  143. <a href="../index.html">3.12.0 Documentation</a> &#187;
  144. </li>
  145. <li class="nav-item nav-item-1"><a href="index.html" accesskey="U">Python HOWTOs</a> &#187;</li>
  146. <li class="nav-item nav-item-this"><a href="">Annotations Best Practices</a></li>
  147. <li class="right">
  148. <div class="inline-search" role="search">
  149. <form class="inline-search" action="../search.html" method="get">
  150. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  151. <input type="submit" value="Go" />
  152. </form>
  153. </div>
  154. |
  155. </li>
  156. <li class="right">
  157. <label class="theme-selector-label">
  158. Theme
  159. <select class="theme-selector" oninput="activateTheme(this.value)">
  160. <option value="auto" selected>Auto</option>
  161. <option value="light">Light</option>
  162. <option value="dark">Dark</option>
  163. </select>
  164. </label> |</li>
  165. </ul>
  166. </div>
  167. <div class="document">
  168. <div class="documentwrapper">
  169. <div class="bodywrapper">
  170. <div class="body" role="main">
  171. <section id="annotations-best-practices">
  172. <span id="annotations-howto"></span><h1>Annotations Best Practices<a class="headerlink" href="#annotations-best-practices" title="Permalink to this headline">¶</a></h1>
  173. <dl class="field-list simple">
  174. <dt class="field-odd">author</dt>
  175. <dd class="field-odd"><p>Larry Hastings</p>
  176. </dd>
  177. </dl>
  178. <div class="topic">
  179. <p class="topic-title">Abstract</p>
  180. <p>This document is designed to encapsulate the best practices
  181. for working with annotations dicts. If you write Python code
  182. that examines <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> on Python objects, we
  183. encourage you to follow the guidelines described below.</p>
  184. <p>The document is organized into four sections:
  185. best practices for accessing the annotations of an object
  186. in Python versions 3.10 and newer,
  187. best practices for accessing the annotations of an object
  188. in Python versions 3.9 and older,
  189. other best practices
  190. for <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> that apply to any Python version,
  191. and
  192. quirks of <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>.</p>
  193. <p>Note that this document is specifically about working with
  194. <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>, not uses <em>for</em> annotations.
  195. If you’re looking for information on how to use “type hints”
  196. in your code, please see the <a class="reference internal" href="../library/typing.html#module-typing" title="typing: Support for type hints (see :pep:`484`)."><code class="xref py py-mod docutils literal notranslate"><span class="pre">typing</span></code></a> module.</p>
  197. </div>
  198. <section id="accessing-the-annotations-dict-of-an-object-in-python-3-10-and-newer">
  199. <h2>Accessing The Annotations Dict Of An Object In Python 3.10 And Newer<a class="headerlink" href="#accessing-the-annotations-dict-of-an-object-in-python-3-10-and-newer" title="Permalink to this headline">¶</a></h2>
  200. <p>Python 3.10 adds a new function to the standard library:
  201. <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a>. In Python versions 3.10
  202. and newer, calling this function is the best practice for
  203. accessing the annotations dict of any object that supports
  204. annotations. This function can also “un-stringize”
  205. stringized annotations for you.</p>
  206. <p>If for some reason <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a> isn’t
  207. viable for your use case, you may access the
  208. <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> data member manually. Best practice
  209. for this changed in Python 3.10 as well: as of Python 3.10,
  210. <code class="docutils literal notranslate"><span class="pre">o.__annotations__</span></code> is guaranteed to <em>always</em> work
  211. on Python functions, classes, and modules. If you’re
  212. certain the object you’re examining is one of these three
  213. <em>specific</em> objects, you may simply use <code class="docutils literal notranslate"><span class="pre">o.__annotations__</span></code>
  214. to get at the object’s annotations dict.</p>
  215. <p>However, other types of callables–for example,
  216. callables created by <a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>–may
  217. not have an <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute defined. When
  218. accessing the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> of a possibly unknown
  219. object, best practice in Python versions 3.10 and
  220. newer is to call <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> with three arguments,
  221. for example <code class="docutils literal notranslate"><span class="pre">getattr(o,</span> <span class="pre">'__annotations__',</span> <span class="pre">None)</span></code>.</p>
  222. <p>Before Python 3.10, accessing <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> on a class that
  223. defines no annotations but that has a parent class with
  224. annotations would return the parent’s <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>.
  225. In Python 3.10 and newer, the child class’s annotations
  226. will be an empty dict instead.</p>
  227. </section>
  228. <section id="accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older">
  229. <h2>Accessing The Annotations Dict Of An Object In Python 3.9 And Older<a class="headerlink" href="#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older" title="Permalink to this headline">¶</a></h2>
  230. <p>In Python 3.9 and older, accessing the annotations dict
  231. of an object is much more complicated than in newer versions.
  232. The problem is a design flaw in these older versions of Python,
  233. specifically to do with class annotations.</p>
  234. <p>Best practice for accessing the annotations dict of other
  235. objects–functions, other callables, and modules–is the same
  236. as best practice for 3.10, assuming you aren’t calling
  237. <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a>: you should use three-argument
  238. <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> to access the object’s <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>
  239. attribute.</p>
  240. <p>Unfortunately, this isn’t best practice for classes. The problem
  241. is that, since <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> is optional on classes, and
  242. because classes can inherit attributes from their base classes,
  243. accessing the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute of a class may
  244. inadvertently return the annotations dict of a <em>base class.</em>
  245. As an example:</p>
  246. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">Base</span><span class="p">:</span>
  247. <span class="n">a</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">3</span>
  248. <span class="n">b</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">&#39;abc&#39;</span>
  249. <span class="k">class</span> <span class="nc">Derived</span><span class="p">(</span><span class="n">Base</span><span class="p">):</span>
  250. <span class="k">pass</span>
  251. <span class="nb">print</span><span class="p">(</span><span class="n">Derived</span><span class="o">.</span><span class="vm">__annotations__</span><span class="p">)</span>
  252. </pre></div>
  253. </div>
  254. <p>This will print the annotations dict from <code class="docutils literal notranslate"><span class="pre">Base</span></code>, not
  255. <code class="docutils literal notranslate"><span class="pre">Derived</span></code>.</p>
  256. <p>Your code will have to have a separate code path if the object
  257. you’re examining is a class (<code class="docutils literal notranslate"><span class="pre">isinstance(o,</span> <span class="pre">type)</span></code>).
  258. In that case, best practice relies on an implementation detail
  259. of Python 3.9 and before: if a class has annotations defined,
  260. they are stored in the class’s <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> dictionary. Since
  261. the class may or may not have annotations defined, best practice
  262. is to call the <code class="docutils literal notranslate"><span class="pre">get</span></code> method on the class dict.</p>
  263. <p>To put it all together, here is some sample code that safely
  264. accesses the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute on an arbitrary
  265. object in Python 3.9 and before:</p>
  266. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">if</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="nb">type</span><span class="p">):</span>
  267. <span class="n">ann</span> <span class="o">=</span> <span class="n">o</span><span class="o">.</span><span class="vm">__dict__</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s1">&#39;__annotations__&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
  268. <span class="k">else</span><span class="p">:</span>
  269. <span class="n">ann</span> <span class="o">=</span> <span class="nb">getattr</span><span class="p">(</span><span class="n">o</span><span class="p">,</span> <span class="s1">&#39;__annotations__&#39;</span><span class="p">,</span> <span class="kc">None</span><span class="p">)</span>
  270. </pre></div>
  271. </div>
  272. <p>After running this code, <code class="docutils literal notranslate"><span class="pre">ann</span></code> should be either a
  273. dictionary or <code class="docutils literal notranslate"><span class="pre">None</span></code>. You’re encouraged to double-check
  274. the type of <code class="docutils literal notranslate"><span class="pre">ann</span></code> using <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> before further
  275. examination.</p>
  276. <p>Note that some exotic or malformed type objects may not have
  277. a <code class="docutils literal notranslate"><span class="pre">__dict__</span></code> attribute, so for extra safety you may also wish
  278. to use <a class="reference internal" href="../library/functions.html#getattr" title="getattr"><code class="xref py py-func docutils literal notranslate"><span class="pre">getattr()</span></code></a> to access <code class="docutils literal notranslate"><span class="pre">__dict__</span></code>.</p>
  279. </section>
  280. <section id="manually-un-stringizing-stringized-annotations">
  281. <h2>Manually Un-Stringizing Stringized Annotations<a class="headerlink" href="#manually-un-stringizing-stringized-annotations" title="Permalink to this headline">¶</a></h2>
  282. <p>In situations where some annotations may be “stringized”,
  283. and you wish to evaluate those strings to produce the
  284. Python values they represent, it really is best to
  285. call <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a> to do this work
  286. for you.</p>
  287. <p>If you’re using Python 3.9 or older, or if for some reason
  288. you can’t use <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a>, you’ll need
  289. to duplicate its logic. You’re encouraged to examine the
  290. implementation of <a class="reference internal" href="../library/inspect.html#inspect.get_annotations" title="inspect.get_annotations"><code class="xref py py-func docutils literal notranslate"><span class="pre">inspect.get_annotations()</span></code></a> in the
  291. current Python version and follow a similar approach.</p>
  292. <p>In a nutshell, if you wish to evaluate a stringized annotation
  293. on an arbitrary object <code class="docutils literal notranslate"><span class="pre">o</span></code>:</p>
  294. <ul class="simple">
  295. <li><p>If <code class="docutils literal notranslate"><span class="pre">o</span></code> is a module, use <code class="docutils literal notranslate"><span class="pre">o.__dict__</span></code> as the
  296. <code class="docutils literal notranslate"><span class="pre">globals</span></code> when calling <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.</p></li>
  297. <li><p>If <code class="docutils literal notranslate"><span class="pre">o</span></code> is a class, use <code class="docutils literal notranslate"><span class="pre">sys.modules[o.__module__].__dict__</span></code>
  298. as the <code class="docutils literal notranslate"><span class="pre">globals</span></code>, and <code class="docutils literal notranslate"><span class="pre">dict(vars(o))</span></code> as the <code class="docutils literal notranslate"><span class="pre">locals</span></code>,
  299. when calling <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.</p></li>
  300. <li><p>If <code class="docutils literal notranslate"><span class="pre">o</span></code> is a wrapped callable using <a class="reference internal" href="../library/functools.html#functools.update_wrapper" title="functools.update_wrapper"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.update_wrapper()</span></code></a>,
  301. <a class="reference internal" href="../library/functools.html#functools.wraps" title="functools.wraps"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.wraps()</span></code></a>, or <a class="reference internal" href="../library/functools.html#functools.partial" title="functools.partial"><code class="xref py py-func docutils literal notranslate"><span class="pre">functools.partial()</span></code></a>, iteratively
  302. unwrap it by accessing either <code class="docutils literal notranslate"><span class="pre">o.__wrapped__</span></code> or <code class="docutils literal notranslate"><span class="pre">o.func</span></code> as
  303. appropriate, until you have found the root unwrapped function.</p></li>
  304. <li><p>If <code class="docutils literal notranslate"><span class="pre">o</span></code> is a callable (but not a class), use
  305. <code class="docutils literal notranslate"><span class="pre">o.__globals__</span></code> as the globals when calling <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.</p></li>
  306. </ul>
  307. <p>However, not all string values used as annotations can
  308. be successfully turned into Python values by <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a>.
  309. String values could theoretically contain any valid string,
  310. and in practice there are valid use cases for type hints that
  311. require annotating with string values that specifically
  312. <em>can’t</em> be evaluated. For example:</p>
  313. <ul class="simple">
  314. <li><p><span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0604/"><strong>PEP 604</strong></a> union types using <code class="docutils literal notranslate"><span class="pre">|</span></code>, before support for this
  315. was added to Python 3.10.</p></li>
  316. <li><p>Definitions that aren’t needed at runtime, only imported
  317. when <a class="reference internal" href="../library/typing.html#typing.TYPE_CHECKING" title="typing.TYPE_CHECKING"><code class="xref py py-const docutils literal notranslate"><span class="pre">typing.TYPE_CHECKING</span></code></a> is true.</p></li>
  318. </ul>
  319. <p>If <a class="reference internal" href="../library/functions.html#eval" title="eval"><code class="xref py py-func docutils literal notranslate"><span class="pre">eval()</span></code></a> attempts to evaluate such values, it will
  320. fail and raise an exception. So, when designing a library
  321. API that works with annotations, it’s recommended to only
  322. attempt to evaluate string values when explicitly requested
  323. to by the caller.</p>
  324. </section>
  325. <section id="best-practices-for-annotations-in-any-python-version">
  326. <h2>Best Practices For <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> In Any Python Version<a class="headerlink" href="#best-practices-for-annotations-in-any-python-version" title="Permalink to this headline">¶</a></h2>
  327. <ul class="simple">
  328. <li><p>You should avoid assigning to the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  329. of objects directly. Let Python manage setting <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>.</p></li>
  330. <li><p>If you do assign directly to the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  331. of an object, you should always set it to a <code class="docutils literal notranslate"><span class="pre">dict</span></code> object.</p></li>
  332. <li><p>If you directly access the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  333. of an object, you should ensure that it’s a
  334. dictionary before attempting to examine its contents.</p></li>
  335. <li><p>You should avoid modifying <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> dicts.</p></li>
  336. <li><p>You should avoid deleting the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute
  337. of an object.</p></li>
  338. </ul>
  339. </section>
  340. <section id="annotations-quirks">
  341. <h2><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> Quirks<a class="headerlink" href="#annotations-quirks" title="Permalink to this headline">¶</a></h2>
  342. <p>In all versions of Python 3, function
  343. objects lazy-create an annotations dict if no annotations
  344. are defined on that object. You can delete the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>
  345. attribute using <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">fn.__annotations__</span></code>, but if you then
  346. access <code class="docutils literal notranslate"><span class="pre">fn.__annotations__</span></code> the object will create a new empty dict
  347. that it will store and return as its annotations. Deleting the
  348. annotations on a function before it has lazily created its annotations
  349. dict will throw an <code class="docutils literal notranslate"><span class="pre">AttributeError</span></code>; using <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">fn.__annotations__</span></code>
  350. twice in a row is guaranteed to always throw an <code class="docutils literal notranslate"><span class="pre">AttributeError</span></code>.</p>
  351. <p>Everything in the above paragraph also applies to class and module
  352. objects in Python 3.10 and newer.</p>
  353. <p>In all versions of Python 3, you can set <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>
  354. on a function object to <code class="docutils literal notranslate"><span class="pre">None</span></code>. However, subsequently
  355. accessing the annotations on that object using <code class="docutils literal notranslate"><span class="pre">fn.__annotations__</span></code>
  356. will lazy-create an empty dictionary as per the first paragraph of
  357. this section. This is <em>not</em> true of modules and classes, in any Python
  358. version; those objects permit setting <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> to any
  359. Python value, and will retain whatever value is set.</p>
  360. <p>If Python stringizes your annotations for you
  361. (using <code class="docutils literal notranslate"><span class="pre">from</span> <span class="pre">__future__</span> <span class="pre">import</span> <span class="pre">annotations</span></code>), and you
  362. specify a string as an annotation, the string will
  363. itself be quoted. In effect the annotation is quoted
  364. <em>twice.</em> For example:</p>
  365. <div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="kn">import</span> <span class="n">annotations</span>
  366. <span class="k">def</span> <span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">:</span> <span class="s2">&quot;str&quot;</span><span class="p">):</span> <span class="k">pass</span>
  367. <span class="nb">print</span><span class="p">(</span><span class="n">foo</span><span class="o">.</span><span class="vm">__annotations__</span><span class="p">)</span>
  368. </pre></div>
  369. </div>
  370. <p>This prints <code class="docutils literal notranslate"><span class="pre">{'a':</span> <span class="pre">&quot;'str'&quot;}</span></code>. This shouldn’t really be considered
  371. a “quirk”; it’s mentioned here simply because it might be surprising.</p>
  372. </section>
  373. </section>
  374. <div class="clearer"></div>
  375. </div>
  376. </div>
  377. </div>
  378. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  379. <div class="sphinxsidebarwrapper">
  380. <div>
  381. <h3><a href="../contents.html">Table of Contents</a></h3>
  382. <ul>
  383. <li><a class="reference internal" href="#">Annotations Best Practices</a><ul>
  384. <li><a class="reference internal" href="#accessing-the-annotations-dict-of-an-object-in-python-3-10-and-newer">Accessing The Annotations Dict Of An Object In Python 3.10 And Newer</a></li>
  385. <li><a class="reference internal" href="#accessing-the-annotations-dict-of-an-object-in-python-3-9-and-older">Accessing The Annotations Dict Of An Object In Python 3.9 And Older</a></li>
  386. <li><a class="reference internal" href="#manually-un-stringizing-stringized-annotations">Manually Un-Stringizing Stringized Annotations</a></li>
  387. <li><a class="reference internal" href="#best-practices-for-annotations-in-any-python-version">Best Practices For <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> In Any Python Version</a></li>
  388. <li><a class="reference internal" href="#annotations-quirks"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> Quirks</a></li>
  389. </ul>
  390. </li>
  391. </ul>
  392. </div>
  393. <div>
  394. <h4>Previous topic</h4>
  395. <p class="topless"><a href="perf_profiling.html"
  396. title="previous chapter">Python support for the Linux <code class="docutils literal notranslate"><span class="pre">perf</span></code> profiler</a></p>
  397. </div>
  398. <div>
  399. <h4>Next topic</h4>
  400. <p class="topless"><a href="isolating-extensions.html"
  401. title="next chapter">Isolating Extension Modules</a></p>
  402. </div>
  403. <div role="note" aria-label="source link">
  404. <h3>This Page</h3>
  405. <ul class="this-page-menu">
  406. <li><a href="../bugs.html">Report a Bug</a></li>
  407. <li>
  408. <a href="https://github.com/python/cpython/blob/main/Doc/howto/annotations.rst"
  409. rel="nofollow">Show Source
  410. </a>
  411. </li>
  412. </ul>
  413. </div>
  414. </div>
  415. </div>
  416. <div class="clearer"></div>
  417. </div>
  418. <div class="related" role="navigation" aria-label="related navigation">
  419. <h3>Navigation</h3>
  420. <ul>
  421. <li class="right" style="margin-right: 10px">
  422. <a href="../genindex.html" title="General Index"
  423. >index</a></li>
  424. <li class="right" >
  425. <a href="../py-modindex.html" title="Python Module Index"
  426. >modules</a> |</li>
  427. <li class="right" >
  428. <a href="isolating-extensions.html" title="Isolating Extension Modules"
  429. >next</a> |</li>
  430. <li class="right" >
  431. <a href="perf_profiling.html" title="Python support for the Linux perf profiler"
  432. >previous</a> |</li>
  433. <li><img src="../_static/py.svg" alt="python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  434. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  435. <li class="switchers">
  436. <div class="language_switcher_placeholder"></div>
  437. <div class="version_switcher_placeholder"></div>
  438. </li>
  439. <li>
  440. </li>
  441. <li id="cpython-language-and-version">
  442. <a href="../index.html">3.12.0 Documentation</a> &#187;
  443. </li>
  444. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  445. <li class="nav-item nav-item-this"><a href="">Annotations Best Practices</a></li>
  446. <li class="right">
  447. <div class="inline-search" role="search">
  448. <form class="inline-search" action="../search.html" method="get">
  449. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" />
  450. <input type="submit" value="Go" />
  451. </form>
  452. </div>
  453. |
  454. </li>
  455. <li class="right">
  456. <label class="theme-selector-label">
  457. Theme
  458. <select class="theme-selector" oninput="activateTheme(this.value)">
  459. <option value="auto" selected>Auto</option>
  460. <option value="light">Light</option>
  461. <option value="dark">Dark</option>
  462. </select>
  463. </label> |</li>
  464. </ul>
  465. </div>
  466. <div class="footer">
  467. &copy; <a href="../copyright.html">Copyright</a> 2001-2023, Python Software Foundation.
  468. <br />
  469. This page is licensed under the Python Software Foundation License Version 2.
  470. <br />
  471. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  472. <br />
  473. See <a href="/license.html">History and License</a> for more information.<br />
  474. <br />
  475. The Python Software Foundation is a non-profit corporation.
  476. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  477. <br />
  478. <br />
  479. Last updated on Oct 02, 2023.
  480. <a href="/bugs.html">Found a bug</a>?
  481. <br />
  482. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 4.5.0.
  483. </div>
  484. </body>
  485. </html>