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.

540 line
36KB

  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="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.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="Isolating Extension Modules" href="isolating-extensions.html" />
  33. <link rel="prev" title="Python support for the Linux perf profiler" href="perf_profiling.html" />
  34. <link rel="canonical" href="https://docs.python.org/3/howto/annotations.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="#">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.3 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" id="search-box" />
  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="Link to this heading">¶</a></h1>
  173. <dl class="field-list simple">
  174. <dt class="field-odd">author<span class="colon">:</span></dt>
  175. <dd class="field-odd"><p>Larry Hastings</p>
  176. </dd>
  177. </dl>
  178. <aside 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. </aside>
  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="Link to this heading">¶</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="Link to this heading">¶</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="Link to this heading">¶</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. <a class="reference internal" href="../reference/datamodel.html#function.__globals__" title="function.__globals__"><code class="xref py py-attr docutils literal notranslate"><span class="pre">o.__globals__</span></code></a> as the globals when calling
  306. <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>
  307. </ul>
  308. <p>However, not all string values used as annotations can
  309. 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>.
  310. String values could theoretically contain any valid string,
  311. and in practice there are valid use cases for type hints that
  312. require annotating with string values that specifically
  313. <em>can’t</em> be evaluated. For example:</p>
  314. <ul class="simple">
  315. <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
  316. was added to Python 3.10.</p></li>
  317. <li><p>Definitions that aren’t needed at runtime, only imported
  318. 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>
  319. </ul>
  320. <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
  321. fail and raise an exception. So, when designing a library
  322. API that works with annotations, it’s recommended to only
  323. attempt to evaluate string values when explicitly requested
  324. to by the caller.</p>
  325. </section>
  326. <section id="best-practices-for-annotations-in-any-python-version">
  327. <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="Link to this heading">¶</a></h2>
  328. <ul class="simple">
  329. <li><p>You should avoid assigning to the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  330. of objects directly. Let Python manage setting <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>.</p></li>
  331. <li><p>If you do assign directly to the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  332. of an object, you should always set it to a <code class="docutils literal notranslate"><span class="pre">dict</span></code> object.</p></li>
  333. <li><p>If you directly access the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> member
  334. of an object, you should ensure that it’s a
  335. dictionary before attempting to examine its contents.</p></li>
  336. <li><p>You should avoid modifying <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> dicts.</p></li>
  337. <li><p>You should avoid deleting the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> attribute
  338. of an object.</p></li>
  339. </ul>
  340. </section>
  341. <section id="annotations-quirks">
  342. <h2><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> Quirks<a class="headerlink" href="#annotations-quirks" title="Link to this heading">¶</a></h2>
  343. <p>In all versions of Python 3, function
  344. objects lazy-create an annotations dict if no annotations
  345. are defined on that object. You can delete the <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>
  346. attribute using <code class="docutils literal notranslate"><span class="pre">del</span> <span class="pre">fn.__annotations__</span></code>, but if you then
  347. access <code class="docutils literal notranslate"><span class="pre">fn.__annotations__</span></code> the object will create a new empty dict
  348. that it will store and return as its annotations. Deleting the
  349. annotations on a function before it has lazily created its annotations
  350. 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>
  351. twice in a row is guaranteed to always throw an <code class="docutils literal notranslate"><span class="pre">AttributeError</span></code>.</p>
  352. <p>Everything in the above paragraph also applies to class and module
  353. objects in Python 3.10 and newer.</p>
  354. <p>In all versions of Python 3, you can set <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code>
  355. on a function object to <code class="docutils literal notranslate"><span class="pre">None</span></code>. However, subsequently
  356. accessing the annotations on that object using <code class="docutils literal notranslate"><span class="pre">fn.__annotations__</span></code>
  357. will lazy-create an empty dictionary as per the first paragraph of
  358. this section. This is <em>not</em> true of modules and classes, in any Python
  359. version; those objects permit setting <code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> to any
  360. Python value, and will retain whatever value is set.</p>
  361. <p>If Python stringizes your annotations for you
  362. (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
  363. specify a string as an annotation, the string will
  364. itself be quoted. In effect the annotation is quoted
  365. <em>twice.</em> For example:</p>
  366. <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>
  367. <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>
  368. <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>
  369. </pre></div>
  370. </div>
  371. <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
  372. a “quirk”; it’s mentioned here simply because it might be surprising.</p>
  373. </section>
  374. </section>
  375. <div class="clearer"></div>
  376. </div>
  377. </div>
  378. </div>
  379. <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
  380. <div class="sphinxsidebarwrapper">
  381. <div>
  382. <h3><a href="../contents.html">Table of Contents</a></h3>
  383. <ul>
  384. <li><a class="reference internal" href="#">Annotations Best Practices</a><ul>
  385. <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>
  386. <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>
  387. <li><a class="reference internal" href="#manually-un-stringizing-stringized-annotations">Manually Un-Stringizing Stringized Annotations</a></li>
  388. <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>
  389. <li><a class="reference internal" href="#annotations-quirks"><code class="docutils literal notranslate"><span class="pre">__annotations__</span></code> Quirks</a></li>
  390. </ul>
  391. </li>
  392. </ul>
  393. </div>
  394. <div>
  395. <h4>Previous topic</h4>
  396. <p class="topless"><a href="perf_profiling.html"
  397. title="previous chapter">Python support for the Linux <code class="docutils literal notranslate"><span class="pre">perf</span></code> profiler</a></p>
  398. </div>
  399. <div>
  400. <h4>Next topic</h4>
  401. <p class="topless"><a href="isolating-extensions.html"
  402. title="next chapter">Isolating Extension Modules</a></p>
  403. </div>
  404. <div role="note" aria-label="source link">
  405. <h3>This Page</h3>
  406. <ul class="this-page-menu">
  407. <li><a href="../bugs.html">Report a Bug</a></li>
  408. <li>
  409. <a href="https://github.com/python/cpython/blob/main/Doc/howto/annotations.rst"
  410. rel="nofollow">Show Source
  411. </a>
  412. </li>
  413. </ul>
  414. </div>
  415. </div>
  416. <div id="sidebarbutton" title="Collapse sidebar">
  417. <span>«</span>
  418. </div>
  419. </div>
  420. <div class="clearer"></div>
  421. </div>
  422. <div class="related" role="navigation" aria-label="related navigation">
  423. <h3>Navigation</h3>
  424. <ul>
  425. <li class="right" style="margin-right: 10px">
  426. <a href="../genindex.html" title="General Index"
  427. >index</a></li>
  428. <li class="right" >
  429. <a href="../py-modindex.html" title="Python Module Index"
  430. >modules</a> |</li>
  431. <li class="right" >
  432. <a href="isolating-extensions.html" title="Isolating Extension Modules"
  433. >next</a> |</li>
  434. <li class="right" >
  435. <a href="perf_profiling.html" title="Python support for the Linux perf profiler"
  436. >previous</a> |</li>
  437. <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"/></li>
  438. <li><a href="https://www.python.org/">Python</a> &#187;</li>
  439. <li class="switchers">
  440. <div class="language_switcher_placeholder"></div>
  441. <div class="version_switcher_placeholder"></div>
  442. </li>
  443. <li>
  444. </li>
  445. <li id="cpython-language-and-version">
  446. <a href="../index.html">3.12.3 Documentation</a> &#187;
  447. </li>
  448. <li class="nav-item nav-item-1"><a href="index.html" >Python HOWTOs</a> &#187;</li>
  449. <li class="nav-item nav-item-this"><a href="">Annotations Best Practices</a></li>
  450. <li class="right">
  451. <div class="inline-search" role="search">
  452. <form class="inline-search" action="../search.html" method="get">
  453. <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box" />
  454. <input type="submit" value="Go" />
  455. </form>
  456. </div>
  457. |
  458. </li>
  459. <li class="right">
  460. <label class="theme-selector-label">
  461. Theme
  462. <select class="theme-selector" oninput="activateTheme(this.value)">
  463. <option value="auto" selected>Auto</option>
  464. <option value="light">Light</option>
  465. <option value="dark">Dark</option>
  466. </select>
  467. </label> |</li>
  468. </ul>
  469. </div>
  470. <div class="footer">
  471. &copy;
  472. <a href="../copyright.html">
  473. Copyright
  474. </a>
  475. 2001-2024, Python Software Foundation.
  476. <br />
  477. This page is licensed under the Python Software Foundation License Version 2.
  478. <br />
  479. Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.
  480. <br />
  481. See <a href="/license.html">History and License</a> for more information.<br />
  482. <br />
  483. The Python Software Foundation is a non-profit corporation.
  484. <a href="https://www.python.org/psf/donations/">Please donate.</a>
  485. <br />
  486. <br />
  487. Last updated on Apr 09, 2024 (13:47 UTC).
  488. <a href="/bugs.html">Found a bug</a>?
  489. <br />
  490. Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 7.2.6.
  491. </div>
  492. </body>
  493. </html>
上海开阖软件有限公司 沪ICP备12045867号-1