A place to cache linked articles (think custom and personal wayback machine)
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

4 лет назад
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. <!doctype html><!-- This is a valid HTML5 document. -->
  2. <!-- Screen readers, SEO, extensions and so on. -->
  3. <html lang=fr>
  4. <!-- Has to be within the first 1024 bytes, hence before the <title>
  5. See: https://www.w3.org/TR/2012/CR-html5-20121217/document-metadata.html#charset -->
  6. <meta charset=utf-8>
  7. <!-- Why no `X-UA-Compatible` meta: https://stackoverflow.com/a/6771584 -->
  8. <!-- The viewport meta is quite crowded and we are responsible for that.
  9. See: https://codepen.io/tigt/post/meta-viewport-for-2015 -->
  10. <meta name=viewport content="width=device-width,minimum-scale=1,initial-scale=1,shrink-to-fit=no">
  11. <!-- Required to make a valid HTML5 document. -->
  12. <title>The Ultimate Guide to Data Classes in Python 3.7 (archive) — David Larlet</title>
  13. <!-- Generated from https://realfavicongenerator.net/ such a mess. -->
  14. <link rel="apple-touch-icon" sizes="180x180" href="/static/david/icons/apple-touch-icon.png">
  15. <link rel="icon" type="image/png" sizes="32x32" href="/static/david/icons/favicon-32x32.png">
  16. <link rel="icon" type="image/png" sizes="16x16" href="/static/david/icons/favicon-16x16.png">
  17. <link rel="manifest" href="/manifest.json">
  18. <link rel="mask-icon" href="/static/david/icons/safari-pinned-tab.svg" color="#5bbad5">
  19. <link rel="shortcut icon" href="/static/david/icons/favicon.ico">
  20. <meta name="apple-mobile-web-app-title" content="David Larlet">
  21. <meta name="application-name" content="David Larlet">
  22. <meta name="msapplication-TileColor" content="#da532c">
  23. <meta name="msapplication-config" content="/static/david/icons/browserconfig.xml">
  24. <meta name="theme-color" content="#f0f0ea">
  25. <!-- That good ol' feed, subscribe :p. -->
  26. <link rel=alternate type="application/atom+xml" title=Feed href="/david/log/">
  27. <meta name="robots" content="noindex, nofollow">
  28. <meta content="origin-when-cross-origin" name="referrer">
  29. <!-- Canonical URL for SEO purposes -->
  30. <link rel="canonical" href="https://realpython.com/python-data-classes/">
  31. <style>
  32. /* http://meyerweb.com/eric/tools/css/reset/ */
  33. html, body, div, span,
  34. h1, h2, h3, h4, h5, h6, p, blockquote, pre,
  35. a, abbr, address, big, cite, code,
  36. del, dfn, em, img, ins,
  37. small, strike, strong, tt, var,
  38. dl, dt, dd, ol, ul, li,
  39. fieldset, form, label, legend,
  40. table, caption, tbody, tfoot, thead, tr, th, td,
  41. article, aside, canvas, details, embed,
  42. figure, figcaption, footer, header, hgroup,
  43. menu, nav, output, ruby, section, summary,
  44. time, mark, audio, video {
  45. margin: 0;
  46. padding: 0;
  47. border: 0;
  48. font-size: 100%;
  49. font: inherit;
  50. vertical-align: baseline;
  51. }
  52. /* HTML5 display-role reset for older browsers */
  53. article, aside, details, figcaption, figure,
  54. footer, header, hgroup, menu, nav, section { display: block; }
  55. body { line-height: 1; }
  56. blockquote, q { quotes: none; }
  57. blockquote:before, blockquote:after,
  58. q:before, q:after {
  59. content: '';
  60. content: none;
  61. }
  62. table {
  63. border-collapse: collapse;
  64. border-spacing: 0;
  65. }
  66. /* http://practicaltypography.com/equity.html */
  67. /* https://calendar.perfplanet.com/2016/no-font-face-bulletproof-syntax/ */
  68. /* https://www.filamentgroup.com/lab/js-web-fonts.html */
  69. @font-face {
  70. font-family: 'EquityTextB';
  71. src: url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff2') format('woff2'),
  72. url('/static/david/css/fonts/Equity-Text-B-Regular-webfont.woff') format('woff');
  73. font-weight: 300;
  74. font-style: normal;
  75. font-display: swap;
  76. }
  77. @font-face {
  78. font-family: 'EquityTextB';
  79. src: url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff2') format('woff2'),
  80. url('/static/david/css/fonts/Equity-Text-B-Italic-webfont.woff') format('woff');
  81. font-weight: 300;
  82. font-style: italic;
  83. font-display: swap;
  84. }
  85. @font-face {
  86. font-family: 'EquityTextB';
  87. src: url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff2') format('woff2'),
  88. url('/static/david/css/fonts/Equity-Text-B-Bold-webfont.woff') format('woff');
  89. font-weight: 700;
  90. font-style: normal;
  91. font-display: swap;
  92. }
  93. @font-face {
  94. font-family: 'ConcourseT3';
  95. src: url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff2') format('woff2'),
  96. url('/static/david/css/fonts/concourse_t3_regular-webfont-20190806.woff') format('woff');
  97. font-weight: 300;
  98. font-style: normal;
  99. font-display: swap;
  100. }
  101. /* http://practice.typekit.com/lesson/caring-about-opentype-features/ */
  102. body {
  103. /* http://www.cssfontstack.com/ Palatino 99% Win 86% Mac */
  104. font-family: "EquityTextB", Palatino, serif;
  105. background-color: #f0f0ea;
  106. color: #07486c;
  107. font-kerning: normal;
  108. -moz-osx-font-smoothing: grayscale;
  109. -webkit-font-smoothing: subpixel-antialiased;
  110. text-rendering: optimizeLegibility;
  111. font-variant-ligatures: common-ligatures contextual;
  112. font-feature-settings: "kern", "liga", "clig", "calt";
  113. }
  114. pre, code, kbd, samp, var, tt {
  115. font-family: 'TriplicateT4c', monospace;
  116. }
  117. em {
  118. font-style: italic;
  119. color: #323a45;
  120. }
  121. strong {
  122. font-weight: bold;
  123. color: black;
  124. }
  125. nav {
  126. background-color: #323a45;
  127. color: #f0f0ea;
  128. display: flex;
  129. justify-content: space-around;
  130. padding: 1rem .5rem;
  131. }
  132. nav:last-child {
  133. border-bottom: 1vh solid #2d7474;
  134. }
  135. nav a {
  136. color: #f0f0ea;
  137. }
  138. nav abbr {
  139. border-bottom: 1px dotted white;
  140. }
  141. h1 {
  142. border-top: 1vh solid #2d7474;
  143. border-bottom: .2vh dotted #2d7474;
  144. background-color: #e3e1e1;
  145. color: #323a45;
  146. text-align: center;
  147. padding: 5rem 0 4rem 0;
  148. width: 100%;
  149. font-family: 'ConcourseT3';
  150. display: flex;
  151. flex-direction: column;
  152. }
  153. h1.single {
  154. padding-bottom: 10rem;
  155. }
  156. h1 span {
  157. position: absolute;
  158. top: 1vh;
  159. left: 20%;
  160. line-height: 0;
  161. }
  162. h1 span a {
  163. line-height: 1.7;
  164. padding: 1rem 1.2rem .6rem 1.2rem;
  165. border-radius: 0 0 6% 6%;
  166. background: #2d7474;
  167. font-size: 1.3rem;
  168. color: white;
  169. text-decoration: none;
  170. }
  171. h2 {
  172. margin: 4rem 0 1rem;
  173. border-top: .2vh solid #2d7474;
  174. padding-top: 1vh;
  175. }
  176. h3 {
  177. text-align: center;
  178. margin: 3rem 0 .75em;
  179. }
  180. hr {
  181. height: .4rem;
  182. width: .4rem;
  183. border-radius: .4rem;
  184. background: #07486c;
  185. margin: 2.5rem auto;
  186. }
  187. time {
  188. display: bloc;
  189. margin-left: 0 !important;
  190. }
  191. ul, ol {
  192. margin: 2rem;
  193. }
  194. ul {
  195. list-style-type: square;
  196. }
  197. a {
  198. text-decoration-skip-ink: auto;
  199. text-decoration-thickness: 0.05em;
  200. text-underline-offset: 0.09em;
  201. }
  202. article {
  203. max-width: 50rem;
  204. display: flex;
  205. flex-direction: column;
  206. margin: 2rem auto;
  207. }
  208. article.single {
  209. border-top: .2vh dotted #2d7474;
  210. margin: -6rem auto 1rem auto;
  211. background: #f0f0ea;
  212. padding: 2rem;
  213. }
  214. article p:last-child {
  215. margin-bottom: 1rem;
  216. }
  217. p {
  218. padding: 0 .5rem;
  219. margin-left: 3rem;
  220. }
  221. p + p,
  222. figure + p {
  223. margin-top: 2rem;
  224. }
  225. blockquote {
  226. background-color: #e3e1e1;
  227. border-left: .5vw solid #2d7474;
  228. display: flex;
  229. flex-direction: column;
  230. align-items: center;
  231. padding: 1rem;
  232. margin: 1.5rem;
  233. }
  234. blockquote cite {
  235. font-style: italic;
  236. }
  237. blockquote p {
  238. margin-left: 0;
  239. }
  240. figure {
  241. border-top: .2vh solid #2d7474;
  242. background-color: #e3e1e1;
  243. text-align: center;
  244. padding: 1.5rem 0;
  245. margin: 1rem 0 0;
  246. font-size: 1.5rem;
  247. width: 100%;
  248. }
  249. figure img {
  250. max-width: 250px;
  251. max-height: 250px;
  252. border: .5vw solid #323a45;
  253. padding: 1px;
  254. }
  255. figcaption {
  256. padding: 1rem;
  257. line-height: 1.4;
  258. }
  259. aside {
  260. display: flex;
  261. flex-direction: column;
  262. background-color: #e3e1e1;
  263. padding: 1rem 0;
  264. border-bottom: .2vh solid #07486c;
  265. }
  266. aside p {
  267. max-width: 50rem;
  268. margin: 0 auto;
  269. }
  270. /* https://fvsch.com/code/css-locks/ */
  271. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  272. font-size: 1rem;
  273. line-height: calc( 1.5em + 0.2 * 1rem );
  274. }
  275. h1 {
  276. font-size: 1.9rem;
  277. line-height: calc( 1.2em + 0.2 * 1rem );
  278. }
  279. h2 {
  280. font-size: 1.6rem;
  281. line-height: calc( 1.3em + 0.2 * 1rem );
  282. }
  283. h3 {
  284. font-size: 1.35rem;
  285. line-height: calc( 1.4em + 0.2 * 1rem );
  286. }
  287. @media (min-width: 20em) {
  288. /* The (100vw - 20rem) / (50 - 20) part
  289. resolves to 0-1rem, depending on the
  290. viewport width (between 20em and 50em). */
  291. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  292. font-size: calc( 1rem + .6 * (100vw - 20rem) / (50 - 20) );
  293. line-height: calc( 1.5em + 0.2 * (100vw - 50rem) / (20 - 50) );
  294. margin-left: 0;
  295. }
  296. h1 {
  297. font-size: calc( 1.9rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  298. line-height: calc( 1.2em + 0.2 * (100vw - 50rem) / (20 - 50) );
  299. }
  300. h2 {
  301. font-size: calc( 1.5rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  302. line-height: calc( 1.3em + 0.2 * (100vw - 50rem) / (20 - 50) );
  303. }
  304. h3 {
  305. font-size: calc( 1.35rem + 1.5 * (100vw - 20rem) / (50 - 20) );
  306. line-height: calc( 1.4em + 0.2 * (100vw - 50rem) / (20 - 50) );
  307. }
  308. }
  309. @media (min-width: 50em) {
  310. /* The right part of the addition *must* be a
  311. rem value. In this example we *could* change
  312. the whole declaration to font-size:2.5rem,
  313. but if our baseline value was not expressed
  314. in rem we would have to use calc. */
  315. p, li, pre, code, kbd, samp, var, tt, time, details, figcaption {
  316. font-size: calc( 1rem + .6 * 1rem );
  317. line-height: 1.5em;
  318. }
  319. p, li, pre, details {
  320. margin-left: 3rem;
  321. }
  322. h1 {
  323. font-size: calc( 1.9rem + 1.5 * 1rem );
  324. line-height: 1.2em;
  325. }
  326. h2 {
  327. font-size: calc( 1.5rem + 1.5 * 1rem );
  328. line-height: 1.3em;
  329. }
  330. h3 {
  331. font-size: calc( 1.35rem + 1.5 * 1rem );
  332. line-height: 1.4em;
  333. }
  334. figure img {
  335. max-width: 500px;
  336. max-height: 500px;
  337. }
  338. }
  339. figure.unsquared {
  340. margin-bottom: 1.5rem;
  341. }
  342. figure.unsquared img {
  343. height: inherit;
  344. }
  345. @media print {
  346. body { font-size: 100%; }
  347. a:after { content: " (" attr(href) ")"; }
  348. a, a:link, a:visited, a:after {
  349. text-decoration: underline;
  350. text-shadow: none !important;
  351. background-image: none !important;
  352. background: white;
  353. color: black;
  354. }
  355. abbr[title] { border-bottom: 0; }
  356. abbr[title]:after { content: " (" attr(title) ")"; }
  357. img { page-break-inside: avoid; }
  358. @page { margin: 2cm .5cm; }
  359. h1, h2, h3 { page-break-after: avoid; }
  360. p3 { orphans: 3; widows: 3; }
  361. img {
  362. max-width: 250px !important;
  363. max-height: 250px !important;
  364. }
  365. nav, aside { display: none; }
  366. }
  367. ul.with_columns {
  368. column-count: 1;
  369. }
  370. @media (min-width: 20em) {
  371. ul.with_columns {
  372. column-count: 2;
  373. }
  374. }
  375. @media (min-width: 50em) {
  376. ul.with_columns {
  377. column-count: 3;
  378. }
  379. }
  380. ul.with_two_columns {
  381. column-count: 1;
  382. }
  383. @media (min-width: 20em) {
  384. ul.with_two_columns {
  385. column-count: 1;
  386. }
  387. }
  388. @media (min-width: 50em) {
  389. ul.with_two_columns {
  390. column-count: 2;
  391. }
  392. }
  393. .gallery {
  394. display: flex;
  395. flex-wrap: wrap;
  396. justify-content: space-around;
  397. }
  398. .gallery figure img {
  399. margin-left: 1rem;
  400. margin-right: 1rem;
  401. }
  402. .gallery figure figcaption {
  403. font-family: 'ConcourseT3'
  404. }
  405. footer {
  406. font-family: 'ConcourseT3';
  407. display: flex;
  408. flex-direction: column;
  409. border-top: 3px solid white;
  410. padding: 4rem 0;
  411. background-color: #07486c;
  412. color: white;
  413. }
  414. footer > * {
  415. max-width: 50rem;
  416. margin: 0 auto;
  417. }
  418. footer a {
  419. color: #f1c40f;
  420. }
  421. footer .avatar {
  422. width: 200px;
  423. height: 200px;
  424. border-radius: 50%;
  425. float: left;
  426. -webkit-shape-outside: circle();
  427. shape-outside: circle();
  428. margin-right: 2rem;
  429. padding: 2px 5px 5px 2px;
  430. background: white;
  431. border-left: 1px solid #f1c40f;
  432. border-top: 1px solid #f1c40f;
  433. border-right: 5px solid #f1c40f;
  434. border-bottom: 5px solid #f1c40f;
  435. }
  436. </style>
  437. <h1>
  438. <span><a id="jumper" href="#jumpto" title="Un peu perdu ?">?</a></span>
  439. The Ultimate Guide to Data Classes in Python 3.7 (archive)
  440. <time>Pour la pérennité des contenus liés. Non-indexé, retrait sur simple email.</time>
  441. </h1>
  442. <section>
  443. <article>
  444. <h3><a href="https://realpython.com/python-data-classes/">Source originale du contenu</a></h3>
  445. <p>One new and exciting feature coming in Python 3.7 is the data class. A data class is a class typically containing mainly data, although there aren’t really any restrictions. It is created using the new <code>@dataclass</code> decorator, as follows:</p>
  446. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  447. <span class="nd">@dataclass</span>
  448. <span class="k">class</span> <span class="nc">DataClassCard</span><span class="p">:</span>
  449. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  450. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  451. </pre></div>
  452. <div class="alert alert-primary" role="alert">
  453. <p><strong>Note:</strong> This code, as well as all other examples in this tutorial, will only work in Python 3.7 and above.</p>
  454. </div>
  455. <p>A data class comes with basic functionality already implemented. For instance, you can instantiate, print, and compare data class instances straight out of the box:</p>
  456. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">DataClassCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  457. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span><span class="o">.</span><span class="n">rank</span>
  458. <span class="go">'Q'</span>
  459. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span>
  460. <span class="go">DataClassCard(rank='Q', suit='Hearts')</span>
  461. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">==</span> <span class="n">DataClassCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  462. <span class="go">True</span>
  463. </pre></div>
  464. <p>Compare that to a regular class. A minimal regular class would look something like this:</p>
  465. <div class="highlight python"><pre><span/><span class="k">class</span> <span class="nc">RegularCard</span>
  466. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">rank</span><span class="p">,</span> <span class="n">suit</span><span class="p">):</span>
  467. <span class="bp">self</span><span class="o">.</span><span class="n">rank</span> <span class="o">=</span> <span class="n">rank</span>
  468. <span class="bp">self</span><span class="o">.</span><span class="n">suit</span> <span class="o">=</span> <span class="n">suit</span>
  469. </pre></div>
  470. <p>While this is not much more code to write, you can already see signs of the boilerplate pain: <code>rank</code> and <code>suit</code> are both repeated three times simply to initialize an object. Furthermore, if you try to use this plain class, you’ll notice that the representation of the objects is not very descriptive, and for some reason a queen of hearts is not the same as a queen of hearts:</p>
  471. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">RegularCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  472. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span><span class="o">.</span><span class="n">rank</span>
  473. <span class="go">'Q'</span>
  474. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span>
  475. <span class="go">&lt;__main__.RegularCard object at 0x7fb6eee35d30&gt;</span>
  476. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">==</span> <span class="n">RegularCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  477. <span class="go">False</span>
  478. </pre></div>
  479. <p>Seems like data classes are helping us out behind the scenes. By default, data classes implement a <code>.__repr__()</code> method to provide a nice string representation and an <code>.__eq__()</code> method that can do basic object comparisons. For the <code>RegularCard</code> class to imitate the data class above, you need to add these methods as well:</p>
  480. <div class="highlight python"><pre><span/><span class="k">class</span> <span class="nc">RegularCard</span>
  481. <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">rank</span><span class="p">,</span> <span class="n">suit</span><span class="p">):</span>
  482. <span class="bp">self</span><span class="o">.</span><span class="n">rank</span> <span class="o">=</span> <span class="n">rank</span>
  483. <span class="bp">self</span><span class="o">.</span><span class="n">suit</span> <span class="o">=</span> <span class="n">suit</span>
  484. <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  485. <span class="k">return</span> <span class="p">(</span><span class="n">f</span><span class="s1">'{self.__class__.__name__}'</span>
  486. <span class="n">f</span><span class="s1">'(rank={self.rank!r}, suit={self.suit!r})'</span><span class="p">)</span>
  487. <span class="k">def</span> <span class="fm">__eq__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
  488. <span class="k">if</span> <span class="n">other</span><span class="o">.</span><span class="vm">__class__</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">self</span><span class="o">.</span><span class="vm">__class__</span><span class="p">:</span>
  489. <span class="k">return</span> <span class="bp">NotImplemented</span>
  490. <span class="k">return</span> <span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">rank</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">suit</span><span class="p">)</span> <span class="o">==</span> <span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">rank</span><span class="p">,</span> <span class="n">other</span><span class="o">.</span><span class="n">suit</span><span class="p">)</span>
  491. </pre></div>
  492. <p>In this tutorial, you will learn exactly which conveniences data classes provide. In addition to nice representations and comparisons, you’ll see:</p>
  493. <ul>
  494. <li>How to add default values to data class fields</li>
  495. <li>How data classes allow for ordering of objects</li>
  496. <li>How to represent immutable data</li>
  497. <li>How data classes handle inheritance</li>
  498. </ul>
  499. <p>We will soon dive deeper into those features of data classes. However, you might be thinking that you have already seen something like this before.</p>
  500. <h2 id="alternatives-to-data-classes">Alternatives to Data Classes</h2>
  501. <p>For simple data structures, you have probably already used <a href="https://dbader.org/blog/records-structs-and-data-transfer-objects-in-python">a <code>tuple</code> or a <code>dict</code></a>. You could represent the queen of hearts card in either of the following ways:</p>
  502. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts_tuple</span> <span class="o">=</span> <span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  503. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts_dict</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'rank'</span><span class="p">:</span> <span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'suit'</span><span class="p">:</span> <span class="s1">'Hearts'</span><span class="p">}</span>
  504. </pre></div>
  505. <p>It works. However, it puts a lot of responsibility on you as a programmer:</p>
  506. <ul>
  507. <li>You need to remember that the <code>queen_of_hearts_...</code> variable represents a card.</li>
  508. <li>For the <code>_tuple</code> version, you need to remember the order of the attributes. Writing <code>('Spades', 'A')</code> will mess up your program but probably not give you an easily understandable error message.</li>
  509. <li>If you use the <code>_dict</code>, you must make sure the names of the attributes are consistent. For instance <code>{'value': 'A', 'suit': 'Spades'}</code> will not work as expected.</li>
  510. </ul>
  511. <p>Furthermore, using these structures is not ideal:</p>
  512. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts_tuple</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="c1"># No named access</span>
  513. <span class="go">'Q'</span>
  514. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts_dict</span><span class="p">[</span><span class="s1">'suit'</span><span class="p">]</span> <span class="c1"># Would be nicer with .suit</span>
  515. <span class="go">'Hearts'</span>
  516. </pre></div>
  517. <p>A better alternative is the <a href="https://dbader.org/blog/writing-clean-python-with-namedtuples"><code>namedtuple</code></a>. It has long been used to create readable small data structures. We can in fact recreate the data class example above using a <code>namedtuple</code> like this:</p>
  518. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">collections</span> <span class="kn">import</span> <span class="n">namedtuple</span>
  519. <span class="n">NamedTupleCard</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'NamedTupleCard'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'rank'</span><span class="p">,</span> <span class="s1">'suit'</span><span class="p">])</span>
  520. </pre></div>
  521. <p>This definition of <code>NamedTupleCard</code> will give the exact same output as our <code>DataClassCard</code> example did:</p>
  522. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">NamedTupleCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  523. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span><span class="o">.</span><span class="n">rank</span>
  524. <span class="go">'Q'</span>
  525. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span>
  526. <span class="go">NamedTupleCard(rank='Q', suit='Hearts')</span>
  527. <span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">==</span> <span class="n">NamedTupleCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  528. <span class="go">True</span>
  529. </pre></div>
  530. <p>So why even bother with data classes? First of all, data classes come with many more features than you have seen so far. At the same time, the <code>namedtuple</code> has some other features that are not necessarily desirable. By design, a <code>namedtuple</code> is a regular tuple. This can be seen in comparisons, for instance:</p>
  531. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">==</span> <span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  532. <span class="go">True</span>
  533. </pre></div>
  534. <p>While this might seem like a good thing, this lack of awareness about its own type can lead to subtle and hard-to-find bugs, especially since it will also happily compare two different <code>namedtuple</code> classes:</p>
  535. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Person</span> <span class="o">=</span> <span class="n">namedtuple</span><span class="p">(</span><span class="s1">'Person'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'first_initial'</span><span class="p">,</span> <span class="s1">'last_name'</span><span class="p">]</span>
  536. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">NamedTupleCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'Spades'</span><span class="p">)</span>
  537. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">==</span> <span class="n">Person</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'Spades'</span><span class="p">)</span>
  538. <span class="go">True</span>
  539. </pre></div>
  540. <p>The <code>namedtuple</code> also comes with some restrictions. For instance, it is hard to add default values to some of the fields in a <code>namedtuple</code>. A <code>namedtuple</code> is also by nature immutable. That is, the value of a <code>namedtuple</code> can never change. In some applications, this is an awesome feature, but in other settings, it would be nice to have more flexibility:</p>
  541. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">card</span> <span class="o">=</span> <span class="n">NamedTupleCard</span><span class="p">(</span><span class="s1">'7'</span><span class="p">,</span> <span class="s1">'Diamonds'</span><span class="p">)</span>
  542. <span class="gp">&gt;&gt;&gt; </span><span class="n">card</span><span class="o">.</span><span class="n">rank</span> <span class="o">=</span> <span class="s1">'9'</span>
  543. <span class="go">AttributeError: can't set attribute</span>
  544. </pre></div>
  545. <p>Data classes will not replace all uses of <code>namedtuple</code>. For instance, if you need your data structure to behave like a tuple, then a named tuple is a great alternative!</p>
  546. <p>Another alternative, and one of the <a href="https://mail.python.org/pipermail/python-dev/2017-December/151034.html">inspirations for data classes</a>, is the <a href="http://www.attrs.org"><code>attrs</code> project</a>. With <code>attrs</code> installed (<code>pip install attrs</code>), you can write a card class as follows:</p>
  547. <div class="highlight python"><pre><span/><span class="kn">import</span> <span class="nn">attr</span>
  548. <span class="nd">@attr.s</span>
  549. <span class="k">class</span> <span class="nc">AttrsCard</span><span class="p">:</span>
  550. <span class="n">rank</span> <span class="o">=</span> <span class="n">attr</span><span class="o">.</span><span class="n">ib</span><span class="p">()</span>
  551. <span class="n">suit</span> <span class="o">=</span> <span class="n">attr</span><span class="o">.</span><span class="n">ib</span><span class="p">()</span>
  552. </pre></div>
  553. <p>This can be used in exactly the same way as the <code>DataClassCard</code> and <code>NamedTupleCard</code> examples earlier. The <code>attrs</code> project is great and does support some features that data classes do not, including converters and validators. Furthermore, <code>attrs</code> has been around for a while and is supported in Python 2.7 as well as Python 3.4 and up. However, as <code>attrs</code> is not a part of the standard library, it does add an external dependency to your projects. Through data classes, similar functionality will be available everywhere.</p>
  554. <p>In addition to <code>tuple</code>, <code>dict</code>, <code>namedtuple</code>, and <code>attrs</code>, there are <a href="https://www.python.org/dev/peps/pep-0557/#rationale">many other similar projects</a>, including <a href="https://docs.python.org/library/typing.html#typing.NamedTuple"><code>typing.NamedTuple</code></a>, <a href="https://pypi.org/project/namedlist/"><code>namedlist</code></a>, <a href="https://pypi.org/project/attrdict/"><code>attrdict</code></a>, <a href="https://pypi.org/project/plumber/"><code>plumber</code></a>, and <a href="https://pypi.org/project/fields/"><code>fields</code></a>. While data classes are a great new alternative, there are still use cases where one of the older variants fits better. For instance, if you need compatibility with a specific API expecting tuples or need functionality not supported in data classes.</p>
  555. <h2 id="basic-data-classes">Basic Data Classes</h2>
  556. <p>Let us get back to data classes. As an example, we will create a <code>Position</code> class that will represent geographic positions with a name as well as the latitude and longitude:</p>
  557. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  558. <span class="nd">@dataclass</span>
  559. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  560. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  561. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span>
  562. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span>
  563. </pre></div>
  564. <p>What makes this a data class is the <a href="https://realpython.com/primer-on-python-decorators/"><code>@dataclass</code> decorator</a> just above the class definition. Beneath the <code>class Position:</code> line, you simply list the fields you want in your data class. The <code>:</code> notation used for the fields is using a new feature in Python 3.6 called <a href="https://www.python.org/dev/peps/pep-0526/">variable annotations</a>. We will <a href="#type-hints">soon</a> talk more about this notation and why we specify data types like <code>str</code> and <code>float</code>.</p>
  565. <p>Those few lines of code are all you need. The new class is ready for use:</p>
  566. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">pos</span> <span class="o">=</span> <span class="n">Position</span><span class="p">(</span><span class="s1">'Oslo'</span><span class="p">,</span> <span class="mf">10.8</span><span class="p">,</span> <span class="mf">59.9</span><span class="p">)</span>
  567. <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">pos</span><span class="p">)</span>
  568. <span class="go">Position(name='Oslo', lon=10.8, lat=59.9)</span>
  569. <span class="gp">&gt;&gt;&gt; </span><span class="n">pos</span><span class="o">.</span><span class="n">lat</span>
  570. <span class="go">59.9</span>
  571. <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">f</span><span class="s1">'{pos.name} is at {pos.lat}°N, {pos.lon}°E'</span><span class="p">)</span>
  572. <span class="go">Oslo is at 59.9°N, 10.8°E</span>
  573. </pre></div>
  574. <p>You can also create data classes similarly to how named tuples are created. The following is (almost) equivalent to the definition of <code>Position</code> above:</p>
  575. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">make_dataclass</span>
  576. <span class="n">Position</span> <span class="o">=</span> <span class="n">make_dataclass</span><span class="p">(</span><span class="s1">'Position'</span><span class="p">,</span> <span class="p">[</span><span class="s1">'name'</span><span class="p">,</span> <span class="s1">'lat'</span><span class="p">,</span> <span class="s1">'lon'</span><span class="p">])</span>
  577. </pre></div>
  578. <p>A data class is a regular Python class. The only thing that sets it apart is that it has basic <a href="https://docs.python.org/reference/datamodel.html#basic-customization">data model methods</a> like <code>.__init__()</code>, <code>.__repr__()</code>, and <code>.__eq__()</code> implemented for you.</p>
  579. <h3 id="default-values">Default Values</h3>
  580. <p>It is easy to add default values to the fields of your data class:</p>
  581. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  582. <span class="nd">@dataclass</span>
  583. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  584. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  585. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  586. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  587. </pre></div>
  588. <p>This works exactly as if you had specified the default values in the definition of the <code>.__init__()</code> method of a regular class:</p>
  589. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Position</span><span class="p">(</span><span class="s1">'Null Island'</span><span class="p">)</span>
  590. <span class="go">Position(name='Null Island', lon=0.0, lat=0.0)</span>
  591. <span class="gp">&gt;&gt;&gt; </span><span class="n">Position</span><span class="p">(</span><span class="s1">'Greenwich'</span><span class="p">,</span> <span class="n">lat</span><span class="o">=</span><span class="mf">51.8</span><span class="p">)</span>
  592. <span class="go">Position(name='Greenwich', lon=0.0, lat=51.8)</span>
  593. <span class="gp">&gt;&gt;&gt; </span><span class="n">Position</span><span class="p">(</span><span class="s1">'Vancouver'</span><span class="p">,</span> <span class="o">-</span><span class="mf">123.1</span><span class="p">,</span> <span class="mf">49.3</span><span class="p">)</span>
  594. <span class="go">Position(name='Vancouver', lon=-123.1, lat=49.3)</span>
  595. </pre></div>
  596. <p><a href="#advanced-default-values">Later</a> you will learn about <code>default_factory</code>, which gives a way to provide more complicated default values.</p>
  597. <h3 id="type-hints">Type Hints</h3>
  598. <p>So far, we have not made a big fuss of the fact that data classes support <a href="https://www.youtube.com/watch?v=2xWhaALHTvU">typing</a> out of the box. You have probably noticed that we defined the fields with a type hint: <code>name: str</code> says that <code>name</code> should be a text string (<code>str</code> type).</p>
  599. <p>In fact, adding some kind of type hint is mandatory when defining the fields in your data class. Without a type hint, the field will not be a part of the data class. However, if you do not want to add explicit types to your data class, use <code>typing.Any</code>:</p>
  600. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  601. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">Any</span>
  602. <span class="nd">@dataclass</span>
  603. <span class="k">class</span> <span class="nc">WithoutExplicitTypes</span><span class="p">:</span>
  604. <span class="n">name</span><span class="p">:</span> <span class="n">Any</span>
  605. <span class="n">value</span><span class="p">:</span> <span class="n">Any</span> <span class="o">=</span> <span class="mi">42</span>
  606. </pre></div>
  607. <p>While you need to add type hints in some form when using data classes, these types are not enforced at runtime. The following code runs without any problems:</p>
  608. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Position</span><span class="p">(</span><span class="mf">3.14</span><span class="p">,</span> <span class="s1">'pi day'</span><span class="p">,</span> <span class="mi">2018</span><span class="p">)</span>
  609. <span class="go">Position(name=3.14, lon='pi day', lat=2018)</span>
  610. </pre></div>
  611. <p>This is how typing in Python usually works: <a href="https://www.python.org/dev/peps/pep-0484/#non-goals">Python is and will always be a dynamically typed language</a>. To actually catch type errors, type checkers like <a href="http://mypy-lang.org">Mypy</a> can be run on your source code.</p>
  612. <h3 id="adding-methods">Adding Methods</h3>
  613. <p>You already know that a data class is just a regular class. That means that you can freely add your own methods to a data class. As an example, let us calculate the distance between one position and another, along the Earth’s surface. One way to do this is by using <a href="https://en.wikipedia.org/wiki/Haversine_formula">the haversine formula</a>:</p>
  614. <p><a href="https://files.realpython.com/media/haversine_formula_150.fb2b87d122a4.png"><img class="img-fluid mb-3 mx-auto d-block" src="https://files.realpython.com/media/haversine_formula_150.fb2b87d122a4.png" alt="The haversine formula"/></a></p>
  615. <p>You can add a <code>.distance_to()</code> method to your data class just like you can with normal classes:</p>
  616. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  617. <span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">asin</span><span class="p">,</span> <span class="n">cos</span><span class="p">,</span> <span class="n">radians</span><span class="p">,</span> <span class="n">sin</span><span class="p">,</span> <span class="n">sqrt</span>
  618. <span class="nd">@dataclass</span>
  619. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  620. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  621. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  622. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  623. <span class="k">def</span> <span class="nf">distance_to</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">other</span><span class="p">):</span>
  624. <span class="n">r</span> <span class="o">=</span> <span class="mi">6371</span> <span class="c1"># Earth radius in kilometers</span>
  625. <span class="n">lam_1</span><span class="p">,</span> <span class="n">lam_2</span> <span class="o">=</span> <span class="n">radians</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lon</span><span class="p">),</span> <span class="n">radians</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">lon</span><span class="p">)</span>
  626. <span class="n">phi_1</span><span class="p">,</span> <span class="n">phi_2</span> <span class="o">=</span> <span class="n">radians</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">lat</span><span class="p">),</span> <span class="n">radians</span><span class="p">(</span><span class="n">other</span><span class="o">.</span><span class="n">lat</span><span class="p">)</span>
  627. <span class="n">h</span> <span class="o">=</span> <span class="p">(</span><span class="n">sin</span><span class="p">((</span><span class="n">phi_2</span> <span class="o">-</span> <span class="n">phi_1</span><span class="p">)</span> <span class="o">/</span> <span class="mi">2</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span>
  628. <span class="o">+</span> <span class="n">cos</span><span class="p">(</span><span class="n">phi_1</span><span class="p">)</span> <span class="o">*</span> <span class="n">cos</span><span class="p">(</span><span class="n">phi_2</span><span class="p">)</span> <span class="o">*</span> <span class="n">sin</span><span class="p">((</span><span class="n">lam_2</span> <span class="o">-</span> <span class="n">lam_1</span><span class="p">)</span> <span class="o">/</span> <span class="mi">2</span><span class="p">)</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
  629. <span class="k">return</span> <span class="mi">2</span> <span class="o">*</span> <span class="n">r</span> <span class="o">*</span> <span class="n">asin</span><span class="p">(</span><span class="n">sqrt</span><span class="p">(</span><span class="n">h</span><span class="p">))</span>
  630. </pre></div>
  631. <p>It works as you would expect:</p>
  632. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">oslo</span> <span class="o">=</span> <span class="n">Position</span><span class="p">(</span><span class="s1">'Oslo'</span><span class="p">,</span> <span class="mf">10.8</span><span class="p">,</span> <span class="mf">59.9</span><span class="p">)</span>
  633. <span class="gp">&gt;&gt;&gt; </span><span class="n">vancouver</span> <span class="o">=</span> <span class="n">Position</span><span class="p">(</span><span class="s1">'Vancouver'</span><span class="p">,</span> <span class="o">-</span><span class="mf">123.1</span><span class="p">,</span> <span class="mf">49.3</span><span class="p">)</span>
  634. <span class="gp">&gt;&gt;&gt; </span><span class="n">oslo</span><span class="o">.</span><span class="n">distance_to</span><span class="p">(</span><span class="n">vancouver</span><span class="p">)</span>
  635. <span class="go">7181.7841229421165</span>
  636. </pre></div>
  637. <h2 id="more-flexible-data-classes">More Flexible Data Classes</h2>
  638. <p>So far, you have seen some of the basic features of the data class: it gives you some convenience methods, and you can still add default values and other methods. Now you will learn about some more advanced features like parameters to the <code>@dataclass</code> decorator and the <code>field()</code> function. Together, they give you more control when creating a data class.</p>
  639. <p>Let us return to the playing card example you saw at the beginning of the tutorial and add a class containing a deck of cards while we are at it:</p>
  640. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  641. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
  642. <span class="nd">@dataclass</span>
  643. <span class="k">class</span> <span class="nc">PlayingCard</span><span class="p">:</span>
  644. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  645. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  646. <span class="nd">@dataclass</span>
  647. <span class="k">class</span> <span class="nc">Deck</span><span class="p">:</span>
  648. <span class="n">cards</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">PlayingCard</span><span class="p">]</span>
  649. </pre></div>
  650. <p>A simple deck containing only two cards can be created like this:</p>
  651. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'Hearts'</span><span class="p">)</span>
  652. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'Spades'</span><span class="p">)</span>
  653. <span class="gp">&gt;&gt;&gt; </span><span class="n">two_cards</span> <span class="o">=</span> <span class="n">Deck</span><span class="p">([</span><span class="n">queen_of_hearts</span><span class="p">,</span> <span class="n">ace_of_spades</span><span class="p">])</span>
  654. <span class="go">Deck(cards=[PlayingCard(rank='Q', suit='Hearts'),</span>
  655. <span class="go"> PlayingCard(rank='A', suit='Spades')])</span>
  656. </pre></div>
  657. <h3 id="advanced-default-values">Advanced Default Values</h3>
  658. <p>Say that you want to give a default value to the <code>Deck</code>. It would for example be convenient if <code>Deck()</code> created a <a href="https://en.wikipedia.org/wiki/French_playing_cards">regular (French) deck</a> of 52 playing cards. First, specify the different ranks and suits. Then, add a function <code>make_french_deck()</code> that creates a list of instances of <code>PlayingCard</code>:</p>
  659. <div class="highlight python"><pre><span/><span class="n">RANKS</span> <span class="o">=</span> <span class="s1">'2 3 4 5 6 7 8 9 10 J Q K A'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  660. <span class="n">SUITS</span> <span class="o">=</span> <span class="s1">'♣ ♢ ♡ ♠'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  661. <span class="k">def</span> <span class="nf">make_french_deck</span><span class="p">():</span>
  662. <span class="k">return</span> <span class="p">[</span><span class="n">PlayingCard</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">s</span><span class="p">)</span> <span class="k">for</span> <span class="n">s</span> <span class="ow">in</span> <span class="n">SUITS</span> <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">RANKS</span><span class="p">]</span>
  663. </pre></div>
  664. <p>For fun, the four different suits are specified using their <a href="https://en.wikipedia.org/wiki/Playing_cards_in_Unicode">Unicode symbols</a>.</p>
  665. <blockquote>
  666. <p><strong>Note:</strong> Above, we used Unicode glyphs like <code>♠</code> directly in the source code. We could do this because <a href="https://docs.python.org/howto/unicode.html#unicode-literals-in-python-source-code">Python supports writing source code in UTF-8 by default</a>. Refer to <a href="https://en.wikipedia.org/wiki/Unicode_input">this page on Unicode input</a> for how to enter these on your system. You could also enter the Unicode symbols for the suits using <code>\N</code> named character escapes (like <code>\N{BLACK SPADE SUIT}</code>) or <code>\u</code> Unicode escapes (like <code>\u2660</code>).</p>
  667. </blockquote>
  668. <p>To simplify comparisons of cards later, the ranks and suits are also listed in their usual order.</p>
  669. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">make_french_deck</span><span class="p">()</span>
  670. <span class="go">[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ...</span>
  671. <span class="go"> PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')]</span>
  672. </pre></div>
  673. <p>In theory, you could now use this function to specify a default value for <code>Deck.cards</code>:</p>
  674. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  675. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
  676. <span class="nd">@dataclass</span>
  677. <span class="k">class</span> <span class="nc">Deck</span><span class="p">:</span> <span class="c1"># Will NOT work</span>
  678. <span class="n">cards</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">PlayingCard</span><span class="p">]</span> <span class="o">=</span> <span class="n">make_french_deck</span><span class="p">()</span>
  679. </pre></div>
  680. <p>Don’t do this! This introduces one of the most common anti-patterns in Python: <a href="http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments">using mutable default arguments</a>. The problem is that all instances of <code>Deck</code> will use the same list object as the default value of the <code>.cards</code> property. This means that if, say, one card is removed from one <code>Deck</code>, then it disappears from all other instances of <code>Deck</code> as well. Actually, data classes try to <a href="https://www.python.org/dev/peps/pep-0557/#mutable-default-values">prevent you from doing this</a>, and the code above will raise a <code>ValueError</code>.</p>
  681. <p>Instead, data classes use something called a <code>default_factory</code> to handle mutable default values. To use <code>default_factory</code> (and many other cool features of data classes), you need to use the <code>field()</code> specifier:</p>
  682. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span><span class="p">,</span> <span class="n">field</span>
  683. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
  684. <span class="nd">@dataclass</span>
  685. <span class="k">class</span> <span class="nc">Deck</span><span class="p">:</span>
  686. <span class="n">cards</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">PlayingCard</span><span class="p">]</span> <span class="o">=</span> <span class="n">field</span><span class="p">(</span><span class="n">default_factory</span><span class="o">=</span><span class="n">make_french_deck</span><span class="p">)</span>
  687. </pre></div>
  688. <p>The argument to <code>default_factory</code> can be any zero parameter callable. Now it is easy to create a full deck of playing cards:</p>
  689. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Deck</span><span class="p">()</span>
  690. <span class="go">Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ...</span>
  691. <span class="go"> PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')])</span>
  692. </pre></div>
  693. <p>The <code>field()</code> specifier is used to customize each field of a data class individually. You will see some other examples later. For reference, these are the parameters <code>field()</code> supports:</p>
  694. <ul>
  695. <li><code>default</code>: Default value of the field</li>
  696. <li><code>default_factory</code>: Function that returns the initial value of the field</li>
  697. <li><code>init</code>: Use field in <code>.__init__()</code> method? (Default is <code>True</code>.)</li>
  698. <li><code>repr</code>: Use field in <code>repr</code> of the object? (Default is <code>True</code>.)</li>
  699. <li><code>compare</code>: Include the field in comparisons? (Default is <code>True</code>.)</li>
  700. <li><code>hash</code>: Include the field when calculating <code>hash()</code>? (Default is to use the same as for <code>compare</code>.)</li>
  701. <li><code>metadata</code>: A mapping with information about the field</li>
  702. </ul>
  703. <p>In the <code>Position</code> example, you saw how to add simple default values by writing <code>lat: float = 0.0</code>. However, if you also want to customize the field, for instance to hide it in the <code>repr</code>, you need to use the <code>default</code> parameter: <code>lat: float = field(default=0.0, repr=False)</code>. You may not specify both <code>default</code> and <code>default_factory</code>.</p>
  704. <p>The <code>metadata</code> parameter is not used by the data classes themselves but is available for you (or third party packages) to attach information to fields. In the <code>Position</code> example, you could for instance specify that latitude and longitude should be given in degrees:</p>
  705. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span><span class="p">,</span> <span class="n">field</span>
  706. <span class="nd">@dataclass</span>
  707. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  708. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  709. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="n">field</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mf">0.0</span><span class="p">,</span> <span class="n">metadata</span><span class="o">=</span><span class="p">{</span><span class="s1">'unit'</span><span class="p">:</span> <span class="s1">'degrees'</span><span class="p">})</span>
  710. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="n">field</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mf">0.0</span><span class="p">,</span> <span class="n">metadata</span><span class="o">=</span><span class="p">{</span><span class="s1">'unit'</span><span class="p">:</span> <span class="s1">'degrees'</span><span class="p">})</span>
  711. </pre></div>
  712. <p>The metadata (and other information about a field) can be retrieved using the <code>fields()</code> function (note the plural <em>s</em>):</p>
  713. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">fields</span>
  714. <span class="gp">&gt;&gt;&gt; </span><span class="n">fields</span><span class="p">(</span><span class="n">Position</span><span class="p">)</span>
  715. <span class="go">(Field(name='name',type=&lt;class 'str'&gt;,...,metadata={}),</span>
  716. <span class="go"> Field(name='lon',type=&lt;class 'float'&gt;,...,metadata={'unit': 'degrees'}),</span>
  717. <span class="go"> Field(name='lat',type=&lt;class 'float'&gt;,...,metadata={'unit': 'degrees'}))</span>
  718. <span class="gp">&gt;&gt;&gt; </span><span class="n">lat_unit</span> <span class="o">=</span> <span class="n">fields</span><span class="p">(</span><span class="n">Position</span><span class="p">)[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">metadata</span><span class="p">[</span><span class="s1">'unit'</span><span class="p">]</span>
  719. <span class="gp">&gt;&gt;&gt; </span><span class="n">lat_unit</span>
  720. <span class="go">'degrees'</span>
  721. </pre></div>
  722. <h3 id="you-need-representation">You Need Representation?</h3>
  723. <p>Recall that we can create decks of cards out of thin air:</p>
  724. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Deck</span><span class="p">()</span>
  725. <span class="go">Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ...</span>
  726. <span class="go"> PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')])</span>
  727. </pre></div>
  728. <p>While this representation of a <code>Deck</code> is explicit and readable, it is also very verbose. I have deleted 48 of the 52 cards in the deck in the output above. On an 80-column display, simply printing the full <code>Deck</code> takes up 22 lines! Let us add a more concise representation. In general, a Python object has <a href="https://dbader.org/blog/python-repr-vs-str">two different string representations</a>:</p>
  729. <ul>
  730. <li>
  731. <p><code>repr(obj)</code> is defined by <code>obj.__repr__()</code> and should return a developer-friendly representation of <code>obj</code>. If possible, this should be code that can recreate <code>obj</code>. Data classes do this.</p>
  732. </li>
  733. <li>
  734. <p><code>str(obj)</code> is defined by <code>obj.__str__()</code> and should return a user-friendly representation of <code>obj</code>. Data classes do not implement a <code>.__str__()</code> method, so Python will fall back to the <code>.__repr__()</code> method.</p>
  735. </li>
  736. </ul>
  737. <p>Let us implement a user-friendly representation of a <code>PlayingCard</code>:</p>
  738. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  739. <span class="nd">@dataclass</span>
  740. <span class="k">class</span> <span class="nc">PlayingCard</span><span class="p">:</span>
  741. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  742. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  743. <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  744. <span class="k">return</span> <span class="n">f</span><span class="s1">'{self.suit}{self.rank}'</span>
  745. </pre></div>
  746. <p>The cards now look much nicer, but the deck is still as verbose as ever:</p>
  747. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span>
  748. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span>
  749. <span class="go">PlayingCard(rank='A', suit='♠')</span>
  750. <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">ace_of_spades</span><span class="p">)</span>
  751. <span class="go">♠A</span>
  752. <span class="gp">&gt;&gt;&gt; </span><span class="k">print</span><span class="p">(</span><span class="n">Deck</span><span class="p">())</span>
  753. <span class="go">Deck(cards=[PlayingCard(rank='2', suit='♣'), PlayingCard(rank='3', suit='♣'), ...</span>
  754. <span class="go"> PlayingCard(rank='K', suit='♠'), PlayingCard(rank='A', suit='♠')])</span>
  755. </pre></div>
  756. <p>To show that it is possible to add your own <code>.__repr__()</code> method as well, we will violate the principle that it should return code that can recreate an object. <a href="https://www.python.org/dev/peps/pep-0020/">Practicality beats purity</a> after all. The following code adds a more concise representation of the <code>Deck</code>:</p>
  757. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span><span class="p">,</span> <span class="n">field</span>
  758. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
  759. <span class="nd">@dataclass</span>
  760. <span class="k">class</span> <span class="nc">Deck</span><span class="p">:</span>
  761. <span class="n">cards</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">PlayingCard</span><span class="p">]</span> <span class="o">=</span> <span class="n">field</span><span class="p">(</span><span class="n">default_factory</span><span class="o">=</span><span class="n">make_french_deck</span><span class="p">)</span>
  762. <span class="k">def</span> <span class="fm">__repr__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  763. <span class="n">cards</span> <span class="o">=</span> <span class="s1">', '</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">f</span><span class="s1">'{c!s}'</span> <span class="k">for</span> <span class="n">c</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">cards</span><span class="p">)</span>
  764. <span class="k">return</span> <span class="n">f</span><span class="s1">'{self.__class__.__name__}({cards})'</span>
  765. </pre></div>
  766. <p>Note the <code>!s</code> specifier in the <code>{c!s}</code> format string. It means that we explicitly want to use the <code>str()</code> representation of <code>PlayingCard</code>s. With the new <code>.__repr__()</code>, the representation of <code>Deck</code> is easier on the eyes:</p>
  767. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Deck</span><span class="p">()</span>
  768. <span class="go">Deck(♣2, ♣3, ♣4, ♣5, ♣6, ♣7, ♣8, ♣9, ♣10, ♣J, ♣Q, ♣K, ♣A,</span>
  769. <span class="go"> ♢2, ♢3, ♢4, ♢5, ♢6, ♢7, ♢8, ♢9, ♢10, ♢J, ♢Q, ♢K, ♢A,</span>
  770. <span class="go"> ♡2, ♡3, ♡4, ♡5, ♡6, ♡7, ♡8, ♡9, ♡10, ♡J, ♡Q, ♡K, ♡A,</span>
  771. <span class="go"> ♠2, ♠3, ♠4, ♠5, ♠6, ♠7, ♠8, ♠9, ♠10, ♠J, ♠Q, ♠K, ♠A)</span>
  772. </pre></div>
  773. <h3 id="comparing-cards">Comparing Cards</h3>
  774. <p>In many card games, cards are compared to each other. For instance in a typical trick taking game, the highest card takes the trick. As it is currently implemented, the <code>PlayingCard</code> class does not support this kind of comparison:</p>
  775. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  776. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span>
  777. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">&gt;</span> <span class="n">queen_of_hearts</span>
  778. <span class="go">TypeError: '&gt;' not supported between instances of 'Card' and 'Card'</span>
  779. </pre></div>
  780. <p>This is, however, (seemingly) easy to rectify:</p>
  781. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  782. <span class="nd">@dataclass</span><span class="p">(</span><span class="n">order</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  783. <span class="k">class</span> <span class="nc">PlayingCard</span><span class="p">:</span>
  784. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  785. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  786. <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  787. <span class="k">return</span> <span class="n">f</span><span class="s1">'{self.suit}{self.rank}'</span>
  788. </pre></div>
  789. <p>The <code>@dataclass</code> decorator has two forms. So far you have seen the simple form where <code>@dataclass</code> is specified without any parentheses and parameters. However, you can also give parameters to the <code>@dataclass()</code> decorator in parentheses. The following parameters are supported:</p>
  790. <ul>
  791. <li><code>init</code>: Add <code>.__init__()</code> method? (Default is <code>True</code>.)</li>
  792. <li><code>repr</code>: Add <code>.__repr__()</code> method? (Default is <code>True</code>.)</li>
  793. <li><code>eq</code>: Add <code>.__eq__()</code> method? (Default is <code>True</code>.)</li>
  794. <li><code>order</code>: Add ordering methods? (Default is <code>False</code>.)</li>
  795. <li><code>unsafe_hash</code>: Force the addition of a <code>.__hash__()</code> method? (Default is <code>False</code>.)</li>
  796. <li><code>frozen</code>: If <code>True</code>, assigning to fields raise an exception. (Default is <code>False</code>.)</li>
  797. </ul>
  798. <p>See <a href="https://www.python.org/dev/peps/pep-0557/#id7">the original PEP</a> for more information about each parameter. After setting <code>order=True</code>, instances of <code>PlayingCard</code> can be compared:</p>
  799. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  800. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span>
  801. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">&gt;</span> <span class="n">queen_of_hearts</span>
  802. <span class="go">False</span>
  803. </pre></div>
  804. <p>How are the two cards compared though? You have not specified how the ordering should be done, and for some reason Python seems to believe that a Queen is higher than an Ace…</p>
  805. <p>It turns out that data classes compare objects as if they were tuples of their fields. In other words, a Queen is higher than an Ace because <code>'Q'</code> comes after <code>'A'</code> in the alphabet:</p>
  806. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span> <span class="o">&gt;</span> <span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  807. <span class="go">False</span>
  808. </pre></div>
  809. <p>That does not really work for us. Instead, we need to define some kind of sort index that uses the order of <code>RANKS</code> and <code>SUITS</code>. Something like this:</p>
  810. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">RANKS</span> <span class="o">=</span> <span class="s1">'2 3 4 5 6 7 8 9 10 J Q K A'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  811. <span class="gp">&gt;&gt;&gt; </span><span class="n">SUITS</span> <span class="o">=</span> <span class="s1">'♣ ♢ ♡ ♠'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  812. <span class="gp">&gt;&gt;&gt; </span><span class="n">card</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  813. <span class="gp">&gt;&gt;&gt; </span><span class="n">RANKS</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">card</span><span class="o">.</span><span class="n">rank</span><span class="p">)</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">SUITS</span><span class="p">)</span> <span class="o">+</span> <span class="n">SUITS</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="n">card</span><span class="o">.</span><span class="n">suit</span><span class="p">)</span>
  814. <span class="go">42</span>
  815. </pre></div>
  816. <p>For <code>PlayingCard</code> to use this sort index for comparisons, we need to add a field <code>.sort_index</code> to the class. However, this field should be calculated from the other fields <code>.rank</code> and <code>.suit</code> automatically. This is exactly what the special method <code>.__post_init__()</code> is for. It allows for special processing after the regular <code>.__init__()</code> method is called:</p>
  817. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span><span class="p">,</span> <span class="n">field</span>
  818. <span class="n">RANKS</span> <span class="o">=</span> <span class="s1">'2 3 4 5 6 7 8 9 10 J Q K A'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  819. <span class="n">SUITS</span> <span class="o">=</span> <span class="s1">'♣ ♢ ♡ ♠'</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
  820. <span class="nd">@dataclass</span><span class="p">(</span><span class="n">order</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  821. <span class="k">class</span> <span class="nc">PlayingCard</span><span class="p">:</span>
  822. <span class="n">sort_index</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="n">field</span><span class="p">(</span><span class="n">init</span><span class="o">=</span><span class="bp">False</span><span class="p">,</span> <span class="nb">repr</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
  823. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  824. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  825. <span class="k">def</span> <span class="nf">__post_init__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  826. <span class="bp">self</span><span class="o">.</span><span class="n">sort_index</span> <span class="o">=</span> <span class="p">(</span><span class="n">RANKS</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">rank</span><span class="p">)</span> <span class="o">*</span> <span class="nb">len</span><span class="p">(</span><span class="n">SUITS</span><span class="p">)</span>
  827. <span class="o">+</span> <span class="n">SUITS</span><span class="o">.</span><span class="n">index</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">suit</span><span class="p">))</span>
  828. <span class="k">def</span> <span class="fm">__str__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
  829. <span class="k">return</span> <span class="n">f</span><span class="s1">'{self.suit}{self.rank}'</span>
  830. </pre></div>
  831. <p>Note that <code>.sort_index</code> is added as the first field of the class. That way, the comparison is first done using <code>.sort_index</code> and only if there are ties are the other fields used. Using <code>field()</code>, you must also specify that <code>.sort_index</code> should not be included as a parameter in the <code>.__init__()</code> method (because it is calculated from the <code>.rank</code> and <code>.suit</code> fields). To avoid confusing the user about this implementation detail, it is probably also a good idea to remove <code>.sort_index</code> from the <code>repr</code> of the class.</p>
  832. <p>Finally, aces are high:</p>
  833. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  834. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">PlayingCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span>
  835. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">&gt;</span> <span class="n">queen_of_hearts</span>
  836. <span class="go">True</span>
  837. </pre></div>
  838. <p>You can now easily create a sorted deck:</p>
  839. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Deck</span><span class="p">(</span><span class="nb">sorted</span><span class="p">(</span><span class="n">make_french_deck</span><span class="p">()))</span>
  840. <span class="go">Deck(♣2, ♢2, ♡2, ♠2, ♣3, ♢3, ♡3, ♠3, ♣4, ♢4, ♡4, ♠4, ♣5,</span>
  841. <span class="go"> ♢5, ♡5, ♠5, ♣6, ♢6, ♡6, ♠6, ♣7, ♢7, ♡7, ♠7, ♣8, ♢8,</span>
  842. <span class="go"> ♡8, ♠8, ♣9, ♢9, ♡9, ♠9, ♣10, ♢10, ♡10, ♠10, ♣J, ♢J, ♡J,</span>
  843. <span class="go"> ♠J, ♣Q, ♢Q, ♡Q, ♠Q, ♣K, ♢K, ♡K, ♠K, ♣A, ♢A, ♡A, ♠A)</span>
  844. </pre></div>
  845. <p>Or, if you don’t care about sorting, this is how you draw a random hand of 10 cards:</p>
  846. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">random</span> <span class="kn">import</span> <span class="n">sample</span>
  847. <span class="gp">&gt;&gt;&gt; </span><span class="n">Deck</span><span class="p">(</span><span class="n">sample</span><span class="p">(</span><span class="n">make_french_deck</span><span class="p">(),</span> <span class="n">k</span><span class="o">=</span><span class="mi">10</span><span class="p">))</span>
  848. <span class="go">Deck(♢2, ♡A, ♢10, ♣2, ♢3, ♠3, ♢A, ♠8, ♠9, ♠2)</span>
  849. </pre></div>
  850. <p>Of course, you don’t need <code>order=True</code> for that…</p>
  851. <h2 id="immutable-data-classes">Immutable Data Classes</h2>
  852. <p>One of the defining features of the <code>namedtuple</code> you saw earlier is that it is <a href="https://medium.com/@meghamohan/mutable-and-immutable-side-of-python-c2145cf72747">immutable</a>. That is, the value of its fields may never change. For many types of data classes, this is a great idea! To make a data class immutable, set <code>frozen=True</code> when you create it. For example, the following is an immutable version of the <code>Position</code> class <a href="#basic-data-classes">you saw earlier</a>:</p>
  853. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  854. <span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  855. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  856. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  857. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  858. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  859. </pre></div>
  860. <p>In a frozen data class, you can not assign values to the fields after creation:</p>
  861. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">pos</span> <span class="o">=</span> <span class="n">Position</span><span class="p">(</span><span class="s1">'Oslo'</span><span class="p">,</span> <span class="mf">10.8</span><span class="p">,</span> <span class="mf">59.9</span><span class="p">)</span>
  862. <span class="gp">&gt;&gt;&gt; </span><span class="n">pos</span><span class="o">.</span><span class="n">name</span>
  863. <span class="go">'Oslo'</span>
  864. <span class="gp">&gt;&gt;&gt; </span><span class="n">pos</span><span class="o">.</span><span class="n">name</span> <span class="o">=</span> <span class="s1">'Stockholm'</span>
  865. <span class="go">dataclasses.FrozenInstanceError: cannot assign to field 'name'</span>
  866. </pre></div>
  867. <p>Be aware though that if your data class contains mutable fields, those might still change. This is true for all nested data structures in Python (see <a href="https://www.youtube.com/watch?v=p9ppfvHv2Us">this video for further info</a>):</p>
  868. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  869. <span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">List</span>
  870. <span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  871. <span class="k">class</span> <span class="nc">ImmutableCard</span><span class="p">:</span>
  872. <span class="n">rank</span><span class="p">:</span> <span class="nb">str</span>
  873. <span class="n">suit</span><span class="p">:</span> <span class="nb">str</span>
  874. <span class="nd">@dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  875. <span class="k">class</span> <span class="nc">ImmutableDeck</span><span class="p">:</span>
  876. <span class="n">cards</span><span class="p">:</span> <span class="n">List</span><span class="p">[</span><span class="n">PlayingCard</span><span class="p">]</span>
  877. </pre></div>
  878. <p>Even though both <code>ImmutableCard</code> and <code>ImmutableDeck</code> are immutable, the list holding <code>cards</code> is not. You can therefore still change the cards in the deck:</p>
  879. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">queen_of_hearts</span> <span class="o">=</span> <span class="n">ImmutableCard</span><span class="p">(</span><span class="s1">'Q'</span><span class="p">,</span> <span class="s1">'♡'</span><span class="p">)</span>
  880. <span class="gp">&gt;&gt;&gt; </span><span class="n">ace_of_spades</span> <span class="o">=</span> <span class="n">ImmutableCard</span><span class="p">(</span><span class="s1">'A'</span><span class="p">,</span> <span class="s1">'♠'</span><span class="p">)</span>
  881. <span class="gp">&gt;&gt;&gt; </span><span class="n">deck</span> <span class="o">=</span> <span class="n">ImmutableDeck</span><span class="p">([</span><span class="n">queen_of_hearts</span><span class="p">,</span> <span class="n">ace_of_spades</span><span class="p">])</span>
  882. <span class="gp">&gt;&gt;&gt; </span><span class="n">deck</span>
  883. <span class="go">ImmutableDeck(cards=[ImmutableCard(rank='Q', suit='♡'), ImmutableCard(rank='A', suit='♠')])</span>
  884. <span class="gp">&gt;&gt;&gt; </span><span class="n">deck</span><span class="o">.</span><span class="n">cards</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">ImmutableCard</span><span class="p">(</span><span class="s1">'7'</span><span class="p">,</span> <span class="s1">'♢'</span><span class="p">)</span>
  885. <span class="gp">&gt;&gt;&gt; </span><span class="n">deck</span>
  886. <span class="go">ImmutableDeck(cards=[ImmutableCard(rank='7', suit='♢'), ImmutableCard(rank='A', suit='♠')])</span>
  887. </pre></div>
  888. <p>To avoid this, make sure all fields of an immutable data class use immutable types (but remember that types are not enforced at runtime). The <code>ImmutableDeck</code> should be implemented using a tuple instead of a list.</p>
  889. <h2 id="inheritance">Inheritance</h2>
  890. <p>You can <a href="https://realpython.com/python3-object-oriented-programming/">subclass</a> data classes quite freely. As an example, we will extend our <code>Position</code> example with a <code>country</code> field and use it to record capitals:</p>
  891. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  892. <span class="nd">@dataclass</span>
  893. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  894. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  895. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span>
  896. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span>
  897. <span class="nd">@dataclass</span>
  898. <span class="k">class</span> <span class="nc">Capital</span><span class="p">(</span><span class="n">Position</span><span class="p">):</span>
  899. <span class="n">country</span><span class="p">:</span> <span class="nb">str</span>
  900. </pre></div>
  901. <p>In this simple example, everything works without a hitch:</p>
  902. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Capital</span><span class="p">(</span><span class="s1">'Oslo'</span><span class="p">,</span> <span class="mf">10.8</span><span class="p">,</span> <span class="mf">59.9</span><span class="p">,</span> <span class="s1">'Norway'</span><span class="p">)</span>
  903. <span class="go">Capital(name='Oslo', lon=10.8, lat=59.9, country='Norway')</span>
  904. </pre></div>
  905. <p>The <code>country</code> field of <code>Capital</code> is added after the three original fields in <code>Position</code>. Things get a little more complicated if any fields in the base class have default values:</p>
  906. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  907. <span class="nd">@dataclass</span>
  908. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  909. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  910. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  911. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  912. <span class="nd">@dataclass</span>
  913. <span class="k">class</span> <span class="nc">Capital</span><span class="p">(</span><span class="n">Position</span><span class="p">):</span>
  914. <span class="n">country</span><span class="p">:</span> <span class="nb">str</span> <span class="c1"># Does NOT work</span>
  915. </pre></div>
  916. <p>This code will immediately crash with a <code>TypeError</code> complaining that “non-default argument ‘country’ follows default argument.” The problem is that our new <code>country</code> field has no default value, while the <code>lon</code> and <code>lat</code> fields have default values. The data class will try to write an <code>.__init__()</code> method with the following signature:</p>
  917. <div class="highlight python"><pre><span/><span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="n">name</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">,</span> <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span><span class="p">,</span> <span class="n">country</span><span class="p">:</span> <span class="nb">str</span><span class="p">):</span>
  918. <span class="o">...</span>
  919. </pre></div>
  920. <p>However, this is not valid Python. <a href="https://docs.python.org/reference/compound_stmts.html#function-definitions">If a parameter has a default value, all following parameters must also have a default value</a>. In other words, if a field in a base class has a default value, then all new fields added in a subclass must have default values as well.</p>
  921. <p>Another thing to be aware of is how fields are ordered in a subclass. Starting with the base class, fields are ordered in the order in which they are first defined. If a field is redefined in a subclass, its order does not change. For example, if you define <code>Position</code> and <code>Capital</code> as follows:</p>
  922. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  923. <span class="nd">@dataclass</span>
  924. <span class="k">class</span> <span class="nc">Position</span><span class="p">:</span>
  925. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  926. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  927. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">0.0</span>
  928. <span class="nd">@dataclass</span>
  929. <span class="k">class</span> <span class="nc">Capital</span><span class="p">(</span><span class="n">Position</span><span class="p">):</span>
  930. <span class="n">country</span><span class="p">:</span> <span class="nb">str</span> <span class="o">=</span> <span class="s1">'Unknown'</span>
  931. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span> <span class="o">=</span> <span class="mf">40.0</span>
  932. </pre></div>
  933. <p>Then the order of the fields in <code>Capital</code> will still be <code>name</code>, <code>lon</code>, <code>lat</code>, <code>country</code>. However, the default value of <code>lat</code> will be <code>40.0</code>.</p>
  934. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="n">Capital</span><span class="p">(</span><span class="s1">'Madrid'</span><span class="p">,</span> <span class="n">country</span><span class="o">=</span><span class="s1">'Spain'</span><span class="p">)</span>
  935. <span class="go">Capital(name='Madrid', lon=0.0, lat=40.0, country='Spain')</span>
  936. </pre></div>
  937. <h2 id="optimizing-data-classes">Optimizing Data Classes</h2>
  938. <p>I’m going to end this tutorial with a few words about <a href="https://docs.python.org/reference/datamodel.html#slots">slots</a>. Slots can be used to make classes faster and use less memory. Data classes have no explicit syntax for working with slots, but the normal way of creating slots works for data classes as well. (They really are just regular classes!)</p>
  939. <div class="highlight python"><pre><span/><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
  940. <span class="nd">@dataclass</span>
  941. <span class="k">class</span> <span class="nc">SimplePosition</span><span class="p">:</span>
  942. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  943. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span>
  944. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span>
  945. <span class="nd">@dataclass</span>
  946. <span class="k">class</span> <span class="nc">SlotPosition</span><span class="p">:</span>
  947. <span class="vm">**slots**</span> <span class="o">=</span> <span class="p">[</span><span class="s1">'name'</span><span class="p">,</span> <span class="s1">'lon'</span><span class="p">,</span> <span class="s1">'lat'</span><span class="p">]</span>
  948. <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
  949. <span class="n">lon</span><span class="p">:</span> <span class="nb">float</span>
  950. <span class="n">lat</span><span class="p">:</span> <span class="nb">float</span>
  951. </pre></div>
  952. <p>Essentially, slots are defined using <code>.__slots__</code> to list the variables on a class. Variables or attributes not present in <code>.__slots__</code> may not be defined. Furthermore, a slots class may not have default values.</p>
  953. <p>The benefit of adding such restrictions is that certain optimizations may be done. For instance, slots classes take up less memory, as can be measured using <a href="https://pythonhosted.org/Pympler/">Pympler</a>:</p>
  954. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">pympler</span> <span class="kn">import</span> <span class="n">asizeof</span>
  955. <span class="gp">&gt;&gt;&gt; </span><span class="n">simple</span> <span class="o">=</span> <span class="n">SimplePosition</span><span class="p">(</span><span class="s1">'London'</span><span class="p">,</span> <span class="o">-</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">51.5</span><span class="p">)</span>
  956. <span class="gp">&gt;&gt;&gt; </span><span class="n">slot</span> <span class="o">=</span> <span class="n">SlotPosition</span><span class="p">(</span><span class="s1">'Madrid'</span><span class="p">,</span> <span class="o">-</span><span class="mf">3.7</span><span class="p">,</span> <span class="mf">40.4</span><span class="p">)</span>
  957. <span class="gp">&gt;&gt;&gt; </span><span class="n">asizeof</span><span class="o">.</span><span class="n">asizesof</span><span class="p">(</span><span class="n">simple</span><span class="p">,</span> <span class="n">slot</span><span class="p">)</span>
  958. <span class="go">(440, 248)</span>
  959. </pre></div>
  960. <p>Similarly, slots classes are typically faster to work with. The following example measures the speed of attribute access on a slots data class and a regular data class using <a href="https://docs.python.org/library/timeit.html">timeit</a> from the standard library.</p>
  961. <div class="highlight python"><pre><span/><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">timeit</span> <span class="kn">import</span> <span class="n">timeit</span>
  962. <span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="p">(</span><span class="s1">'slot.name'</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s2">"from position import SlotPosition; slot=SlotPosition('Oslo', 10.8, 59.9)"</span><span class="p">)</span>
  963. <span class="go">0.05882283499886398</span>
  964. <span class="gp">&gt;&gt;&gt; </span><span class="n">timeit</span><span class="p">(</span><span class="s1">'simple.name'</span><span class="p">,</span> <span class="n">setup</span><span class="o">=</span><span class="s2">"from position import SimplePosition; simple=SimplePosition('Oslo', 10.8, 59.9)"</span><span class="p">)</span>
  965. <span class="go">0.09207444800267695</span>
  966. </pre></div>
  967. <p>In this particular example, the slot class is about 35% faster.</p>
  968. <h2 id="conclusion-further-reading">Conclusion &amp; Further Reading</h2>
  969. <p>Data classes are one of the new features of Python 3.7. With data classes, you do not have to write boilerplate code to get proper initialization, representation, and comparisons for your objects. </p>
  970. <p>You have seen how to define your own data classes, as well as:</p>
  971. <ul>
  972. <li>How to add default values to the fields in your data class</li>
  973. <li>How to customize the ordering of data class objects</li>
  974. <li>How to work with immutable data classes</li>
  975. <li>How inheritance works for data classes</li>
  976. </ul>
  977. <p>If you want to dive into all the details of data classes, have a look at <a href="https://www.python.org/dev/peps/pep-0557/">PEP 557</a> as well as the discussions in the original <a href="https://github.com/ericvsmith/dataclasses/issues?utf8=%E2%9C%93&amp;q=">GitHub repo</a>.</p>
  978. <p>In addition, Raymond Hettinger’s PyCon 2018 talk <a href="https://www.youtube.com/watch?v=T-TwcmT6Rcw">Dataclasses: The code generator to end all code generators</a> is well worth watching.</p>
  979. <p>If you do not yet have Python 3.7, there is also a <a href="https://github.com/ericvsmith/dataclasses">data classes backport for Python 3.6</a>. And now, go forth and write less code!</p>
  980. </article>
  981. </section>
  982. <nav id="jumpto">
  983. <p>
  984. <a href="/david/blog/">Accueil du blog</a> |
  985. <a href="https://realpython.com/python-data-classes/">Source originale</a> |
  986. <a href="/david/stream/2019/">Accueil du flux</a>
  987. </p>
  988. </nav>
  989. <footer>
  990. <div>
  991. <img src="/static/david/david-larlet-avatar.jpg" loading="lazy" class="avatar" width="200" height="200">
  992. <p>
  993. Bonjour/Hi!
  994. Je suis <a href="/david/" title="Profil public">David&nbsp;Larlet</a>, je vis actuellement à Montréal et j’alimente cet espace depuis 15 ans. <br>
  995. Si tu as apprécié cette lecture, n’hésite pas à poursuivre ton exploration. Par exemple via les <a href="/david/blog/" title="Expériences bienveillantes">réflexions bimestrielles</a>, la <a href="/david/stream/2019/" title="Pensées (dés)articulées">veille hebdomadaire</a> ou en t’abonnant au <a href="/david/log/" title="S’abonner aux publications via RSS">flux RSS</a> (<a href="/david/blog/2019/flux-rss/" title="Tiens c’est quoi un flux RSS ?">so 2005</a>).
  996. </p>
  997. <p>
  998. Je m’intéresse à la place que je peux avoir dans ce monde. En tant qu’humain, en tant que membre d’une famille et en tant qu’associé d’une coopérative. De temps en temps, je fais aussi des <a href="https://github.com/davidbgk" title="Principalement sur Github mais aussi ailleurs">trucs techniques</a>. Et encore plus rarement, <a href="/david/talks/" title="En ce moment je laisse plutôt la place aux autres">j’en parle</a>.
  999. </p>
  1000. <p>
  1001. Voici quelques articles choisis :
  1002. <a href="/david/blog/2019/faire-equipe/" title="Accéder à l’article complet">Faire équipe</a>,
  1003. <a href="/david/blog/2018/bivouac-automnal/" title="Accéder à l’article complet">Bivouac automnal</a>,
  1004. <a href="/david/blog/2018/commodite-effondrement/" title="Accéder à l’article complet">Commodité et effondrement</a>,
  1005. <a href="/david/blog/2017/donnees-communs/" title="Accéder à l’article complet">Des données aux communs</a>,
  1006. <a href="/david/blog/2016/accompagner-enfant/" title="Accéder à l’article complet">Accompagner un enfant</a>,
  1007. <a href="/david/blog/2016/senior-developer/" title="Accéder à l’article complet">Senior developer</a>,
  1008. <a href="/david/blog/2016/illusion-sociale/" title="Accéder à l’article complet">L’illusion sociale</a>,
  1009. <a href="/david/blog/2016/instantane-scopyleft/" title="Accéder à l’article complet">Instantané Scopyleft</a>,
  1010. <a href="/david/blog/2016/enseigner-web/" title="Accéder à l’article complet">Enseigner le Web</a>,
  1011. <a href="/david/blog/2016/simplicite-defaut/" title="Accéder à l’article complet">Simplicité par défaut</a>,
  1012. <a href="/david/blog/2016/minimalisme-esthetique/" title="Accéder à l’article complet">Minimalisme et esthétique</a>,
  1013. <a href="/david/blog/2014/un-web-omni-present/" title="Accéder à l’article complet">Un web omni-présent</a>,
  1014. <a href="/david/blog/2014/manifeste-developpeur/" title="Accéder à l’article complet">Manifeste de développeur</a>,
  1015. <a href="/david/blog/2013/confort-convivialite/" title="Accéder à l’article complet">Confort et convivialité</a>,
  1016. <a href="/david/blog/2013/testament-numerique/" title="Accéder à l’article complet">Testament numérique</a>,
  1017. et <a href="/david/blog/" title="Accéder aux archives">bien d’autres…</a>
  1018. </p>
  1019. <p>
  1020. On peut <a href="mailto:david%40larlet.fr" title="Envoyer un courriel">échanger par courriel</a>. Si éventuellement tu souhaites que l’on travaille ensemble, tu devrais commencer par consulter le <a href="http://larlet.com">profil dédié à mon activité professionnelle</a> et/ou contacter directement <a href="http://scopyleft.fr/">scopyleft</a>, la <abbr title="Société coopérative et participative">SCOP</abbr> dont je fais partie depuis six ans. Je recommande au préalable de lire <a href="/david/blog/2018/cout-site/" title="Attention ce qui va suivre peut vous choquer">combien coûte un site</a> et pourquoi je suis plutôt favorable à une <a href="/david/pro/devis/" title="Discutons-en !">non-demande de devis</a>.
  1021. </p>
  1022. <p>
  1023. Je ne traque pas ta navigation mais mon
  1024. <abbr title="Alwaysdata, 62 rue Tiquetonne 75002 Paris, +33.184162340">hébergeur</abbr>
  1025. conserve des logs d’accès.
  1026. </p>
  1027. </div>
  1028. </footer>
  1029. <script type="text/javascript">
  1030. ;(_ => {
  1031. const jumper = document.getElementById('jumper')
  1032. jumper.addEventListener('click', e => {
  1033. e.preventDefault()
  1034. const anchor = e.target.getAttribute('href')
  1035. const targetEl = document.getElementById(anchor.substring(1))
  1036. targetEl.scrollIntoView({behavior: 'smooth'})
  1037. })
  1038. })()
  1039. </script>