A place to cache linked articles (think custom and personal wayback machine)
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.

index.md 37KB

4 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  1. title: API Evolution the Right Way
  2. url: https://emptysqua.re/blog/api-evolution-the-right-way/
  3. hash_url: f064de13a0e15573a8051034d081f3c8
  4. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/dragon.jpg" alt=""/></p>
  5. <p>Imagine you are a creator deity, designing a body for a creature. In your benevelonce, you wish for the creature to evolve over time: first, because it must respond to changes in its environment, and second, because your wisdom grows and you think of better designs for the beast. It shouldn’t remain in the same body forever!</p>
  6. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/praise-the-creator.jpg" alt=""/></p>
  7. <p>The creature, however, might be relying on features of its present anatomy. You can’t add wings or change its scales without warning. It needs an orderly process to adapt its lifestyle to its new body. How can you, as a responsible designer in charge of this creature’s natural history, gently coax it toward ever greater improvements?</p>
  8. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/creator.jpg" alt=""/></p>
  9. <p>It’s the same for responsible library maintainers. We keep our promises to the people who depend on our code: we release bugfixes and useful new features. We sometimes delete features if that’s beneficial for the library’s future. We continue to innovate, but we don’t break the code of people who use our library. How can we fulfill all those goals at once?</p>
  10. <h1 id="add-useful-features">Add Useful Features</h1>
  11. <p>Your library shouldn’t stay the same for eternity: you should add features that your make your library better for your users.
  12. For example, if you have a Reptile class and it would be useful to have wings for flying, go for it.</p>
  13. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>class</span> <span>Reptile</span>:
  14. <span>@property</span>
  15. <span>def</span> <span>teeth</span>(<span>self</span>):
  16. <span>return</span> <span>'sharp fangs'</span>
  17. <span> <span># If wings are useful, add them!</span>
  18. </span><span> <span>@property</span>
  19. </span><span> <span>def</span> <span>wings</span>(<span>self</span>):
  20. </span><span> <span>return</span> <span>'majestic wings'</span>
  21. </span></code></pre></div>
  22. <p>But beware, features come with risk.
  23. Consider the following feature in the Python standard library, and let us see what went wrong with it.</p>
  24. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>bool</span>(datetime<span>.</span>time(<span>9</span>, <span>30</span>)) <span>==</span> <span>True</span>
  25. <span>bool</span>(datetime<span>.</span>time(<span>0</span>, <span>0</span>)) <span>==</span> <span>False</span>
  26. </code></pre></div>
  27. <p>This is peculiar: converting any time object to a boolean yields True, except for midnight. (Worse, the rules for timezone-aware times are even stranger.)
  28. I’ve been writing Python for more than a decade but I didn’t discover this rule until last week. What kind of bugs can this odd behavior cause in users’ code?</p>
  29. <p>Consider a calendar application with a function that creates events. If an event has an end time, the function requires it to also have a start time:</p>
  30. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>def</span> <span>create_event</span>(day,
  31. start_time<span>=</span><span>None</span>,
  32. end_time<span>=</span><span>None</span>):
  33. <span>if</span> end_time <span>and</span> <span>not</span> start_time:
  34. <span>raise</span> <span>ValueError</span>(<span>"Can't pass end_time without start_time"</span>)
  35. <span># The coven meets from midnight until 4am.</span>
  36. create_event(datetime<span>.</span>date<span>.</span>today(),
  37. datetime<span>.</span>time(<span>0</span>, <span>0</span>),
  38. datetime<span>.</span>time(<span>4</span>, <span>0</span>))
  39. </code></pre></div>
  40. <p>Unfortunately for witches, an event starting at midnight fails this validation. A careful programmer who knows about the quirk at midnight can write this function correctly, of course:</p>
  41. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>def</span> <span>create_event</span>(day,
  42. start_time<span>=</span><span>None</span>,
  43. end_time<span>=</span><span>None</span>):
  44. <span>if</span> end_time <span>is</span> <span>not</span> <span>None</span> <span>and</span> start_time <span>is</span> <span>None</span>:
  45. <span>raise</span> <span>ValueError</span>(<span>"Can't pass end_time without start_time"</span>)
  46. </code></pre></div>
  47. <p>But this subtlety is worrisome. If a library creator wanted to make an API that bites users, a “feature” like the boolean conversion of midnight works nicely.</p>
  48. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/bite.jpg" alt=""/></p>
  49. <p>The responsible creator’s goal, however, is to make your library easy to use correctly.</p>
  50. <p>This feature was written by Tim Peters when he first made the datetime module in 2002. Even founding Pythonistas like Tim make mistakes. <a href="https://bugs.python.org/issue13936">The quirk was removed</a>, and all times are True now.</p>
  51. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Python 3.5 and later.</span>
  52. <span>bool</span>(datetime<span>.</span>time(<span>9</span>, <span>30</span>)) <span>==</span> <span>True</span>
  53. <span>bool</span>(datetime<span>.</span>time(<span>0</span>, <span>0</span>)) <span>==</span> <span>True</span>
  54. </code></pre></div>
  55. <p>Programmers who didn’t know about the oddity of midnight are saved from obscure bugs, but it makes me nervous to think about any code that actually relies on the weird old behavior and didn’t notice the change. It would have been better if this bad feature were never implemented at all. This leads us to the first promise of any library maintainer:</p>
  56. <div><p>
  57. First Covenant:<br/>Avoid Bad Features
  58. </p></div>
  59. <p>The most painful change to make is when you have to delete a feature. One way to avoid bad features is to add few features in general! Make no public method, class, function, or property without a good reason. Thus:</p>
  60. <div><p>
  61. Second Covenant:<br/>Minimize Features
  62. </p></div>
  63. <p>Features are like children: conceived in a moment of passion, they must be supported for years.
  64. Don’t do anything silly just because you can. Don’t add feathers to a snake!</p>
  65. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/feathers.jpg" alt=""/></p>
  66. <p>But of course, there are plenty of occasions when users need something from your library that it does not yet offer. How do you choose the right feature to give them? Here’s another cautionary tale.</p>
  67. <h1 id="a-cautionary-tale-from-asyncio">A Cautionary Tale From asyncio</h1>
  68. <p>As you may know, when you call a coroutine function, it returns a coroutine object:</p>
  69. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>async</span> <span>def</span> <span>my_coroutine</span>():
  70. <span>pass</span>
  71. <span>print</span>(my_coroutine())
  72. </code></pre></div>
  73. <div class="highlight"><pre><code class="language-text" data-lang="text"><span/>&amp;lt;coroutine object my_coroutine at 0x10bfcbac8&amp;gt;
  74. </code></pre></div>
  75. <p>Your code must “await” this object to actually run the coroutine. It’s easy to forget this, so the asyncio developers wanted a “debug mode” that catches this mistake. Whenever a coroutine is destroyed without being awaited, the debug mode prints a warning with a traceback to the line where it was created.</p>
  76. <p>When Yury Selivanov implemented the debug mode, he added as its foundation a “coroutine wrapper” feature. The wrapper is a function that takes in a coroutine and returns anything at all. Yury used it to install the warning logic on each coroutine, but someone else could use it to turn coroutines into the string “hi!”:</p>
  77. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>import</span> <span>sys</span>
  78. <span>def</span> <span>my_wrapper</span>(coro):
  79. <span>return</span> <span>'hi!'</span>
  80. sys<span>.</span>set_coroutine_wrapper(my_wrapper)
  81. <span>async</span> <span>def</span> <span>my_coroutine</span>():
  82. <span>pass</span>
  83. <span>print</span>(my_coroutine())
  84. </code></pre></div>
  85. <p>That is one hell of a customization. It changes the very meaning of “async”. Calling set_coroutine_wrapper once will globally and permanently change all coroutine functions.
  86. It is, as Nathaniel Smith wrote, “a problematic API” which is prone to misuse and had to be removed. The asyncio developers could have avoided the pain of deleting the feature if they’d better shaped it to its purpose. Responsible creators must keep this in mind:</p>
  87. <div><p>
  88. Third Covenant:<br/>Keep Features Narrow
  89. </p></div>
  90. <p>Luckily, Yury had the good judgment to mark this feature provisional, so asyncio users knew not to rely on it. Nathaniel was free to replace set_coroutine_wrapper with a narrower feature that only customized the traceback depth:</p>
  91. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>import</span> <span>sys</span>
  92. sys<span>.</span>set_coroutine_origin_tracking_depth(<span>2</span>)
  93. <span>async</span> <span>def</span> <span>my_coroutine</span>():
  94. <span>pass</span>
  95. <span>print</span>(my_coroutine())
  96. </code></pre></div>
  97. <div class="highlight"><pre><code class="language-text" data-lang="text"><span/>&lt;coroutine object my_coroutine at 0x10bfcbac8&gt;
  98. RuntimeWarning:'my_coroutine' was never awaited
  99. Coroutine created at (most recent call last)
  100. File "script.py", line 8, in &lt;module&gt;
  101. print(my_coroutine())
  102. </code></pre></div>
  103. <p>This is much better. There’s no more global setting that can change coroutines’ type, so asyncio users need not code as defensively. Deities should all be as farsighted as Yury:</p>
  104. <div><p>
  105. Fourth Covenant:<br/>Mark Experimental Features "Provisional"
  106. </p></div>
  107. <p>If you have merely a hunch that your creature wants horns and a quadruple-forked tongue, introduce the features but mark them “provisional”.</p>
  108. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/horns.jpg" alt=""/></p>
  109. <p>You might discover that the horns are adventitious but the quadruple-forked tongue is useful after all. In the next release of your library you can delete the former and mark the latter official.</p>
  110. <h1 id="deleting-features">Deleting Features</h1>
  111. <p>No matter how wisely we guide our creature’s evolution, there may come a time when it’s best to delete an official feature. For example, you might have created a lizard, and now you choose to delete its legs. Perhaps you want to transform this awkward creature into a sleek and modern python.</p>
  112. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/lizard-to-snake.jpg" alt=""/></p>
  113. <p>There are two main reasons to delete features. First, you might discover a feature was a bad idea, through user feedback or your own growing wisdom. That was the case with the quirky behavior of midnight. Or, the feature might have been well-adapted to your library’s environment at first, but the ecology changes. Perhaps another deity invents mammals. Your creature wants to squeeze into their little burrows and eat the tasty mammal filling, so it has to lose its legs.</p>
  114. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/mammal.jpg" alt=""/></p>
  115. <p>Similarly, the Python standard library deletes features in response to changes in the language itself. Consider asyncio’s Lock. It has been awaitable ever since “await” was added as a keyword:</p>
  116. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/>lock <span>=</span> asyncio<span>.</span>Lock()
  117. <span>async</span> <span>def</span> <span>critical_section</span>():
  118. <span> <span>await</span> lock
  119. </span> <span>try</span>:
  120. <span>print</span>(<span>'holding lock'</span>)
  121. <span>finally</span>:
  122. lock<span>.</span>release()
  123. </code></pre></div>
  124. <p>But now, we can do “async with lock”:</p>
  125. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/>lock <span>=</span> asyncio<span>.</span>Lock()
  126. <span>async</span> <span>def</span> <span>critical_section</span>():
  127. <span> <span>async</span> <span>with</span> lock:
  128. </span> <span>print</span>(<span>'holding lock'</span>)
  129. </code></pre></div>
  130. <p>The new style is much better! It’s short, and less prone to mistakes in a big function with other try-except blocks. Since “there should be one and preferably only one obvious way to do it” <a href="https://bugs.python.org/issue32253">the old syntax is deprecated in Python 3.7</a> and it will be banned soon.</p>
  131. <p>It’s inevitable that ecological change will have this effect on your code too, so learn to delete features gently. Before you do so, consider the cost or benefit of deleting it. Responsible maintainers are reluctant to make their users change a large amount of their code, or change their logic. (Remember how painful it was when Python 3 removed the “u” string prefix, before it was added back.) If the code changes are mechanical, however, like a simple search and replace, or if the feature is dangerous, it may be worth deleting.</p>
  132. <div><p>
  133. Whether to Delete a Feature
  134. </p></div>
  135. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/scale.jpg" alt=""/></p>
  136. <table class="pro-con">
  137. <thead>
  138. <tr>
  139. <th>Con</th>
  140. <th>Pro</th>
  141. </tr>
  142. </thead>
  143. <tbody>
  144. <tr>
  145. <td>Code must change</td>
  146. <td>Change is mechanical</td>
  147. </tr>
  148. <tr>
  149. <td>Logic must change</td>
  150. <td>Feature is dangerous</td>
  151. </tr>
  152. </tbody>
  153. </table>
  154. <p>In the case of our hungry lizard, we decide to delete its legs so it slither into a mouse’s hole and eat it. How do we go about this? We could just delete the <code>walk</code> method, changing code from this:</p>
  155. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>class</span> <span>Reptile</span>:
  156. <span>def</span> <span>walk</span>(<span>self</span>):
  157. <span>print</span>(<span>'step step step'</span>)
  158. </code></pre></div>
  159. <p>To this:</p>
  160. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>class</span> <span>Reptile</span>:
  161. <span>def</span> <span>slither</span>(<span>self</span>):
  162. <span>print</span>(<span>'slide slide slide'</span>)
  163. </code></pre></div>
  164. <p>That’s not a good idea, the creature is used to walking! Or, in terms of a library, your users have code that relies on the existing method. When they upgrade to the latest version of your library, their code will break.</p>
  165. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># User's code. Oops!</span>
  166. Reptile<span>.</span>walk()
  167. </code></pre></div>
  168. <p>Therefore responsible creators make this promise:</p>
  169. <div><p>
  170. Fifth Covenant:<br/>Delete Features Gently
  171. </p></div>
  172. <p>There’s a few steps involved in deleting a feature gently. Starting with a lizard that walks with its legs, you first add the new method, “slither”. Next, deprecate the old method.</p>
  173. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span>import</span> <span>warnings</span>
  174. <span>class</span> <span>Reptile</span>:
  175. <span>def</span> <span>walk</span>(<span>self</span>):
  176. warnings<span>.</span>warn(
  177. <span>"walk is deprecated, use slither"</span>,
  178. <span>DeprecationWarning</span>, stacklevel<span>=2</span>)
  179. <span>print</span>(<span>'step step step'</span>)
  180. <span>def</span> <span>slither</span>(<span>self</span>):
  181. <span>print</span>(<span>'slide slide slide'</span>)
  182. </code></pre></div>
  183. <p>The Python warnings module is quite powerful. By default it prints warnings to stderr, only once per code location, but you can silence warnings or turn them into exceptions, among other options.</p>
  184. <p>As soon as you add this warning to your library, PyCharm and other IDEs render the deprecated method with a strikethrough. Users know right away that the method is due for deletion.</p>
  185. <pre><code>Reptile().<span>walk()</span></code></pre>
  186. <p>What happens when they run their code with the upgraded library?</p>
  187. <div class="highlight"><pre><code class="language-text" data-lang="text"><span/>&gt; python3 script.py
  188. DeprecationWarning: walk is deprecated, use slither
  189. script.py:14: Reptile().walk()
  190. step step step
  191. </code></pre></div>
  192. <p>By default, they see a warning on stderr, but the script succeeds and prints “step step step”. The warning’s traceback shows what line of the user’s code must be fixed. (That’s what the “stacklevel” argument does: it shows the call site that users need to change, not the line where the warning is generated.) Notice that the error message is instructive, it describes what a library user must do to migrate to the new version.</p>
  193. <p>Your users will want to test their code and prove they call no deprecated library methods. Warnings alone won’t make unittests fail, but exceptions will. Python has a command-line option to turn deprecation warnings into exceptions:</p>
  194. <div class="highlight"><pre><code class="language-text" data-lang="text"><span/>&gt; python3 -Werror::DeprecationWarning script.py
  195. Traceback (most recent call last):
  196. File "script.py", line 14, in &lt;module&gt;
  197. Reptile().walk()
  198. File "script.py", line 8, in walk
  199. DeprecationWarning, stacklevel=2)
  200. DeprecationWarning: walk is deprecated, use slither
  201. </code></pre></div>
  202. <p>Now, “step step step” is not printed, because the script terminates with an error.</p>
  203. <p>So once you’ve released a version of your library that warns about the deprecated “walk” method, you can delete it safely in the next release. Right?</p>
  204. <p>Consider what your library’s users might have in their projects’ requirements:</p>
  205. <pre><code># User's requirements.txt has a dependency on the reptile package.
  206. reptile
  207. </code></pre>
  208. <p>The next time they deploy their code, they’ll install the latest version of your library. If they haven’t yet handled all deprecations then their code will break, because it still depends on “walk”. You need to be gentler than this. There are three more promises you must keep to your users: to maintain a changelog, choose a version scheme, and write an upgrade guide.</p>
  209. <div><p>
  210. Sixth Covenant:<br/>Maintain a Changelog
  211. </p></div>
  212. <p>Your library must have a change log; its main purpose is to announce when a feature that your users rely on is deprecated or deleted.</p>
  213. <div>
  214. <p>Changes in Version 1.1</p>
  215. <p><strong>New features</strong></p>
  216. <ul><li>New function Reptile.slither()</li></ul>
  217. <p><strong>Deprecations</strong></p>
  218. <ul><li>Reptile.walk() is deprecated and will be removed in version 2.0, use slither()</li></ul></div>
  219. <p>Responsible creators use version numbers to express how a library has changed, so users can make informed decisions about upgrading. A “version scheme” is a language for communicating the pace of change.</p>
  220. <div><p>
  221. Seventh Covenant:<br/>Choose a Version Scheme
  222. </p></div>
  223. <p>There are two schemes in widespread use, <a href="https://semver.org">semantic versioning</a> and time-based versioning. I recommend semantic versioning for nearly any library. The Python flavor thereof is defined in <a href="https://www.python.org/dev/peps/pep-0440/">PEP 440</a>, and tools like “pip” understand semantic version numbers.</p>
  224. <p>If you choose semantic versioning for your library, you can delete its legs gently with version numbers like:</p>
  225. <blockquote>
  226. <p>1.0: First “stable” release, with walk()<br/>
  227. 1.1: Add slither(), deprecate walk()<br/>
  228. 2.0: Delete walk()</p>
  229. </blockquote>
  230. <p>Your users should depend on a range of your library’s versions like so:</p>
  231. <pre><code># User's requirements.txt.
  232. reptile&gt;=1,&lt;2
  233. </code></pre>
  234. <p>This allows them to upgrade automatically within a major release, receiving bugfixes and potentially raising some deprecation warnings, but not upgrading to the <strong>next</strong> major release and risking a change that breaks their code.</p>
  235. <p>If you follow time-based version your releases might be numbered thus:</p>
  236. <blockquote>
  237. <p>2017.06.0: A release in June 2017<br/>
  238. 2018.11.0: Add slither(), deprecate walk()<br/>
  239. 2019.04.0: Delete walk()</p>
  240. </blockquote>
  241. <p>And users can depend on your library like:</p>
  242. <pre><code># User's requirements.txt for time-based version.
  243. reptile==2018.11.*
  244. </code></pre>
  245. <p>This is terrific, but how do your users know your versioning scheme and how to test their code for deprecations? You have to advise them how to upgrade.</p>
  246. <div><p>
  247. Eighth Covenant:<br/>Write an Upgrade Guide
  248. </p></div>
  249. <p>Here’s how a responsible library creator might guide users:</p>
  250. <div>
  251. <p>Upgrading to 2.0</p>
  252. <p><strong>Migrate from Deprecated APIs</strong></p>
  253. <p>See the <span>changelog</span> for deprecated features.</p>
  254. <p><strong>Enable Deprecation Warnings</strong></p>
  255. <p>Upgrade to 1.1 and test your code with:</p>
  256. <code>python -Werror::DeprecationWarning</code>
  257. <p>Now it's safe to upgrade.</p></div>
  258. <p>You must teach users how to handle deprecation warnings by showing them the command line options. Not all Python programmers know this—I certainly have to look up the syntax each time. And take note, you must <strong>release</strong> a version that prints warnings from each deprecated API, so users can test with that version before upgrading again. In this example, version 1.1 is the bridge release. It allows your users to rewrite their code incrementally, fixing each deprecation warning separately until they have entirely migrated to the latest API. They can test changes to their code, and changes in your library, independently from each other, and isolate the cause of bugs.</p>
  259. <p>If you chose semantic versioning, this transitional period lasts until the next major release, from 1.x to 2.0, or from 2.x to 3.0, and so on. The gentle way to delete a creature’s legs is to give it at least one version in which to adjust its lifestyle. Don’t remove the legs all at once!</p>
  260. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/skink.jpg" alt=""/></p>
  261. <p>Version numbers, deprecation warnings, the changelog, and the upgrade guide work together to gently evolve your library without breaking the covenant with your users. The <a href="https://twistedmatrix.com/documents/current/core/development/policy/compatibility-policy.html">Twisted project’s Compatibility Policy</a> explains this beautifully:</p>
  262. <blockquote>
  263. <p>“The First One’s Always Free”</p>
  264. <p>Any application which runs without warnings may be upgraded one minor version of Twisted.</p>
  265. <p>In other words, any application which runs its tests without triggering any warnings from Twisted should be able to have its Twisted version upgraded at least once with no ill effects except the possible production of new warnings.</p>
  266. </blockquote>
  267. <p>Now, we creator deities have gained the wisdom and power to add features by adding methods, and to delete them gently. We can also add features by adding parameters, but this brings a new level of difficulty. Are you ready?</p>
  268. <h1 id="adding-parameters">Adding Parameters</h1>
  269. <p>Imagine that you just gave your snake-like creature a pair of wings. Now you must allow it the choice whether to move by slithering or flying. Currently its “move” function takes one parameter:</p>
  270. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  271. <span>def</span> <span>move</span>(direction):
  272. <span>print</span>(f<span>'slither </span><span>{direction}</span><span>'</span>)
  273. <span># A user's application.</span>
  274. move(<span>'north'</span>)
  275. </code></pre></div>
  276. <p>You want to add a “mode” parameter, but this breaks your users’ code if they upgrade, because they pass only one argument:</p>
  277. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  278. <span>def</span> <span>move</span>(direction, mode):
  279. <span>assert</span> mode <span>in</span> (<span>'slither'</span>, <span>'fly'</span>)
  280. <span>print</span>(f<span>'</span><span>{mode}</span><span> </span><span>{direction}</span><span>'</span>)
  281. <span># A user's application. Error!</span>
  282. <span>move(<span>'north'</span>)
  283. </span></code></pre></div>
  284. <p>A truly wise creator promises not to break users’ code this way.</p>
  285. <div><p>
  286. Ninth Covenant:<br/>Add Parameters Compatibly
  287. </p></div>
  288. <p>To keep this covenant, add each new parameter with a default value that preserves the original behavior.</p>
  289. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  290. <span>def</span> <span>move</span>(direction, mode<span>=</span><span>'slither'</span>):
  291. <span>assert</span> mode <span>in</span> (<span>'slither'</span>, <span>'fly'</span>)
  292. <span>print</span>(f<span>'</span><span>{mode}</span><span> </span><span>{direction}</span><span>'</span>)
  293. <span># A user's application.</span>
  294. move(<span>'north'</span>)
  295. </code></pre></div>
  296. <p>Over time, parameters are the natural history of your function’s evolution. They’re listed oldest first, each with a default value. Library users can pass keyword arguments to opt in to specific new behaviors, and accept the defaults for all others.</p>
  297. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  298. <span>def</span> <span>move</span>(direction,
  299. mode<span>=</span><span>'slither'</span>,
  300. turbo<span>=</span><span>False</span>,
  301. extra_sinuous<span>=</span><span>False</span>,
  302. hail_lyft<span>=</span><span>False</span>):
  303. <span># ...</span>
  304. <span># A user's application.</span>
  305. move(<span>'north'</span>, extra_sinuous<span>=</span><span>True</span>)
  306. </code></pre></div>
  307. <p>There is a danger, however, that a user might write code like this:</p>
  308. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># A user's application, poorly-written.</span>
  309. move(<span>'north'</span>, <span>'slither'</span>, <span>False</span>, <span>True</span>)
  310. </code></pre></div>
  311. <p>What happens if, in the next major version of your library, you get rid of one of the parameters, like “turbo”?</p>
  312. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code, next major version. "turbo" is deleted.</span>
  313. <span>def</span> <span>move</span>(direction,
  314. mode<span>=</span><span>'slither'</span>,
  315. extra_sinuous<span>=</span><span>False</span>,
  316. hail_lyft<span>=</span><span>False</span>):
  317. <span># ...</span>
  318. <span># A user's application, poorly-written.</span>
  319. move(<span>'north'</span>, <span>'slither'</span>, <span>False</span>, <span>True</span>)
  320. </code></pre></div>
  321. <p>The user’s code still compiles, and this is a bad thing. The code stopped moving extra-sinuously and started hailing a Lyft, which was not the intention. I trust that you can predict what I’ll say next: deleting a parameter requires several steps. First, of course, deprecate the “turbo” parameter. I like a technique like this one that detects whether any user’s code is relying on this parameter:</p>
  322. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  323. _turbo_default <span>=</span> <span>object</span>()
  324. <span>def</span> <span>move</span>(direction,
  325. mode<span>=</span><span>'slither'</span>,
  326. turbo<span>=</span>_turbo_default,
  327. extra_sinuous<span>=</span><span>False</span>,
  328. hail_lyft<span>=</span><span>False</span>):
  329. <span>if</span> turbo <span>is</span> <span>not</span> _turbo_default:
  330. warnings<span>.</span>warn(
  331. <span>"'turbo' is deprecated"</span>,
  332. <span>DeprecationWarning</span>,
  333. stacklevel<span>=2</span>)
  334. <span>else</span>:
  335. <span># The old default.</span>
  336. turbo <span>=</span> <span>False</span>
  337. </code></pre></div>
  338. <p>But your users might not notice the warning. Warnings are not very loud: they can be suppressed, or lost in log files. Users might heedlessly upgrade to the next major version of your library, the version that deletes “turbo”. Their code will run without error and silently do the wrong thing! As the Zen of Python says, “Errors should never pass silently.” Indeed, reptiles hear poorly, so you must correct them very loudly when they make mistakes.</p>
  339. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/loudly.jpg" alt=""/></p>
  340. <p>The best way to protect your users is with Python 3’s star syntax, which requires callers to pass keyword arguments.</p>
  341. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code.</span>
  342. <span># All arguments after "*" must be passed by keyword.</span>
  343. <span>def</span> <span>move</span>(direction,
  344. <span>*</span>,
  345. mode<span>=</span><span>'slither'</span>,
  346. turbo<span>=</span><span>False</span>,
  347. extra_sinuous<span>=</span><span>False</span>,
  348. hail_lyft<span>=</span><span>False</span>):
  349. <span># ...</span>
  350. <span># A user's application, poorly-written.</span>
  351. <span># Error! Can't use positional args, keyword args required.</span>
  352. move(<span>'north'</span>, <span>'slither'</span>, <span>False</span>, <span>True</span>)
  353. </code></pre></div>
  354. <p>With the star in place, this is the only syntax allowed:</p>
  355. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># A user's application.</span>
  356. move(<span>'north'</span>, extra_sinuous<span>=</span><span>True</span>)
  357. </code></pre></div>
  358. <p>Now when you delete “turbo”, you can be certain any user code that relies on it will fail loudly. If your library also supports Python 2, there’s no shame in that, you can simulate the star syntax thus (<a href="http://www.informit.com/articles/article.aspx?p=2314818">credit to Brett Slatkin</a>):</p>
  359. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># Your library code, Python 2 compatible.</span>
  360. <span>def</span> <span>move</span>(direction, <span>**</span>kwargs):
  361. mode <span>=</span> kwargs<span>.</span>pop(<span>'mode'</span>, <span>'slither'</span>)
  362. sinuous <span>=</span> kwargs<span>.</span>pop(<span>'extra_sinuous'</span>, <span>False</span>)
  363. lyft <span>=</span> kwargs<span>.</span>pop(<span>'hail_lyft'</span>, <span>False</span>)
  364. <span>if</span> kwargs:
  365. <span>raise</span> <span>TypeError</span>(<span>'Unexpected kwargs: </span><span>%r</span><span>'</span>
  366. <span>%</span> kwargs)
  367. <span># ...</span>
  368. </code></pre></div>
  369. <p>Requiring keyword arguments is a wise choice, but it requires foresight. If you allow an argument to be passed positionally, you cannot convert it to keyword-only in a later release. So, add the star now. You can observe in the asyncio API that it uses the star pervasively in constructors, methods, and functions. Even though “Lock” only takes one optional parameter so far, the asyncio developers added the star right away. This is providential.</p>
  370. <div class="highlight"><pre><code class="language-py3" data-lang="py3"><span/><span># In asyncio.</span>
  371. <span>class</span> <span>Lock</span>:
  372. <span>def</span> <span>__init__</span>(<span>self</span>, <span>*</span>, loop<span>=</span><span>None</span>):
  373. <span># ...</span>
  374. </code></pre></div>
  375. <p>Now we’ve gained the wisdom to change methods and parameters while keeping our covenant with users. The time has come to try the most challenging kind of evolution: changing behavior without changing either methods or parameters.</p>
  376. <h1 id="changing-behavior">Changing Behavior</h1>
  377. <p>Let’s say your creature is a rattlesnake, and you want to teach it a new behavior.</p>
  378. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/rattlesnake.jpg" alt=""/></p>
  379. <p>Sidewinding! The creature’s body will appear the same, but its behavior will change. How can we prepare it for this step of its evolution?</p>
  380. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/sidewinding.jpg" alt=""/></p>
  381. <p>A responsible creator can learn from the following example in the Python standard library, when behavior changed without a new function or parameters. Once upon a time, the os.stat function was introduced to get file statistics, like the creation time. At first, times were always integers.</p>
  382. <div class="highlight"><pre><code class="language-pycon" data-lang="pycon"><span/><span>&gt;&gt;&gt; </span>os<span>.</span>stat(<span>'file.txt'</span>)<span>.</span>st_ctime
  383. <span>1540817862</span>
  384. </code></pre></div>
  385. <p>One day, the core developers decided to use floats for os.stat times, to give sub-second precision. But they worried that existing user code wasn’t ready for the change.
  386. They created a setting in Python 2.3, “stat_float_times”, that was false by default. A user could set it to True to opt in to floating-point timestamps.</p>
  387. <div class="highlight"><pre><code class="language-pycon" data-lang="pycon"><span/><span>&gt;&gt;&gt; </span><span># Python 2.3.</span>
  388. <span>&gt;&gt;&gt; </span>os<span>.</span>stat_float_times(<span>True</span>)
  389. <span>&gt;&gt;&gt; </span>os<span>.</span>stat(<span>'file.txt'</span>)<span>.</span>st_ctime
  390. <span>1540817862.598021</span>
  391. </code></pre></div>
  392. <p>Starting in Python 2.5, float times became the default, so any new code written for 2.5 and later could ignore the setting and expect floats. Of course, you could set it to False to keep the old behavior, or set it to True to ensure the new behavior in all Python versions, and prepare your code for the day when stat_float_times is deleted.</p>
  393. <p>Ages passed. In Python 3.1 the setting was deprecated to prepare people for the distant future, and finally, after its decades-long journey, <a href="https://bugs.python.org/issue31827">the setting was removed</a>. Float times are now the only option. It’s a long road, but responsible deities are patient because we know this gradual process has a good chance of saving users from unexpected behavior changes.</p>
  394. <div><p>
  395. Tenth Covenant:<br/>Change Behavior Gradually
  396. </p></div>
  397. <p>Here are the steps:</p>
  398. <ul>
  399. <li>Add a flag to opt in to the new behavior, default False, warn if it’s False<br/></li>
  400. <li>Change default to True, deprecate flag entirely<br/></li>
  401. <li>Remove the flag</li>
  402. </ul>
  403. <p>If you follow semantic versioning, the versions might be like so:</p>
  404. <table class="versions-table" rules="rows">
  405. <thead>
  406. <tr>
  407. <th>Library version</th><th>Library API</th><th>User code</th>
  408. </tr>
  409. </thead>
  410. <tbody>
  411. <tr>
  412. </tr><tr><td>1.0</td><td>No flag</td><td>Expect old behavior</td>
  413. </tr><tr><td>1.1</td><td>Add flag, default False,<br/>
  414. warn if it's False </td><td>Set flag True,<br/>
  415. handle new behavior</td></tr>
  416. <tr><td>2.0</td><td>Change default to True,<br/>
  417. deprecate flag entirely</td><td>Handle new behavior</td></tr>
  418. <tr><td>3.0</td><td>Remove flag</td><td>Handle new behavior</td></tr>
  419. </tbody></table>
  420. <p>You need <strong>two</strong> major releases to complete the maneuver. If you had gone straight from “Add flag, default False, warn if it’s False” to “Remove flag” without the intervening release, your users’ code would be unable to upgrade. User code written correctly for 1.1, which sets the flag to True and handles the new behavior, must be able to upgrade to the next release with no ill effect except new warnings, but if the flag were deleted in the next release that code would break. A responsible deity never violates the Twisted policy: “The First One’s Always Free.”</p>
  421. <h1 id="the-responsible-creator">The Responsible Creator</h1>
  422. <p><img src="https://emptysqua.re/blog/api-evolution-the-right-way/demeter.jpg" alt=""/></p>
  423. <p>Our ten covenants belong loosely in three categories:</p>
  424. <h3 id="evolve-cautiously">Evolve Cautiously</h3>
  425. <ol>
  426. <li>Avoid Bad Features</li>
  427. <li>Minimize Features</li>
  428. <li>Keep Features Narrow</li>
  429. <li>Mark Experimental Features “Provisional”</li>
  430. <li>Delete Features Gently</li>
  431. </ol>
  432. <h3 id="record-history-rigorously">Record History Rigorously</h3>
  433. <ol>
  434. <li>Maintain a Changelog</li>
  435. <li>Choose a Version Scheme</li>
  436. <li>Write an Upgrade Guide</li>
  437. </ol>
  438. <h3 id="change-slowly-and-loudly">Change Slowly and Loudly</h3>
  439. <ol>
  440. <li>Add Parameters Compatibly</li>
  441. <li>Change Behavior Gradually</li>
  442. </ol>
  443. <p>If you keep these covenants with your creature, you’ll be a responsible creator deity. Your creature’s body can evolve over time, forever improving and adapting to changes in its environment, but without sudden changes the creature isn’t prepared for. If you maintain a library, keep these promises to your users, and you can innovate your library without breaking the code of the people who rely on you.</p>
  444. <hr/>
  445. <p>Illustrations:</p>
  446. <ul>
  447. <li><a href="https://www.gutenberg.org/files/42224/42224-h/42224-h.htm">The World’s Progress, The Delphian Society, 1913</a></li>
  448. <li><a href="https://publicdomainreview.org/product-att/artist/charles-owen/">Essay Towards a Natural History of Serpents, Charles Owen, 1742</a></li>
  449. <li><a href="https://archive.org/details/onbatrachiarepti00cope/page/n3">On the batrachia and reptilia of Costa Rica: With notes on the herpetology and ichthyology of Nicaragua and Peru, Edward Drinker Cope, 1875</a></li>
  450. <li><a href="https://www.flickr.com/photos/internetarchivebookimages/20556001490">Natural History, Richard Lydekker et. al., 1897</a></li>
  451. <li><a href="https://www.oldbookillustrations.com/illustrations/stationery/">Mes Prisons, Silvio Pellico, 1843</a></li>
  452. <li><a href="https://www.alamy.com/mediacomp/ImageDetails.aspx?ref=D7Y61W">Tierfotoagentur / m.blue-shadow</a></li>
  453. <li><a href="https://www.vintag.es/2013/06/riding-alligator-c-1930s.html">From Los Angeles Public Library, 1930</a></li>
  454. </ul>
  455. </div>