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

2663 lines
240 KiB

5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
4 years ago
  1. <!DOCTYPE html>
  2. <html class="ocks-org do-not-copy">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
  6. <title>Comprehensive Python Cheatsheet</title>
  7. <meta name="description" content="Exhaustive, simple, beautiful and concise. A truly pythonic cheat sheet about Python programming language.">
  8. <link rel="icon" href="web/favicon.png">
  9. <link rel="stylesheet" href="web/default.min.css">
  10. <link href="https://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
  11. <meta name="twitter:card" content="summary">
  12. <meta name="twitter:title" content="Comprehensive Python Cheatsheet">
  13. <meta name="twitter:description" content="Exhaustive, simple, beautiful and concise. A truly pythonic cheat sheet about Python programming language.">
  14. <meta name="twitter:image" content="https://gto76.github.io/python-cheatsheet/web/image_twitter_card_2.jpeg">
  15. <meta name="google-site-verification" content="w3rvuG0D1kUm_w20qsJecSEZh59Am8jK4eSPVU83e_M" />
  16. <meta name="viewport" content="initial-scale=0.55">
  17. </head>
  18. <style>
  19. @import url(web/style.css);
  20. @font-face {font-family: "Menlo Regular";
  21. src: url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.eot"); /* IE9*/
  22. src: url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
  23. url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.woff2") format("woff2"), /* chrome、firefox */
  24. url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.woff") format("woff"), /* chrome、firefox */
  25. url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.ttf") format("truetype"), /* chrome、firefox、opera、Safari, Android, iOS 4.2+*/
  26. url("web\\OnlineWebFonts_COM_cb7eb796ae7de7195a34c485cacebad1\\@font-face\\9f94dc20bb2a09c15241d3a880b7ad01.svg#Menlo Regular") format("svg"); /* iOS 4.1- */
  27. }
  28. .join,
  29. .link,
  30. .node rect {
  31. fill: none;
  32. stroke: #636363;
  33. stroke-width: 1.5px;
  34. }
  35. .link {
  36. stroke: #969696;
  37. }
  38. .node rect {
  39. fill: white;
  40. }
  41. .link path,
  42. .node rect,
  43. .node text,
  44. .join {
  45. -webkit-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  46. -moz-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  47. -ms-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  48. -o-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  49. transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  50. }
  51. .node .element rect {
  52. fill: #bdbdbd;
  53. stroke: none;
  54. }
  55. .node .null rect {
  56. fill: none;
  57. stroke: none;
  58. }
  59. .node .null text {
  60. fill: #636363;
  61. }
  62. .node .selection rect {
  63. stroke: #e6550d;
  64. }
  65. .node .data rect {
  66. stroke: #3182bd;
  67. }
  68. .node .datum rect {
  69. fill: #d9d9d9;
  70. stroke: none;
  71. }
  72. .node .code text {
  73. font-family: monospace;
  74. }
  75. .node .key rect {
  76. fill: #a1d99b;
  77. stroke: none;
  78. }
  79. .link .to-key,
  80. .join {
  81. stroke: #a1d99b;
  82. }
  83. .join {
  84. stroke-dasharray: 2,2;
  85. }
  86. .link .to-null {
  87. stroke-dasharray: .5,3.5;
  88. stroke-linecap: round;
  89. }
  90. .link .from-data {
  91. stroke: #3182bd;
  92. }
  93. .play circle {
  94. fill: #fff;
  95. stroke: #000;
  96. stroke-width: 3px;
  97. }
  98. .play:hover path {
  99. fill: #f00;
  100. }
  101. .play.mousedown circle {
  102. fill: #f00;
  103. }
  104. .play.mousedown path {
  105. fill: #fff;
  106. }
  107. .play rect {
  108. fill: none;
  109. pointer-events: all;
  110. cursor: pointer;
  111. }
  112. code span {
  113. -webkit-transition: background 250ms linear;
  114. -moz-transition: background 250ms linear;
  115. -ms-transition: background 250ms linear;
  116. -o-transition: background 250ms linear;
  117. transition: background 250ms linear;
  118. }
  119. pre.prettyprint, code.prettyprint {
  120. background-color: #222;
  121. border-radius: 8px;
  122. font-size: 15px;
  123. }
  124. pre.prettyprint {
  125. width: 90%;
  126. margin: 0.5em;
  127. padding: 1em;
  128. white-space: pre-wrap;
  129. }
  130. #return-to-top {
  131. position: fixed;
  132. bottom: 20px;
  133. right: 20px;
  134. background: rgb(0, 0, 0);
  135. background: rgba(0, 0, 0, 0.2);
  136. width: 50px;
  137. height: 50px;
  138. display: block;
  139. text-decoration: none;
  140. -webkit-border-radius: 35px;
  141. -moz-border-radius: 35px;
  142. border-radius: 35px;
  143. display: none;
  144. -webkit-transition: all 0.3s linear;
  145. -moz-transition: all 0.3s ease;
  146. -ms-transition: all 0.3s ease;
  147. -o-transition: all 0.3s ease;
  148. transition: all 0.3s ease;
  149. }
  150. #return-to-top i {
  151. color: #fff;
  152. margin: 0;
  153. position: relative;
  154. left: 16px;
  155. top: 13px;
  156. font-size: 19px;
  157. -webkit-transition: all 0.3s ease;
  158. -moz-transition: all 0.3s ease;
  159. -ms-transition: all 0.3s ease;
  160. -o-transition: all 0.3s ease;
  161. transition: all 0.3s ease;
  162. }
  163. #return-to-top:hover {
  164. background: rgba(0, 0, 0, 0.35);
  165. }
  166. #return-to-top:hover i {
  167. color: #f0f0f0;
  168. }
  169. @media print {
  170. .pagebreak {
  171. page-break-before: always;
  172. }
  173. div {
  174. page-break-inside: avoid;
  175. }
  176. pre {
  177. page-break-inside: avoid;
  178. }
  179. }
  180. </style>
  181. <body>
  182. <header>
  183. <aside>March 15, 2020</aside>
  184. <a href="../" rel="author">Jure Šorn</a>
  185. </header>
  186. <a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
  187. <div><h1 id="comprehensivepythoncheatsheet">Comprehensive Python Cheatsheet</h1><p class="banner"><sup><a href="https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md">Download text file</a>, <a href="https://transactions.sendowl.com/products/78175486/4422834F/view">Buy PDF</a>, <a href="https://github.com/gto76/python-cheatsheet">Fork me on GitHub</a> or <a href="https://github.com/gto76/python-cheatsheet/wiki/Frequently-Asked-Questions">Check out FAQ</a>.
  188. </sup></p><p class="banner"><img src="web/image_888.jpeg" alt="Monty Python"></p><br><div><h2 id="toc"><a href="#toc" name="toc">#</a>Contents</h2><pre><code class="hljs bash"><strong>ToC</strong> = {
  189. <strong><span class="hljs-string"><span class="hljs-string">'1. Collections'</span></span></strong>: [<a href="#list">List</a>, <a href="#dictionary">Dictionary</a>, <a href="#set">Set</a>, <a href="#tuple">Tuple</a>, <a href="#range">Range</a>, <a href="#enumerate">Enumerate</a>, <a href="#iterator">Iterator</a>, <a href="#generator">Generator</a>],
  190. <strong><span class="hljs-string"><span class="hljs-string">'2. Types'</span></span></strong>: [<a href="#type">Type</a>, <a href="#string">String</a>, <a href="#regex">Regular_Exp</a>, <a href="#format">Format</a>, <a href="#numbers">Numbers</a>, <a href="#combinatorics">Combinatorics</a>, <a href="#datetime">Datetime</a>],
  191. <strong><span class="hljs-string"><span class="hljs-string">'3. Syntax'</span></span></strong>: [<a href="#arguments">Args</a>, <a href="#inline">Inline</a>, <a href="#closure">Closure</a>, <a href="#decorator">Decorator</a>, <a href="#class">Class</a>, <a href="#ducktypes">Duck_Type</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exception</a>],
  192. <strong><span class="hljs-string"><span class="hljs-string">'4. System'</span></span></strong>: [<a href="#exit">Exit</a>, <a href="#print">Print</a>, <a href="#input">Input</a>, <a href="#commandlinearguments">Command_Line_Arguments</a>, <a href="#open">Open</a>, <a href="#path">Path</a>, <a href="#oscommands">OS_Commands</a>],
  193. <strong><span class="hljs-string"><span class="hljs-string">'5. Data'</span></span></strong>: [<a href="#json">JSON</a>, <a href="#pickle">Pickle</a>, <a href="#csv">CSV</a>, <a href="#sqlite">SQLite</a>, <a href="#bytes">Bytes</a>, <a href="#struct">Struct</a>, <a href="#array">Array</a>, <a href="#memoryview">Memory_View</a>, <a href="#deque">Deque</a>],
  194. <strong><span class="hljs-string"><span class="hljs-string">'6. Advanced'</span></span></strong>: [<a href="#threading">Threading</a>, <a href="#operator">Operator</a>, <a href="#introspection">Introspection</a>, <a href="#metaprograming">Metaprograming</a>, <a href="#eval">Eval</a>, <a href="#coroutines">Coroutine</a>],
  195. <strong><span class="hljs-string"><span class="hljs-string">'7. Libraries'</span></span></strong>: [<a href="#progressbar">Progress_Bar</a>, <a href="#plot">Plot</a>, <a href="#table">Table</a>, <a href="#curses">Curses</a>, <a href="#logging">Logging</a>, <a href="#scraping">Scraping</a>, <a href="#web">Web</a>, <a href="#profiling">Profile</a>,
  196. <a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#audio">Audio</a>, <a href="#pygame">Pygame</a>]
  197. }
  198. </code></pre></div></div>
  199. <div><h2 id="main"><a href="#main" name="main">#</a>Main</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>: <span class="hljs-comment"># Runs main() if file wasn't imported.</span>
  200. main()
  201. </code></pre></div>
  202. <div><h2 id="list"><a href="#list" name="list">#</a>List</h2><pre><code class="python language-python hljs">&lt;list&gt; = &lt;list&gt;[from_inclusive : to_exclusive : ±step_size]
  203. </code></pre></div>
  204. <pre><code class="python language-python hljs">&lt;list&gt;.append(&lt;el&gt;) <span class="hljs-comment"># Or: &lt;list&gt; += [&lt;el&gt;]</span>
  205. &lt;list&gt;.extend(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;list&gt; += &lt;collection&gt;</span>
  206. </code></pre>
  207. <pre><code class="python language-python hljs">&lt;list&gt;.sort()
  208. &lt;list&gt;.reverse()
  209. &lt;list&gt; = sorted(&lt;collection&gt;)
  210. &lt;iter&gt; = reversed(&lt;list&gt;)
  211. </code></pre>
  212. <pre><code class="python language-python hljs">sum_of_elements = sum(&lt;collection&gt;)
  213. elementwise_sum = [sum(pair) <span class="hljs-keyword">for</span> pair <span class="hljs-keyword">in</span> zip(list_a, list_b)]
  214. sorted_by_second = sorted(&lt;collection&gt;, key=<span class="hljs-keyword">lambda</span> el: el[<span class="hljs-number">1</span>])
  215. sorted_by_both = sorted(&lt;collection&gt;, key=<span class="hljs-keyword">lambda</span> el: (el[<span class="hljs-number">1</span>], el[<span class="hljs-number">0</span>]))
  216. flatter_list = list(itertools.chain.from_iterable(&lt;list&gt;))
  217. product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out, el: out * el, &lt;collection&gt;)
  218. list_of_chars = list(&lt;str&gt;)
  219. </code></pre>
  220. <ul>
  221. <li><strong>Module <a href="#operator">operator</a> provides functions itemgetter() and mul() that offer the same functionality as <a href="#lambda">lambda</a> expressions above.</strong></li>
  222. </ul>
  223. <pre><code class="python language-python hljs">&lt;int&gt; = &lt;list&gt;.count(&lt;el&gt;) <span class="hljs-comment"># Returns number of occurrences. Also works on strings.</span>
  224. index = &lt;list&gt;.index(&lt;el&gt;) <span class="hljs-comment"># Returns index of first occurrence or raises ValueError.</span>
  225. &lt;list&gt;.insert(index, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
  226. &lt;el&gt; = &lt;list&gt;.pop([index]) <span class="hljs-comment"># Removes and returns item at index or from the end.</span>
  227. &lt;list&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Removes first occurrence of item or raises ValueError.</span>
  228. &lt;list&gt;.clear() <span class="hljs-comment"># Removes all items. Also works on dictionary and set.</span>
  229. </code></pre>
  230. <div><h2 id="dictionary"><a href="#dictionary" name="dictionary">#</a>Dictionary</h2><pre><code class="python language-python hljs">&lt;view&gt; = &lt;dict&gt;.keys() <span class="hljs-comment"># Coll. of keys that reflects changes.</span>
  231. &lt;view&gt; = &lt;dict&gt;.values() <span class="hljs-comment"># Coll. of values that reflects changes.</span>
  232. &lt;view&gt; = &lt;dict&gt;.items() <span class="hljs-comment"># Coll. of key-value tuples that reflects chgs.</span>
  233. </code></pre></div>
  234. <pre><code class="python language-python hljs">value = &lt;dict&gt;.get(key, default=<span class="hljs-keyword">None</span>) <span class="hljs-comment"># Returns default if key is missing.</span>
  235. value = &lt;dict&gt;.setdefault(key, default=<span class="hljs-keyword">None</span>) <span class="hljs-comment"># Returns and writes default if key is missing.</span>
  236. &lt;dict&gt; = collections.defaultdict(&lt;type&gt;) <span class="hljs-comment"># Creates a dict with default value of type.</span>
  237. &lt;dict&gt; = collections.defaultdict(<span class="hljs-keyword">lambda</span>: <span class="hljs-number">1</span>) <span class="hljs-comment"># Creates a dict with default value 1.</span>
  238. </code></pre>
  239. <pre><code class="python language-python hljs">&lt;dict&gt; = dict(&lt;collection&gt;) <span class="hljs-comment"># Creates a dict from coll. of key-value pairs.</span>
  240. &lt;dict&gt; = dict(zip(keys, values)) <span class="hljs-comment"># Creates a dict from two collections.</span>
  241. &lt;dict&gt; = dict.fromkeys(keys [, value]) <span class="hljs-comment"># Creates a dict from collection of keys.</span>
  242. </code></pre>
  243. <pre><code class="python language-python hljs">&lt;dict&gt;.update(&lt;dict&gt;) <span class="hljs-comment"># Adds items. Replaces ones with matching keys.</span>
  244. value = &lt;dict&gt;.pop(key) <span class="hljs-comment"># Removes item or raises KeyError.</span>
  245. {k <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> &lt;dict&gt;.items() <span class="hljs-keyword">if</span> v == value} <span class="hljs-comment"># Returns set of keys that point to the value.</span>
  246. {k: v <span class="hljs-keyword">for</span> k, v <span class="hljs-keyword">in</span> &lt;dict&gt;.items() <span class="hljs-keyword">if</span> k <span class="hljs-keyword">in</span> keys} <span class="hljs-comment"># Returns a dictionary, filtered by keys.</span>
  247. </code></pre>
  248. <div><h3 id="counter">Counter</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> Counter
  249. <span class="hljs-meta">&gt;&gt;&gt; </span>colors = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'red'</span>]
  250. <span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter(colors)
  251. <span class="hljs-meta">&gt;&gt;&gt; </span>counter[<span class="hljs-string">'yellow'</span>] += <span class="hljs-number">1</span>
  252. Counter({<span class="hljs-string">'blue'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'red'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'yellow'</span>: <span class="hljs-number">1</span>})
  253. <span class="hljs-meta">&gt;&gt;&gt; </span>counter.most_common()[<span class="hljs-number">0</span>]
  254. (<span class="hljs-string">'blue'</span>, <span class="hljs-number">3</span>)
  255. </code></pre></div>
  256. <div><h2 id="set"><a href="#set" name="set">#</a>Set</h2><pre><code class="python language-python hljs">&lt;set&gt; = set()
  257. </code></pre></div>
  258. <pre><code class="python language-python hljs">&lt;set&gt;.add(&lt;el&gt;) <span class="hljs-comment"># Or: &lt;set&gt; |= {&lt;el&gt;}</span>
  259. &lt;set&gt;.update(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;set&gt; |= &lt;set&gt;</span>
  260. </code></pre>
  261. <pre><code class="python language-python hljs">&lt;set&gt; = &lt;set&gt;.union(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; | &lt;set&gt;</span>
  262. &lt;set&gt; = &lt;set&gt;.intersection(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &amp; &lt;set&gt;</span>
  263. &lt;set&gt; = &lt;set&gt;.difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; - &lt;set&gt;</span>
  264. &lt;set&gt; = &lt;set&gt;.symmetric_difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; ^ &lt;set&gt;</span>
  265. &lt;bool&gt; = &lt;set&gt;.issubset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &lt;= &lt;set&gt;</span>
  266. &lt;bool&gt; = &lt;set&gt;.issuperset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &gt;= &lt;set&gt;</span>
  267. </code></pre>
  268. <pre><code class="python language-python hljs">&lt;el&gt; = &lt;set&gt;.pop() <span class="hljs-comment"># Raises KeyError if empty.</span>
  269. &lt;set&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Raises KeyError if missing.</span>
  270. &lt;set&gt;.discard(&lt;el&gt;) <span class="hljs-comment"># Doesn't raise an error.</span>
  271. </code></pre>
  272. <div><h3 id="frozenset">Frozen Set</h3><ul>
  273. <li><strong>Is immutable and hashable.</strong></li>
  274. <li><strong>That means it can be used as a key in a dictionary or as an element in a set.</strong></li>
  275. </ul><pre><code class="python language-python hljs">&lt;frozenset&gt; = frozenset(&lt;collection&gt;)
  276. </code></pre></div>
  277. <div><h2 id="tuple"><a href="#tuple" name="tuple">#</a>Tuple</h2><p><strong>Tuple is an immutable and hashable list.</strong></p><pre><code class="python language-python hljs">&lt;tuple&gt; = ()
  278. &lt;tuple&gt; = (&lt;el&gt;, )
  279. &lt;tuple&gt; = (&lt;el_1&gt;, &lt;el_2&gt; [, ...])
  280. </code></pre></div>
  281. <div><h3 id="namedtuple">Named Tuple</h3><p><strong>Tuple's subclass with named elements.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  282. <span class="hljs-meta">&gt;&gt;&gt; </span>Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  283. <span class="hljs-meta">&gt;&gt;&gt; </span>p = Point(<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  284. Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  285. <span class="hljs-meta">&gt;&gt;&gt; </span>p[<span class="hljs-number">0</span>]
  286. <span class="hljs-number">1</span>
  287. <span class="hljs-meta">&gt;&gt;&gt; </span>p.x
  288. <span class="hljs-number">1</span>
  289. <span class="hljs-meta">&gt;&gt;&gt; </span>getattr(p, <span class="hljs-string">'y'</span>)
  290. <span class="hljs-number">2</span>
  291. <span class="hljs-meta">&gt;&gt;&gt; </span>p._fields <span class="hljs-comment"># Or: Point._fields</span>
  292. (<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>)
  293. </code></pre></div>
  294. <div><h2 id="range"><a href="#range" name="range">#</a>Range</h2><pre><code class="python language-python hljs">&lt;range&gt; = range(to_exclusive)
  295. &lt;range&gt; = range(from_inclusive, to_exclusive)
  296. &lt;range&gt; = range(from_inclusive, to_exclusive, ±step_size)
  297. </code></pre></div>
  298. <pre><code class="python language-python hljs">from_inclusive = &lt;range&gt;.start
  299. to_exclusive = &lt;range&gt;.stop
  300. </code></pre>
  301. <div><h2 id="enumerate"><a href="#enumerate" name="enumerate">#</a>Enumerate</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">for</span> i, el <span class="hljs-keyword">in</span> enumerate(&lt;collection&gt; [, i_start]):
  302. ...
  303. </code></pre></div>
  304. <div><h2 id="iterator"><a href="#iterator" name="iterator">#</a>Iterator</h2><pre><code class="python language-python hljs">&lt;iter&gt; = iter(&lt;collection&gt;) <span class="hljs-comment"># `iter(&lt;iter&gt;)` returns unmodified iterator.</span>
  305. &lt;iter&gt; = iter(&lt;function&gt;, to_exclusive) <span class="hljs-comment"># A sequence of return values until 'to_exclusive'.</span>
  306. &lt;el&gt; = next(&lt;iter&gt; [, default]) <span class="hljs-comment"># Raises StopIteration or returns 'default' on end.</span>
  307. &lt;list&gt; = list(&lt;iter&gt;) <span class="hljs-comment"># Returns a list of iterator's remaining elements.</span>
  308. </code></pre></div>
  309. <div><h3 id="itertools">Itertools</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> count, repeat, cycle, chain, islice
  310. </code></pre></div>
  311. <pre><code class="python language-python hljs">&lt;iter&gt; = count(start=<span class="hljs-number">0</span>, step=<span class="hljs-number">1</span>) <span class="hljs-comment"># Returns updated value endlessly. Accepts floats.</span>
  312. &lt;iter&gt; = repeat(&lt;el&gt; [, times]) <span class="hljs-comment"># Returns element endlessly or 'times' times.</span>
  313. &lt;iter&gt; = cycle(&lt;collection&gt;) <span class="hljs-comment"># Repeats the sequence endlessly.</span>
  314. </code></pre>
  315. <pre><code class="python language-python hljs">&lt;iter&gt; = chain(&lt;coll_1&gt;, &lt;coll_2&gt; [, ...]) <span class="hljs-comment"># Empties collections in order.</span>
  316. &lt;iter&gt; = chain.from_iterable(&lt;collection&gt;) <span class="hljs-comment"># Empties collections inside a collection in order.</span>
  317. </code></pre>
  318. <pre><code class="python language-python hljs">&lt;iter&gt; = islice(&lt;collection&gt;, to_exclusive)
  319. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive [, +step_size])
  320. </code></pre>
  321. <div><h2 id="generator"><a href="#generator" name="generator">#</a>Generator</h2><ul>
  322. <li><strong>Any function that contains a yield statement returns a generator.</strong></li>
  323. <li><strong>Generators and iterators are interchangeable.</strong></li>
  324. </ul><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">count</span><span class="hljs-params">(start, step)</span>:</span>
  325. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  326. <span class="hljs-keyword">yield</span> start
  327. start += step
  328. </code></pre></div>
  329. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = count(<span class="hljs-number">10</span>, <span class="hljs-number">2</span>)
  330. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  331. (<span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>)
  332. </code></pre>
  333. <div><h2 id="type"><a href="#type" name="type">#</a>Type</h2><ul>
  334. <li><strong>Everything is an object.</strong></li>
  335. <li><strong>Every object has a type.</strong></li>
  336. <li><strong>Type and class are synonymous.</strong></li>
  337. </ul><pre><code class="python language-python hljs">&lt;type&gt; = type(&lt;el&gt;) <span class="hljs-comment"># Or: &lt;el&gt;.__class__</span>
  338. &lt;bool&gt; = isinstance(&lt;el&gt;, &lt;type&gt;) <span class="hljs-comment"># Or: issubclass(type(&lt;el&gt;), &lt;type&gt;)</span>
  339. </code></pre></div>
  340. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>type(<span class="hljs-string">'a'</span>), <span class="hljs-string">'a'</span>.__class__, str
  341. (&lt;<span class="hljs-class"><span class="hljs-title">class</span> '<span class="hljs-title">str</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">str</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">str</span>'&gt;)
  342. </span></code></pre>
  343. <div><h4 id="sometypesdonothavebuiltinnamessotheymustbeimported">Some types do not have built-in names, so they must be imported:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> types <span class="hljs-keyword">import</span> FunctionType, MethodType, LambdaType, GeneratorType
  344. </code></pre></div>
  345. <div><h3 id="abstractbaseclasses">Abstract Base Classes</h3><p><strong>Each abstract base class specifies a set of virtual subclasses. These classes are then recognized by isinstance() and issubclass() as subclasses of the ABC, although they are really not.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> collections.abc <span class="hljs-keyword">import</span> Sequence, Collection, Iterable
  346. <span class="hljs-meta">&gt;&gt;&gt; </span>isinstance([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], Iterable)
  347. <span class="hljs-keyword">True</span>
  348. </code></pre></div>
  349. <pre><code class="text language-text">┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
  350. ┃ │ Sequence │ Collection │ Iterable ┃
  351. ┠──────────────────┼────────────┼────────────┼────────────┨
  352. ┃ list, range, str │ ✓ │ ✓ │ ✓ ┃
  353. ┃ dict, set │ │ ✓ │ ✓ ┃
  354. ┃ iter │ │ │ ✓ ┃
  355. ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
  356. </code></pre>
  357. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> numbers <span class="hljs-keyword">import</span> Integral, Rational, Real, Complex, Number
  358. <span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(<span class="hljs-number">123</span>, Number)
  359. <span class="hljs-keyword">True</span>
  360. </code></pre>
  361. <pre><code class="text language-text">┏━━━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
  362. ┃ │ Integral │ Rational │ Real │ Complex │ Number ┃
  363. ┠────────────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
  364. ┃ int │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
  365. ┃ fractions.Fraction │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
  366. ┃ float │ │ │ ✓ │ ✓ │ ✓ ┃
  367. ┃ complex │ │ │ │ ✓ │ ✓ ┃
  368. ┃ decimal.Decimal │ │ │ │ │ ✓ ┃
  369. ┗━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
  370. </code></pre>
  371. <div><h2 id="string"><a href="#string" name="string">#</a>String</h2><pre><code class="python language-python hljs">&lt;str&gt; = &lt;str&gt;.strip() <span class="hljs-comment"># Strips all whitespace characters from both ends.</span>
  372. &lt;str&gt; = &lt;str&gt;.strip(<span class="hljs-string">'&lt;chars&gt;'</span>) <span class="hljs-comment"># Strips all passed characters from both ends.</span>
  373. </code></pre></div>
  374. <pre><code class="python language-python hljs">&lt;list&gt; = &lt;str&gt;.split() <span class="hljs-comment"># Splits on one or more whitespace characters.</span>
  375. &lt;list&gt; = &lt;str&gt;.split(sep=<span class="hljs-keyword">None</span>, maxsplit=<span class="hljs-number">-1</span>) <span class="hljs-comment"># Splits on 'sep' str at most 'maxsplit' times.</span>
  376. &lt;list&gt; = &lt;str&gt;.splitlines(keepends=<span class="hljs-keyword">False</span>) <span class="hljs-comment"># Splits on \n,\r,\r\n. Keeps them if 'keepends'.</span>
  377. &lt;str&gt; = &lt;str&gt;.join(&lt;coll_of_strings&gt;) <span class="hljs-comment"># Joins elements using string as separator.</span>
  378. </code></pre>
  379. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;sub_str&gt; <span class="hljs-keyword">in</span> &lt;str&gt; <span class="hljs-comment"># Checks if string contains a substring.</span>
  380. &lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  381. &lt;bool&gt; = &lt;str&gt;.endswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  382. &lt;int&gt; = &lt;str&gt;.find(&lt;sub_str&gt;) <span class="hljs-comment"># Returns start index of first match or -1.</span>
  383. &lt;int&gt; = &lt;str&gt;.index(&lt;sub_str&gt;) <span class="hljs-comment"># Same but raises ValueError if missing.</span>
  384. </code></pre>
  385. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;str&gt;.replace(old, new [, count]) <span class="hljs-comment"># Replaces 'old' with 'new' at most 'count' times.</span>
  386. &lt;str&gt; = &lt;str&gt;.translate(&lt;table&gt;) <span class="hljs-comment"># Use `str.maketrans(&lt;dict&gt;)` to generate table.</span>
  387. </code></pre>
  388. <pre><code class="python language-python hljs">&lt;str&gt; = chr(&lt;int&gt;) <span class="hljs-comment"># Converts int to Unicode char.</span>
  389. &lt;int&gt; = ord(&lt;str&gt;) <span class="hljs-comment"># Converts Unicode char to int.</span>
  390. </code></pre>
  391. <ul>
  392. <li><strong>Also: <code class="python hljs"><span class="hljs-string">'lstrip()'</span></code>, <code class="python hljs"><span class="hljs-string">'rstrip()'</span></code>.</strong></li>
  393. <li><strong>Also: <code class="python hljs"><span class="hljs-string">'lower()'</span></code>, <code class="python hljs"><span class="hljs-string">'upper()'</span></code>, <code class="python hljs"><span class="hljs-string">'capitalize()'</span></code> and <code class="python hljs"><span class="hljs-string">'title()'</span></code>.</strong></li>
  394. </ul>
  395. <div><h3 id="propertymethods">Property Methods</h3><pre><code class="text language-text">┏━━━━━━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┯━━━━━━━━━━┓
  396. ┃ │ [ !#$%…] │ [a-zA-Z] │ [¼½¾] │ [²³¹] │ [0-9] ┃
  397. ┠───────────────┼──────────┼──────────┼──────────┼──────────┼──────────┨
  398. ┃ isprintable() │ ✓ │ ✓ │ ✓ │ ✓ │ ✓ ┃
  399. ┃ isalnum() │ │ ✓ │ ✓ │ ✓ │ ✓ ┃
  400. ┃ isnumeric() │ │ │ ✓ │ ✓ │ ✓ ┃
  401. ┃ isdigit() │ │ │ │ ✓ │ ✓ ┃
  402. ┃ isdecimal() │ │ │ │ │ ✓ ┃
  403. ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┷━━━━━━━━━━┛
  404. </code></pre></div>
  405. <ul>
  406. <li><strong>Also: <code class="python hljs"><span class="hljs-string">'isspace()'</span></code> checks for <code class="python hljs"><span class="hljs-string">'[ \t\n\r\f\v…]'</span></code>.</strong></li>
  407. </ul>
  408. <div><h2 id="regex"><a href="#regex" name="regex">#</a>Regex</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> re
  409. &lt;str&gt; = re.sub(&lt;regex&gt;, new, text, count=<span class="hljs-number">0</span>) <span class="hljs-comment"># Substitutes all occurrences with 'new'.</span>
  410. &lt;list&gt; = re.findall(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as strings.</span>
  411. &lt;list&gt; = re.split(&lt;regex&gt;, text, maxsplit=<span class="hljs-number">0</span>) <span class="hljs-comment"># Use brackets in regex to include the matches.</span>
  412. &lt;Match&gt; = re.search(&lt;regex&gt;, text) <span class="hljs-comment"># Searches for first occurrence of the pattern.</span>
  413. &lt;Match&gt; = re.match(&lt;regex&gt;, text) <span class="hljs-comment"># Searches only at the beginning of the text.</span>
  414. &lt;iter&gt; = re.finditer(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as match objects.</span>
  415. </code></pre></div>
  416. <ul>
  417. <li><strong>Search() and match() return None if they can't find a match.</strong></li>
  418. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.IGNORECASE'</span></code> can be used with all functions.</strong></li>
  419. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.MULTILINE'</span></code> makes <code class="python hljs"><span class="hljs-string">'^'</span></code> and <code class="python hljs"><span class="hljs-string">'$'</span></code> match the start/end of each line.</strong></li>
  420. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.DOTALL'</span></code> makes dot also accept the <code class="python hljs"><span class="hljs-string">'\n'</span></code>.</strong></li>
  421. <li><strong>Use <code class="python hljs"><span class="hljs-string">r'\1'</span></code> or <code class="python hljs"><span class="hljs-string">'\\1'</span></code> for backreference.</strong></li>
  422. <li><strong>Add <code class="python hljs"><span class="hljs-string">'?'</span></code> after an operator to make it non-greedy.</strong></li>
  423. </ul>
  424. <div><h3 id="matchobject">Match Object</h3><pre><code class="python language-python hljs">&lt;str&gt; = &lt;Match&gt;.group() <span class="hljs-comment"># Returns the whole match. Also group(0).</span>
  425. &lt;str&gt; = &lt;Match&gt;.group(<span class="hljs-number">1</span>) <span class="hljs-comment"># Returns part in the first bracket.</span>
  426. &lt;tuple&gt; = &lt;Match&gt;.groups() <span class="hljs-comment"># Returns all bracketed parts.</span>
  427. &lt;int&gt; = &lt;Match&gt;.start() <span class="hljs-comment"># Returns start index of the match.</span>
  428. &lt;int&gt; = &lt;Match&gt;.end() <span class="hljs-comment"># Returns exclusive end index of the match.</span>
  429. </code></pre></div>
  430. <div><h3 id="specialsequences">Special Sequences</h3><ul>
  431. <li><strong>By default digits, alphanumerics and whitespaces from all alphabets are matched, unless <code class="python hljs"><span class="hljs-string">'flags=re.ASCII'</span></code> argument is used.</strong></li>
  432. <li><strong>Use a capital letter for negation.</strong></li>
  433. </ul><pre><code class="python language-python hljs"><span class="hljs-string">'\d'</span> == <span class="hljs-string">'[0-9]'</span> <span class="hljs-comment"># Matches any digit.</span>
  434. <span class="hljs-string">'\w'</span> == <span class="hljs-string">'[a-zA-Z0-9_]'</span> <span class="hljs-comment"># Matches any alphanumeric.</span>
  435. <span class="hljs-string">'\s'</span> == <span class="hljs-string">'[ \t\n\r\f\v]'</span> <span class="hljs-comment"># Matches any whitespace.</span>
  436. </code></pre></div>
  437. <div><h2 id="format"><a href="#format" name="format">#</a>Format</h2><pre><code class="python language-python hljs">&lt;str&gt; = <span class="hljs-string">f'<span class="hljs-subst">{&lt;el_1&gt;}</span>, <span class="hljs-subst">{&lt;el_2&gt;}</span>'</span>
  438. &lt;str&gt; = <span class="hljs-string">'{}, {}'</span>.format(&lt;el_1&gt;, &lt;el_2&gt;)
  439. </code></pre></div>
  440. <div><h3 id="attributes">Attributes</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  441. <span class="hljs-meta">&gt;&gt;&gt; </span>Person = namedtuple(<span class="hljs-string">'Person'</span>, <span class="hljs-string">'name height'</span>)
  442. <span class="hljs-meta">&gt;&gt;&gt; </span>person = Person(<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)
  443. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">f'<span class="hljs-subst">{person.height}</span>'</span>
  444. <span class="hljs-string">'187'</span>
  445. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">'{p.height}'</span>.format(p=person)
  446. <span class="hljs-string">'187'</span>
  447. </code></pre></div>
  448. <div><h3 id="generaloptions">General Options</h3><pre><code class="python language-python hljs">{&lt;el&gt;:&lt;<span class="hljs-number">10</span>} <span class="hljs-comment"># '&lt;el&gt; '</span>
  449. {&lt;el&gt;:^<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt; '</span>
  450. {&lt;el&gt;:&gt;<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt;'</span>
  451. {&lt;el&gt;:.&lt;<span class="hljs-number">10</span>} <span class="hljs-comment"># '&lt;el&gt;......'</span>
  452. {&lt;el&gt;:&lt;<span class="hljs-number">0</span>} <span class="hljs-comment"># '&lt;el&gt;'</span>
  453. </code></pre></div>
  454. <div><h3 id="strings">Strings</h3><p><strong><code class="python hljs"><span class="hljs-string">'!r'</span></code> calls object's <a href="#class">repr()</a> method, instead of <a href="#class">str()</a>, to get a string.</strong></p><pre><code class="python language-python hljs">{<span class="hljs-string">'abcde'</span>!r:<span class="hljs-number">10</span>} <span class="hljs-comment"># "'abcde' "</span>
  455. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># 'abc '</span>
  456. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">.3</span>} <span class="hljs-comment"># 'abc'</span>
  457. </code></pre></div>
  458. <div><h3 id="numbers-1">Numbers</h3><pre><code class="python language-python hljs">{ <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>,} <span class="hljs-comment"># ' 123,456'</span>
  459. { <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>_} <span class="hljs-comment"># ' 123_456'</span>
  460. { <span class="hljs-number">123456</span>:+<span class="hljs-number">10</span>} <span class="hljs-comment"># ' +123456'</span>
  461. {<span class="hljs-number">-123456</span>:=<span class="hljs-number">10</span>} <span class="hljs-comment"># '- 123456'</span>
  462. { <span class="hljs-number">123456</span>: } <span class="hljs-comment"># ' 123456'</span>
  463. {<span class="hljs-number">-123456</span>: } <span class="hljs-comment"># '-123456'</span>
  464. </code></pre></div>
  465. <div><h3 id="floats">Floats</h3><pre><code class="python language-python hljs">{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># ' 1.23'</span>
  466. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>f} <span class="hljs-comment"># ' 1.235'</span>
  467. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>e} <span class="hljs-comment"># ' 1.235e+00'</span>
  468. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>%} <span class="hljs-comment"># ' 123.456%'</span>
  469. </code></pre></div>
  470. <div><h4 id="comparisonofpresentationtypes">Comparison of presentation types:</h4><pre><code class="text language-text">┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
  471. ┃ │ {&lt;float&gt;} │ {&lt;float&gt;:f} │ {&lt;float&gt;:e} │ {&lt;float&gt;:%} ┃
  472. ┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
  473. ┃ 0.000056789 │ '5.6789e-05' │ '0.000057' │ '5.678900e-05' │ '0.005679%' ┃
  474. ┃ 0.00056789 │ '0.00056789' │ '0.000568' │ '5.678900e-04' │ '0.056789%' ┃
  475. ┃ 0.0056789 │ '0.0056789' │ '0.005679' │ '5.678900e-03' │ '0.567890%' ┃
  476. ┃ 0.056789 │ '0.056789' │ '0.056789' │ '5.678900e-02' │ '5.678900%' ┃
  477. ┃ 0.56789 │ '0.56789' │ '0.567890' │ '5.678900e-01' │ '56.789000%' ┃
  478. ┃ 5.6789 │ '5.6789' │ '5.678900' │ '5.678900e+00' │ '567.890000%' ┃
  479. ┃ 56.789 │ '56.789' │ '56.789000' │ '5.678900e+01' │ '5678.900000%' ┃
  480. ┃ 567.89 │ '567.89' │ '567.890000' │ '5.678900e+02' │ '56789.000000%' ┃
  481. ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
  482. </code></pre></div>
  483. <pre><code class="text language-text">┏━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━━━━┓
  484. ┃ │ {&lt;float&gt;:.2} │ {&lt;float&gt;:.2f} │ {&lt;float&gt;:.2e} │ {&lt;float&gt;:.2%} ┃
  485. ┠───────────────┼─────────────────┼─────────────────┼─────────────────┼─────────────────┨
  486. ┃ 0.000056789 │ '5.7e-05' │ '0.00' │ '5.68e-05' │ '0.01%' ┃
  487. ┃ 0.00056789 │ '0.00057' │ '0.00' │ '5.68e-04' │ '0.06%' ┃
  488. ┃ 0.0056789 │ '0.0057' │ '0.01' │ '5.68e-03' │ '0.57%' ┃
  489. ┃ 0.056789 │ '0.057' │ '0.06' │ '5.68e-02' │ '5.68%' ┃
  490. ┃ 0.56789 │ '0.57' │ '0.57' │ '5.68e-01' │ '56.79%' ┃
  491. ┃ 5.6789 │ '5.7' │ '5.68' │ '5.68e+00' │ '567.89%' ┃
  492. ┃ 56.789 │ '5.7e+01' │ '56.79' │ '5.68e+01' │ '5678.90%' ┃
  493. ┃ 567.89 │ '5.7e+02' │ '567.89' │ '5.68e+02' │ '56789.00%' ┃
  494. ┗━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━┛
  495. </code></pre>
  496. <div><h3 id="ints">Ints</h3><pre><code class="python language-python hljs">{<span class="hljs-number">90</span>:c} <span class="hljs-comment"># 'Z'</span>
  497. {<span class="hljs-number">90</span>:b} <span class="hljs-comment"># '1011010'</span>
  498. {<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'</span>
  499. </code></pre></div>
  500. <div><h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2><div><h3 id="types">Types</h3><pre><code class="python language-python hljs">&lt;int&gt; = int(&lt;float/str/bool&gt;) <span class="hljs-comment"># Or: math.floor(&lt;float&gt;)</span>
  501. &lt;float&gt; = float(&lt;int/str/bool&gt;) <span class="hljs-comment"># Or: &lt;real&gt;&lt;int&gt;</span>
  502. &lt;complex&gt; = complex(real=<span class="hljs-number">0</span>, imag=<span class="hljs-number">0</span>) <span class="hljs-comment"># Or: &lt;real&gt; ± &lt;real&gt;j</span>
  503. &lt;Fraction&gt; = fractions.Fraction(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>) <span class="hljs-comment"># Or: Fraction(numerator=0, denominator=1)</span>
  504. &lt;Decimal&gt; = decimal.Decimal(&lt;str/int&gt;) <span class="hljs-comment"># Or: Decimal((sign, digits, exponent))</span>
  505. </code></pre></div></div>
  506. <ul>
  507. <li><strong><code class="python hljs"><span class="hljs-string">'int(&lt;str&gt;)'</span></code> and <code class="python hljs"><span class="hljs-string">'float(&lt;str&gt;)'</span></code> raise ValueError on malformed strings.</strong></li>
  508. <li><strong>Decimal numbers can be represented exactly, unlike floats where <code class="python hljs"><span class="hljs-string">'1.1 + 2.2 != 3.3'</span></code>.</strong></li>
  509. <li><strong>Precision of decimal operations is set with: <code class="python hljs"><span class="hljs-string">'decimal.getcontext().prec = &lt;int&gt;'</span></code>.</strong></li>
  510. </ul>
  511. <div><h3 id="basicfunctions">Basic Functions</h3><pre><code class="python language-python hljs">&lt;num&gt; = pow(&lt;num&gt;, &lt;num&gt;) <span class="hljs-comment"># Or: &lt;num&gt; ** &lt;num&gt;</span>
  512. &lt;num&gt; = abs(&lt;num&gt;) <span class="hljs-comment"># &lt;float&gt; = abs(&lt;complex&gt;)</span>
  513. &lt;num&gt; = round(&lt;num&gt; [, ±ndigits]) <span class="hljs-comment"># `round(126, -1) == 130`</span>
  514. </code></pre></div>
  515. <div><h3 id="math">Math</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> e, pi, inf, nan, isinf, isnan
  516. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians
  517. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2
  518. </code></pre></div>
  519. <div><h3 id="statistics">Statistics</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean, median, variance, stdev, pvariance, pstdev
  520. </code></pre></div>
  521. <div><h3 id="random">Random</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, choice, shuffle
  522. &lt;float&gt; = random()
  523. &lt;int&gt; = randint(from_inclusive, to_inclusive)
  524. &lt;el&gt; = choice(&lt;list&gt;)
  525. shuffle(&lt;list&gt;)
  526. </code></pre></div>
  527. <div><h3 id="binhex">Bin, Hex</h3><pre><code class="python language-python hljs">&lt;int&gt; = <span class="hljs-number">0</span>b&lt;bin&gt; <span class="hljs-comment"># Or: 0x&lt;hex&gt;</span>
  528. &lt;int&gt; = int(<span class="hljs-string">&lt;bin&gt;'</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># Or: int('±&lt;hex&gt;', 16)</span>
  529. &lt;int&gt; = int(<span class="hljs-string">'±0b&lt;bin&gt;'</span>, <span class="hljs-number">0</span>) <span class="hljs-comment"># Or: int('±0x&lt;hex&gt;', 0)</span>
  530. <span class="hljs-string">'[-]0b&lt;bin&gt;'</span> = bin(&lt;int&gt;) <span class="hljs-comment"># Or: hex(&lt;int&gt;)</span>
  531. </code></pre></div>
  532. <div><h3 id="bitwiseoperators">Bitwise Operators</h3><pre><code class="python language-python hljs">&lt;int&gt; = &lt;int&gt; &amp; &lt;int&gt; <span class="hljs-comment"># And</span>
  533. &lt;int&gt; = &lt;int&gt; | &lt;int&gt; <span class="hljs-comment"># Or</span>
  534. &lt;int&gt; = &lt;int&gt; ^ &lt;int&gt; <span class="hljs-comment"># Xor (0 if both bits equal)</span>
  535. &lt;int&gt; = &lt;int&gt; &lt;&lt; n_bits <span class="hljs-comment"># Shift left (&gt;&gt; for right)</span>
  536. &lt;int&gt; = ~&lt;int&gt; <span class="hljs-comment"># Not (also: -&lt;int&gt; - 1)</span>
  537. </code></pre></div>
  538. <div><h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2><ul>
  539. <li><strong>Every function returns an iterator.</strong></li>
  540. <li><strong>If you want to print the iterator, you need to pass it to the list() function first!</strong></li>
  541. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> product, combinations, combinations_with_replacement, permutations
  542. </code></pre></div>
  543. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>product([<span class="hljs-number">0</span>, <span class="hljs-number">1</span>], repeat=<span class="hljs-number">3</span>)
  544. [(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>),
  545. (<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">1</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">0</span>), (<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>)]
  546. </code></pre>
  547. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>product(<span class="hljs-string">'ab'</span>, <span class="hljs-string">'12'</span>)
  548. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'2'</span>),
  549. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'2'</span>)]
  550. </code></pre>
  551. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>combinations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
  552. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  553. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>)]
  554. </code></pre>
  555. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>combinations_with_replacement(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
  556. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  557. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  558. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)]
  559. </code></pre>
  560. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>permutations(<span class="hljs-string">'abc'</span>, <span class="hljs-number">2</span>)
  561. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  562. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  563. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)]
  564. </code></pre>
  565. <div><h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2><ul>
  566. <li><strong>Module 'datetime' provides 'date' <code class="apache hljs"><span class="hljs-section">&lt;D&gt;</span></code>, 'time' <code class="apache hljs"><span class="hljs-section">&lt;T&gt;</span></code>, 'datetime' <code class="apache hljs"><span class="hljs-section">&lt;DT&gt;</span></code> and 'timedelta' <code class="apache hljs"><span class="hljs-section">&lt;TD&gt;</span></code> classes. All are immutable and hashable.</strong></li>
  567. <li><strong>Time and datetime objects can be 'aware' <code class="apache hljs"><span class="hljs-section">&lt;a&gt;</span></code>, meaning they have defined timezone, or 'naive' <code class="apache hljs"><span class="hljs-section">&lt;n&gt;</span></code>, meaning they don't.</strong></li>
  568. <li><strong>If object is naive, it is presumed to be in the system's timezone.</strong></li>
  569. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date, time, datetime, timedelta
  570. <span class="hljs-keyword">from</span> dateutil.tz <span class="hljs-keyword">import</span> UTC, tzlocal, gettz, resolve_imaginary
  571. </code></pre></div>
  572. <div><h3 id="constructors">Constructors</h3><pre><code class="python language-python apache hljs">&lt;D&gt; = date(year, month, day)
  573. &lt;T&gt; = time(hour=<span class="hljs-number">0</span>, minute=<span class="hljs-number">0</span>, second=<span class="hljs-number">0</span>, microsecond=<span class="hljs-number">0</span>, tzinfo=<span class="hljs-keyword">None</span>, fold=<span class="hljs-number">0</span>)
  574. &lt;DT&gt; = datetime(year, month, day, hour=<span class="hljs-number">0</span>, minute=<span class="hljs-number">0</span>, second=<span class="hljs-number">0</span>, ...)
  575. &lt;TD&gt; = timedelta(days=<span class="hljs-number">0</span>, seconds=<span class="hljs-number">0</span>, microseconds=<span class="hljs-number">0</span>, milliseconds=<span class="hljs-number">0</span>,
  576. minutes=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>, weeks=<span class="hljs-number">0</span>)
  577. </code></pre></div>
  578. <ul>
  579. <li><strong>Use <code class="python hljs"><span class="hljs-string">'&lt;D/DT&gt;.weekday()'</span></code> to get the day of the week (Mon == 0).</strong></li>
  580. <li><strong><code class="python hljs"><span class="hljs-string">'fold=1'</span></code> means the second pass in case of time jumping back for one hour.</strong></li>
  581. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;DTa&gt; = resolve_imaginary(&lt;DTa&gt;)'</span></code> fixes DTs that fall into the missing hour.</strong></li>
  582. </ul>
  583. <div><h3 id="now">Now</h3><pre><code class="python language-python hljs">&lt;D/DTn&gt; = D/DT.today() <span class="hljs-comment"># Current local date or naive datetime.</span>
  584. &lt;DTn&gt; = DT.utcnow() <span class="hljs-comment"># Naive datetime from current UTC time.</span>
  585. &lt;DTa&gt; = DT.now(&lt;tzinfo&gt;) <span class="hljs-comment"># Aware datetime from current tz time.</span>
  586. </code></pre></div>
  587. <ul>
  588. <li><strong>To extract time use <code class="python hljs"><span class="hljs-string">'&lt;DTn&gt;.time()'</span></code>, <code class="python hljs"><span class="hljs-string">'&lt;DTa&gt;.time()'</span></code> or <code class="python hljs"><span class="hljs-string">'&lt;DTa&gt;.timetz()'</span></code>.</strong></li>
  589. </ul>
  590. <div><h3 id="timezone">Timezone</h3><pre><code class="python language-python apache hljs">&lt;tzinfo&gt; = UTC <span class="hljs-comment"># UTC timezone. London without DST.</span>
  591. &lt;tzinfo&gt; = tzlocal() <span class="hljs-comment"># Local timezone. Also gettz().</span>
  592. &lt;tzinfo&gt; = gettz(<span class="hljs-string">'&lt;Continent&gt;/&lt;City&gt;'</span>) <span class="hljs-comment"># 'Continent/City_Name' timezone or None.</span>
  593. &lt;DTa&gt; = &lt;DT&gt;.astimezone(&lt;tzinfo&gt;) <span class="hljs-comment"># Datetime, converted to passed timezone.</span>
  594. &lt;Ta/DTa&gt; = &lt;T/DT&gt;.replace(tzinfo=&lt;tzinfo&gt;) <span class="hljs-comment"># Unconverted object with new timezone.</span>
  595. </code></pre></div>
  596. <div><h3 id="encode">Encode</h3><pre><code class="python language-python apache hljs">&lt;D/T/DT&gt; = D/T/DT.fromisoformat(<span class="hljs-string">'&lt;iso&gt;'</span>) <span class="hljs-comment"># Object from ISO string. Raises ValueError.</span>
  597. &lt;DT&gt; = DT.strptime(&lt;str&gt;, <span class="hljs-string">'&lt;format&gt;'</span>) <span class="hljs-comment"># Datetime from str, according to format.</span>
  598. &lt;D/DTn&gt; = D/DT.fromordinal(&lt;int&gt;) <span class="hljs-comment"># D/DTn from days since Christ, at midnight.</span>
  599. &lt;DTn&gt; = DT.fromtimestamp(&lt;real&gt;) <span class="hljs-comment"># Local time DTn from seconds since Epoch.</span>
  600. &lt;DTa&gt; = DT.fromtimestamp(&lt;real&gt;, &lt;tz.&gt;) <span class="hljs-comment"># Aware datetime from seconds since Epoch.</span>
  601. </code></pre></div>
  602. <ul>
  603. <li><strong>ISO strings come in following forms: <code class="python hljs"><span class="hljs-string">'YYYY-MM-DD'</span></code>, <code class="python hljs"><span class="hljs-string">'HH:MM:SS.ffffff[±&lt;offset&gt;]'</span></code>, or both separated by an arbitrary character. Offset is formatted as: <code class="python hljs"><span class="hljs-string">'HH:MM'</span></code>.</strong></li>
  604. <li><strong>Epoch on Unix systems is: <code class="python hljs"><span class="hljs-string">'1970-01-01 00:00 UTC'</span></code>, <code class="python hljs"><span class="hljs-string">'1970-01-01 01:00 CET'</span></code>, …</strong></li>
  605. </ul>
  606. <div><h3 id="decode">Decode</h3><pre><code class="python language-python hljs">&lt;str&gt; = &lt;D/T/DT&gt;.isoformat(sep=<span class="hljs-string">'T'</span>) <span class="hljs-comment"># Also timespec='auto/hours/minutes/seconds'.</span>
  607. &lt;str&gt; = &lt;D/T/DT&gt;.strftime(<span class="hljs-string">'&lt;format&gt;'</span>) <span class="hljs-comment"># Custom string representation.</span>
  608. &lt;int&gt; = &lt;D/DT&gt;.toordinal() <span class="hljs-comment"># Days since Christ, ignoring time and tz.</span>
  609. &lt;float&gt; = &lt;DTn&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch, from DTn in local tz.</span>
  610. &lt;float&gt; = &lt;DTa&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch, from DTa.</span>
  611. </code></pre></div>
  612. <div><h3 id="format-1">Format</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
  613. <span class="hljs-meta">&gt;&gt;&gt; </span>dt = datetime.strptime(<span class="hljs-string">'2015-05-14 23:39:00.00 +0200'</span>, <span class="hljs-string">'%Y-%m-%d %H:%M:%S.%f %z'</span>)
  614. <span class="hljs-meta">&gt;&gt;&gt; </span>dt.strftime(<span class="hljs-string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)
  615. <span class="hljs-string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span>
  616. </code></pre></div>
  617. <ul>
  618. <li><strong>When parsing, <code class="python hljs"><span class="hljs-string">'%z'</span></code> also accepts <code class="python hljs"><span class="hljs-string">'±HH:MM'</span></code>.</strong></li>
  619. <li><strong>For abbreviated weekday and month use <code class="python hljs"><span class="hljs-string">'%a'</span></code> and <code class="python hljs"><span class="hljs-string">'%b'</span></code>.</strong></li>
  620. </ul>
  621. <div><h3 id="arithmetics">Arithmetics</h3><pre><code class="python language-python apache hljs">&lt;D/DT&gt; = &lt;D/DT&gt; ± &lt;TD&gt; <span class="hljs-comment"># Returned datetime can fall into missing hour.</span>
  622. &lt;TD&gt; = &lt;D/DTn&gt; - &lt;D/DTn&gt; <span class="hljs-comment"># Returns the difference, ignoring time jumps.</span>
  623. &lt;TD&gt; = &lt;DTa&gt; - &lt;DTa&gt; <span class="hljs-comment"># Ignores time jumps if they share tzinfo object.</span>
  624. &lt;TD&gt; = &lt;DT_UTC&gt; - &lt;DT_UTC&gt; <span class="hljs-comment"># Convert DTs to UTC to get the actual delta.</span>
  625. </code></pre></div>
  626. <div><h2 id="arguments"><a href="#arguments" name="arguments">#</a>Arguments</h2><div><h3 id="insidefunctioncall">Inside Function Call</h3><pre><code class="python language-python hljs">&lt;function&gt;(&lt;positional_args&gt;) <span class="hljs-comment"># f(0, 0)</span>
  627. &lt;function&gt;(&lt;keyword_args&gt;) <span class="hljs-comment"># f(x=0, y=0)</span>
  628. &lt;function&gt;(&lt;positional_args&gt;, &lt;keyword_args&gt;) <span class="hljs-comment"># f(0, y=0)</span>
  629. </code></pre></div></div>
  630. <div><h3 id="insidefunctiondefinition">Inside Function Definition</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(&lt;nondefault_args&gt;)</span>:</span> <span class="hljs-comment"># def f(x, y):</span>
  631. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(&lt;default_args&gt;)</span>:</span> <span class="hljs-comment"># def f(x=0, y=0):</span>
  632. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(&lt;nondefault_args&gt;, &lt;default_args&gt;)</span>:</span> <span class="hljs-comment"># def f(x, y=0):</span>
  633. </code></pre></div>
  634. <div><h2 id="splatoperator"><a href="#splatoperator" name="splatoperator">#</a>Splat Operator</h2><div><h3 id="insidefunctioncall-1">Inside Function Call</h3><p><strong>Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.</strong></p><pre><code class="python language-python hljs">args = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
  635. kwargs = {<span class="hljs-string">'x'</span>: <span class="hljs-number">3</span>, <span class="hljs-string">'y'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'z'</span>: <span class="hljs-number">5</span>}
  636. func(*args, **kwargs)
  637. </code></pre></div></div>
  638. <div><h4 id="isthesameas">Is the same as:</h4><pre><code class="python language-python hljs">func(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, x=<span class="hljs-number">3</span>, y=<span class="hljs-number">4</span>, z=<span class="hljs-number">5</span>)
  639. </code></pre></div>
  640. <div><h3 id="insidefunctiondefinition-1">Inside Function Definition</h3><p><strong>Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.</strong></p><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(*a)</span>:</span>
  641. <span class="hljs-keyword">return</span> sum(a)
  642. </code></pre></div>
  643. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>add(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  644. <span class="hljs-number">6</span>
  645. </code></pre>
  646. <div><h4 id="legalargumentcombinations">Legal argument combinations:</h4><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
  647. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*, x, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
  648. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *, y, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
  649. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, y, *, z)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span>
  650. </code></pre></div>
  651. <pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args)</span>:</span> <span class="hljs-comment"># f(1, 2, 3)</span>
  652. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args)</span>:</span> <span class="hljs-comment"># f(1, 2, 3)</span>
  653. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, z)</span>:</span> <span class="hljs-comment"># f(1, 2, z=3)</span>
  654. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, z)</span>:</span> <span class="hljs-comment"># f(1, 2, z=3)</span>
  655. </code></pre>
  656. <pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(**kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
  657. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
  658. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*, x, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3)</span>
  659. </code></pre>
  660. <pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
  661. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3)</span>
  662. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(*args, y, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3)</span>
  663. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">f</span><span class="hljs-params">(x, *args, z, **kwargs)</span>:</span> <span class="hljs-comment"># f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3)</span>
  664. </code></pre>
  665. <div><h3 id="otheruses">Other Uses</h3><pre><code class="python language-python hljs">&lt;list&gt; = [*&lt;collection&gt; [, ...]]
  666. &lt;set&gt; = {*&lt;collection&gt; [, ...]}
  667. &lt;tuple&gt; = (*&lt;collection&gt;, [...])
  668. &lt;dict&gt; = {**&lt;dict&gt; [, ...]}
  669. </code></pre></div>
  670. <pre><code class="python language-python hljs">head, *body, tail = &lt;collection&gt;
  671. </code></pre>
  672. <div><h2 id="inline"><a href="#inline" name="inline">#</a>Inline</h2><div><h3 id="lambda">Lambda</h3><pre><code class="python language-python hljs">&lt;function&gt; = <span class="hljs-keyword">lambda</span>: &lt;return_value&gt;
  673. &lt;function&gt; = <span class="hljs-keyword">lambda</span> &lt;argument_1&gt;, &lt;argument_2&gt;: &lt;return_value&gt;
  674. </code></pre></div></div>
  675. <div><h3 id="comprehension">Comprehension</h3><pre><code class="python language-python hljs">&lt;list&gt; = [i+<span class="hljs-number">1</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)] <span class="hljs-comment"># [1, 2, ..., 10]</span>
  676. &lt;set&gt; = {i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>) <span class="hljs-keyword">if</span> i &gt; <span class="hljs-number">5</span>} <span class="hljs-comment"># {6, 7, 8, 9}</span>
  677. &lt;iter&gt; = (i+<span class="hljs-number">5</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (5, 6, ..., 14)</span>
  678. &lt;dict&gt; = {i: i*<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)} <span class="hljs-comment"># {0: 0, 1: 2, ..., 9: 18}</span>
  679. </code></pre></div>
  680. <pre><code class="python language-python hljs">out = [i+j <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>) <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)]
  681. </code></pre>
  682. <div><h4 id="isthesameas-1">Is the same as:</h4><pre><code class="python language-python hljs">out = []
  683. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  684. <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  685. out.append(i+j)
  686. </code></pre></div>
  687. <div><h3 id="mapfilterreduce">Map, Filter, Reduce</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> reduce
  688. &lt;iter&gt; = map(<span class="hljs-keyword">lambda</span> x: x + <span class="hljs-number">1</span>, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (1, 2, ..., 10)</span>
  689. &lt;iter&gt; = filter(<span class="hljs-keyword">lambda</span> x: x &gt; <span class="hljs-number">5</span>, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># (6, 7, 8, 9)</span>
  690. &lt;obj&gt; = reduce(<span class="hljs-keyword">lambda</span> out, x: out + x, range(<span class="hljs-number">10</span>)) <span class="hljs-comment"># 45</span>
  691. </code></pre></div>
  692. <div><h3 id="anyall">Any, All</h3><pre><code class="python language-python hljs">&lt;bool&gt; = any(&lt;collection&gt;) <span class="hljs-comment"># False if empty.</span>
  693. &lt;bool&gt; = all(el[<span class="hljs-number">1</span>] <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> &lt;collection&gt;) <span class="hljs-comment"># True if empty.</span>
  694. </code></pre></div>
  695. <div><h3 id="ifelse">If - Else</h3><pre><code class="python language-python hljs">&lt;obj&gt; = &lt;expression_if_true&gt; <span class="hljs-keyword">if</span> &lt;condition&gt; <span class="hljs-keyword">else</span> &lt;expression_if_false&gt;
  696. </code></pre></div>
  697. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>[a <span class="hljs-keyword">if</span> a <span class="hljs-keyword">else</span> <span class="hljs-string">'zero'</span> <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> (<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)]
  698. [<span class="hljs-string">'zero'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  699. </code></pre>
  700. <div><h3 id="namedtupleenumdataclass">Namedtuple, Enum, Dataclass</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  701. Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  702. point = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
  703. </code></pre></div>
  704. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  705. Direction = Enum(<span class="hljs-string">'Direction'</span>, <span class="hljs-string">'n e s w'</span>)
  706. direction = Direction.n
  707. </code></pre>
  708. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  709. Creature = make_dataclass(<span class="hljs-string">'Creature'</span>, [<span class="hljs-string">'location'</span>, <span class="hljs-string">'direction'</span>])
  710. creature = Creature(Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), Direction.n)
  711. </code></pre>
  712. <div><h2 id="closure"><a href="#closure" name="closure">#</a>Closure</h2><p><strong>We have a closure in Python when:</strong></p><ul>
  713. <li><strong>A nested function references a value of its enclosing function and then</strong></li>
  714. <li><strong>the enclosing function returns the nested function.</strong></li>
  715. </ul><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_multiplier</span><span class="hljs-params">(a)</span>:</span>
  716. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(b)</span>:</span>
  717. <span class="hljs-keyword">return</span> a * b
  718. <span class="hljs-keyword">return</span> out
  719. </code></pre></div>
  720. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3 = get_multiplier(<span class="hljs-number">3</span>)
  721. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  722. <span class="hljs-number">30</span>
  723. </code></pre>
  724. <ul>
  725. <li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
  726. <li><strong>To dynamically access function's first free variable use <code class="python hljs"><span class="hljs-string">'&lt;function&gt;.__closure__[0].cell_contents'</span></code>.</strong></li>
  727. </ul>
  728. <div><h3 id="partial">Partial</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial
  729. &lt;function&gt; = partial(&lt;function&gt; [, &lt;arg_1&gt;, &lt;arg_2&gt;, ...])
  730. </code></pre></div>
  731. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  732. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3 = partial(op.mul, <span class="hljs-number">3</span>)
  733. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  734. <span class="hljs-number">30</span>
  735. </code></pre>
  736. <ul>
  737. <li><strong>Partial is also useful in cases when function needs to be passed as an argument, because it enables us to set its arguments beforehand.</strong></li>
  738. <li><strong>A few examples being: <code class="python hljs"><span class="hljs-string">'defaultdict(&lt;function&gt;)'</span></code>, <code class="python hljs"><span class="hljs-string">'iter(&lt;function&gt;, to_exclusive)'</span></code> and dataclass's <code class="python hljs"><span class="hljs-string">'field(default_factory=&lt;function&gt;)'</span></code>.</strong></li>
  739. </ul>
  740. <div><h3 id="nonlocal">Non-Local</h3><p><strong>If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or a 'nonlocal'.</strong></p><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_counter</span><span class="hljs-params">()</span>:</span>
  741. i = <span class="hljs-number">0</span>
  742. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">()</span>:</span>
  743. <span class="hljs-keyword">nonlocal</span> i
  744. i += <span class="hljs-number">1</span>
  745. <span class="hljs-keyword">return</span> i
  746. <span class="hljs-keyword">return</span> out
  747. </code></pre></div>
  748. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = get_counter()
  749. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  750. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  751. </code></pre>
  752. <div><h2 id="decorator"><a href="#decorator" name="decorator">#</a>Decorator</h2><p><strong>A decorator takes a function, adds some functionality and returns it.</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">@decorator_name</span>
  753. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">function_that_gets_passed_to_decorator</span><span class="hljs-params">()</span>:</span>
  754. ...
  755. </code></pre></div>
  756. <div><h3 id="debuggerexample">Debugger Example</h3><p><strong>Decorator that prints function's name every time it gets called.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
  757. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(func)</span>:</span>
  758. <span class="hljs-meta"> @wraps(func)</span>
  759. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  760. print(func.__name__)
  761. <span class="hljs-keyword">return</span> func(*args, **kwargs)
  762. <span class="hljs-keyword">return</span> out
  763. <span class="hljs-meta">@debug</span>
  764. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  765. <span class="hljs-keyword">return</span> x + y
  766. </code></pre></div>
  767. <ul>
  768. <li><strong>Wraps is a helper decorator that copies the metadata of the passed function (func) to the function it is wrapping (out).</strong></li>
  769. <li><strong>Without it <code class="python hljs"><span class="hljs-string">'add.__name__'</span></code> would return <code class="python hljs"><span class="hljs-string">'out'</span></code>.</strong></li>
  770. </ul>
  771. <div><h3 id="lrucache">LRU Cache</h3><p><strong>Decorator that caches function's return values. All function's arguments must be hashable.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache
  772. <span class="hljs-meta">@lru_cache(maxsize=None)</span>
  773. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>
  774. <span class="hljs-keyword">return</span> n <span class="hljs-keyword">if</span> n &lt; <span class="hljs-number">2</span> <span class="hljs-keyword">else</span> fib(n-<span class="hljs-number">2</span>) + fib(n-<span class="hljs-number">1</span>)
  775. </code></pre></div>
  776. <ul>
  777. <li><strong>CPython interpreter limits recursion depth to 1000 by default. To increase it use <code class="python hljs"><span class="hljs-string">'sys.setrecursionlimit(&lt;depth&gt;)'</span></code>.</strong></li>
  778. </ul>
  779. <div><h3 id="parametrizeddecorator">Parametrized Decorator</h3><p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
  780. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(print_result=False)</span>:</span>
  781. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>
  782. <span class="hljs-meta"> @wraps(func)</span>
  783. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  784. result = func(*args, **kwargs)
  785. print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>)
  786. <span class="hljs-keyword">return</span> result
  787. <span class="hljs-keyword">return</span> out
  788. <span class="hljs-keyword">return</span> decorator
  789. <span class="hljs-meta">@debug(print_result=True)</span>
  790. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  791. <span class="hljs-keyword">return</span> x + y
  792. </code></pre></div>
  793. <div><h2 id="class"><a href="#class" name="class">#</a>Class</h2><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">name</span>&gt;:</span>
  794. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  795. self.a = a
  796. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span><span class="hljs-params">(self)</span>:</span>
  797. class_name = self.__class__.__name__
  798. <span class="hljs-keyword">return</span> <span class="hljs-string">f'<span class="hljs-subst">{class_name}</span>(<span class="hljs-subst">{self.a!r}</span>)'</span>
  799. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
  800. <span class="hljs-keyword">return</span> str(self.a)
  801. <span class="hljs-meta"> @classmethod</span>
  802. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_class_name</span><span class="hljs-params">(cls)</span>:</span>
  803. <span class="hljs-keyword">return</span> cls.__name__
  804. </code></pre></div>
  805. <ul>
  806. <li><strong>Return value of repr() should be unambiguous and of str() readable.</strong></li>
  807. <li><strong>If only repr() is defined, it will also be used for str().</strong></li>
  808. </ul>
  809. <div><h4 id="strusecases">Str() use cases:</h4><pre><code class="python language-python hljs">print(&lt;el&gt;)
  810. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;}</span>'</span>)
  811. <span class="hljs-keyword">raise</span> Exception(&lt;el&gt;)
  812. loguru.logger.debug(&lt;el&gt;)
  813. csv.writer(&lt;file&gt;).writerow([&lt;el&gt;])
  814. </code></pre></div>
  815. <div><h4 id="reprusecases">Repr() use cases:</h4><pre><code class="python language-python hljs">print([&lt;el&gt;])
  816. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;!r}</span>'</span>)
  817. <span class="hljs-meta">&gt;&gt;&gt; </span>&lt;el&gt;
  818. loguru.logger.exception()
  819. Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span class="hljs-string">'a'</span>]); print(Z(&lt;el&gt;))
  820. </code></pre></div>
  821. <div><h3 id="constructoroverloading">Constructor Overloading</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">name</span>&gt;:</span>
  822. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a=None)</span>:</span>
  823. self.a = a
  824. </code></pre></div>
  825. <div><h3 id="inheritance">Inheritance</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
  826. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, age)</span>:</span>
  827. self.name = name
  828. self.age = age
  829. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Person)</span>:</span>
  830. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, name, age, staff_num)</span>:</span>
  831. super().__init__(name, age)
  832. self.staff_num = staff_num
  833. </code></pre></div>
  834. <div><h3 id="multipleinheritance">Multiple Inheritance</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">A</span>:</span> <span class="hljs-keyword">pass</span>
  835. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>:</span> <span class="hljs-keyword">pass</span>
  836. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">C</span><span class="hljs-params">(A, B)</span>:</span> <span class="hljs-keyword">pass</span>
  837. </code></pre></div>
  838. <p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong></p>
  839. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>C.mro()
  840. [&lt;<span class="hljs-class"><span class="hljs-title">class</span> '<span class="hljs-title">C</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">A</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">B</span>'&gt;, &lt;<span class="hljs-title">class</span> '<span class="hljs-title">object</span>'&gt;]
  841. </span></code></pre>
  842. <div><h3 id="property">Property</h3><p><strong>Pythonic way of implementing getters and setters.</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>:</span>
  843. <span class="hljs-meta"> @property</span>
  844. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  845. <span class="hljs-keyword">return</span> self._a
  846. <span class="hljs-meta"> @a.setter</span>
  847. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self, value)</span>:</span>
  848. self._a = value
  849. </code></pre></div>
  850. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>el = MyClass()
  851. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a = <span class="hljs-number">123</span>
  852. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a
  853. <span class="hljs-number">123</span>
  854. </code></pre>
  855. <div><h3 id="dataclass">Dataclass</h3><p><strong>Decorator that automatically generates init(), repr() and eq() special methods.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass, field
  856. <span class="hljs-meta">@dataclass(order=False, frozen=False)</span>
  857. <span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>
  858. &lt;attr_name_1&gt;: &lt;type&gt;
  859. &lt;attr_name_2&gt;: &lt;type&gt; = &lt;default_value&gt;
  860. &lt;attr_name_3&gt;: list/dict/set = field(default_factory=list/dict/set)
  861. </code></pre></div>
  862. <ul>
  863. <li><strong>Objects can be made sortable with <code class="python hljs"><span class="hljs-string">'order=True'</span></code> and/or immutable and hashable with <code class="python hljs"><span class="hljs-string">'frozen=True'</span></code>.</strong></li>
  864. <li><strong>Function field() is needed because <code class="python hljs"><span class="hljs-string">'&lt;attr_name&gt;: list = []'</span></code> would make a list that is shared among all instances.</strong></li>
  865. <li><strong>Default_factory can be any <a href="#callable">callable</a>.</strong></li>
  866. </ul>
  867. <div><h4 id="inline-1">Inline:</h4><pre><code class="python language-python hljs"><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  868. &lt;class&gt; = make_dataclass(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;coll_of_attribute_names&gt;)
  869. &lt;class&gt; = make_dataclass(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;coll_of_tuples&gt;)
  870. &lt;tuple&gt; = (<span class="hljs-string">'&lt;attr_name&gt;'</span>, &lt;type&gt; [, &lt;default_value&gt;])</code></code></pre></div>
  871. <div><h3 id="slots">Slots</h3><p><strong>Mechanism that restricts objects to attributes listed in 'slots' and significantly reduces their memory footprint.</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClassWithSlots</span>:</span>
  872. __slots__ = [<span class="hljs-string">'a'</span>]
  873. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  874. self.a = <span class="hljs-number">1</span>
  875. </code></pre></div>
  876. <div><h3 id="copy">Copy</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> copy <span class="hljs-keyword">import</span> copy, deepcopy
  877. &lt;object&gt; = copy(&lt;object&gt;)
  878. &lt;object&gt; = deepcopy(&lt;object&gt;)
  879. </code></pre></div>
  880. <div><h2 id="ducktypes"><a href="#ducktypes" name="ducktypes">#</a>Duck Types</h2><p><strong>A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.</strong></p><div><h3 id="comparable">Comparable</h3><ul>
  881. <li><strong>If eq() method is not overridden, it returns <code class="python hljs"><span class="hljs-string">'id(self) == id(other)'</span></code>, which is the same as <code class="python hljs"><span class="hljs-string">'self is other'</span></code>.</strong></li>
  882. <li><strong>That means all objects compare not equal by default.</strong></li>
  883. <li><strong>Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted.</strong></li>
  884. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComparable</span>:</span>
  885. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  886. self.a = a
  887. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  888. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  889. <span class="hljs-keyword">return</span> self.a == other.a
  890. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  891. </code></pre></div></div>
  892. <div><h3 id="hashable">Hashable</h3><ul>
  893. <li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
  894. <li><strong>Hashable objects that compare equal must have the same hash value, meaning default hash() that returns <code class="python hljs"><span class="hljs-string">'id(self)'</span></code> will not do.</strong></li>
  895. <li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
  896. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHashable</span>:</span>
  897. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  898. self._a = a
  899. <span class="hljs-meta"> @property</span>
  900. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  901. <span class="hljs-keyword">return</span> self._a
  902. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  903. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  904. <span class="hljs-keyword">return</span> self.a == other.a
  905. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  906. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__hash__</span><span class="hljs-params">(self)</span>:</span>
  907. <span class="hljs-keyword">return</span> hash(self.a)
  908. </code></pre></div>
  909. <div><h3 id="sortable">Sortable</h3><ul>
  910. <li><strong>With total_ordering decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.</strong></li>
  911. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> total_ordering
  912. <span class="hljs-meta">@total_ordering</span>
  913. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySortable</span>:</span>
  914. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  915. self.a = a
  916. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  917. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  918. <span class="hljs-keyword">return</span> self.a == other.a
  919. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  920. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__lt__</span><span class="hljs-params">(self, other)</span>:</span>
  921. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  922. <span class="hljs-keyword">return</span> self.a &lt; other.a
  923. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  924. </code></pre></div>
  925. <div><h3 id="iterator-1">Iterator</h3><ul>
  926. <li><strong>Any object that has methods next() and iter() is an iterator.</strong></li>
  927. <li><strong>Next() should return next item or raise StopIteration.</strong></li>
  928. <li><strong>Iter() should return 'self'.</strong></li>
  929. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
  930. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  931. self.i = <span class="hljs-number">0</span>
  932. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__next__</span><span class="hljs-params">(self)</span>:</span>
  933. self.i += <span class="hljs-number">1</span>
  934. <span class="hljs-keyword">return</span> self.i
  935. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  936. <span class="hljs-keyword">return</span> self
  937. </code></pre></div>
  938. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  939. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  940. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  941. </code></pre>
  942. <div><h4 id="pythonhasmanydifferentiteratorobjects">Python has many different iterator objects:</h4><ul>
  943. <li><strong>Iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong></li>
  944. <li><strong>Objects returned by the <a href="#itertools">itertools</a> module, such as count, repeat and cycle.</strong></li>
  945. <li><strong>Generators returned by the <a href="#generator">generator functions</a> and <a href="#comprehension">generator expressions</a>.</strong></li>
  946. <li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li>
  947. </ul><div><h3 id="callable">Callable</h3><ul>
  948. <li><strong>All functions and classes have a call() method, hence are callable.</strong></li>
  949. <li><strong>When this cheatsheet uses <code class="python hljs"><span class="hljs-string">'&lt;function&gt;'</span></code> as an argument, it actually means <code class="python hljs"><span class="hljs-string">'&lt;callable&gt;'</span></code>.</strong></li>
  950. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
  951. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  952. self.i = <span class="hljs-number">0</span>
  953. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self)</span>:</span>
  954. self.i += <span class="hljs-number">1</span>
  955. <span class="hljs-keyword">return</span> self.i
  956. </code></pre></div></div>
  957. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  958. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  959. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  960. </code></pre>
  961. <div><h3 id="contextmanager">Context Manager</h3><ul>
  962. <li><strong>Enter() should lock the resources and optionally return an object.</strong></li>
  963. <li><strong>Exit() should release the resources.</strong></li>
  964. <li><strong>Any exception that happens inside the with block is passed to the exit() method.</strong></li>
  965. <li><strong>If it wishes to suppress the exception it must return a true value.</strong></li>
  966. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyOpen</span>:</span>
  967. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, filename)</span>:</span>
  968. self.filename = filename
  969. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span><span class="hljs-params">(self)</span>:</span>
  970. self.file = open(self.filename)
  971. <span class="hljs-keyword">return</span> self.file
  972. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, exc_type, exception, traceback)</span>:</span>
  973. self.file.close()
  974. </code></pre></div>
  975. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> open(<span class="hljs-string">'test.txt'</span>, <span class="hljs-string">'w'</span>) <span class="hljs-keyword">as</span> file:
  976. <span class="hljs-meta">... </span> file.write(<span class="hljs-string">'Hello World!'</span>)
  977. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">with</span> MyOpen(<span class="hljs-string">'test.txt'</span>) <span class="hljs-keyword">as</span> file:
  978. <span class="hljs-meta">... </span> print(file.read())
  979. Hello World!
  980. </code></pre>
  981. <div><h2 id="iterableducktypes"><a href="#iterableducktypes" name="iterableducktypes">#</a>Iterable Duck Types</h2><div><h3 id="iterable">Iterable</h3><ul>
  982. <li><strong>Only required method is iter(). It should return an iterator of object's items.</strong></li>
  983. <li><strong>Contains() automatically works on any object that has iter() defined.</strong></li>
  984. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyIterable</span>:</span>
  985. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  986. self.a = a
  987. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  988. <span class="hljs-keyword">return</span> iter(self.a)
  989. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  990. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  991. </code></pre></div></div>
  992. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>obj = MyIterable([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
  993. <span class="hljs-meta">&gt;&gt;&gt; </span>[el <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> obj]
  994. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  995. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">1</span> <span class="hljs-keyword">in</span> obj
  996. <span class="hljs-keyword">True</span>
  997. </code></pre>
  998. <div><h3 id="collection">Collection</h3><ul>
  999. <li><strong>Only required methods are iter() and len().</strong></li>
  1000. <li><strong>This cheatsheet actually means <code class="python hljs"><span class="hljs-string">'&lt;iterable&gt;'</span></code> when it uses <code class="python hljs"><span class="hljs-string">'&lt;collection&gt;'</span></code>.</strong></li>
  1001. <li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.</strong></li>
  1002. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCollection</span>:</span>
  1003. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1004. self.a = a
  1005. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  1006. <span class="hljs-keyword">return</span> iter(self.a)
  1007. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  1008. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  1009. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  1010. <span class="hljs-keyword">return</span> len(self.a)
  1011. </code></pre></div>
  1012. <div><h3 id="sequence">Sequence</h3><ul>
  1013. <li><strong>Only required methods are len() and getitem().</strong></li>
  1014. <li><strong>Getitem() should return an item at index or raise IndexError.</strong></li>
  1015. <li><strong>Iter() and contains() automatically work on any object that has getitem() defined.</strong></li>
  1016. <li><strong>Reversed() automatically works on any object that has getitem() and len() defined.</strong></li>
  1017. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySequence</span>:</span>
  1018. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1019. self.a = a
  1020. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  1021. <span class="hljs-keyword">return</span> iter(self.a)
  1022. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  1023. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  1024. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  1025. <span class="hljs-keyword">return</span> len(self.a)
  1026. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  1027. <span class="hljs-keyword">return</span> self.a[i]
  1028. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__reversed__</span><span class="hljs-params">(self)</span>:</span>
  1029. <span class="hljs-keyword">return</span> reversed(self.a)
  1030. </code></pre></div>
  1031. <div><h3 id="abcsequence">ABC Sequence</h3><ul>
  1032. <li><strong>It's a richer interface than the basic sequence.</strong></li>
  1033. <li><strong>Extending it generates iter(), contains(), reversed(), index() and count().</strong></li>
  1034. <li><strong>Unlike <code class="python hljs"><span class="hljs-string">'abc.Iterable'</span></code> and <code class="python hljs"><span class="hljs-string">'abc.Collection'</span></code>, it is not a duck type. That is why <code class="python hljs"><span class="hljs-string">'issubclass(MySequence, abc.Sequence)'</span></code> would return False even if MySequence had all the methods defined.</strong></li>
  1035. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> abc
  1036. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAbcSequence</span><span class="hljs-params">(abc.Sequence)</span>:</span>
  1037. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1038. self.a = a
  1039. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  1040. <span class="hljs-keyword">return</span> len(self.a)
  1041. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  1042. <span class="hljs-keyword">return</span> self.a[i]
  1043. </code></pre></div>
  1044. <div><h4 id="tableofrequiredandautomaticallyavailablespecialmethods">Table of required and automatically available special methods:</h4><pre><code class="text language-text">┏━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
  1045. ┃ │ Iterable │ Collection │ Sequence │ abc.Sequence ┃
  1046. ┠────────────┼────────────┼────────────┼────────────┼──────────────┨
  1047. ┃ iter() │ ! │ ! │ ✓ │ ✓ ┃
  1048. ┃ contains() │ ✓ │ ✓ │ ✓ │ ✓ ┃
  1049. ┃ len() │ │ ! │ ! │ ! ┃
  1050. ┃ getitem() │ │ │ ! │ ! ┃
  1051. ┃ reversed() │ │ │ ✓ │ ✓ ┃
  1052. ┃ index() │ │ │ │ ✓ ┃
  1053. ┃ count() │ │ │ │ ✓ ┃
  1054. ┗━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
  1055. </code></pre></div>
  1056. <ul>
  1057. <li><strong>Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.</strong></li>
  1058. <li><strong>Names of their required methods are stored in <code class="python hljs"><span class="hljs-string">'&lt;abc&gt;.__abstractmethods__'</span></code>.</strong></li>
  1059. </ul>
  1060. <div><h2 id="enum"><a href="#enum" name="enum">#</a>Enum</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum, auto
  1061. <span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">enum_name</span>&gt;<span class="hljs-params">(Enum)</span>:</span>
  1062. &lt;member_name_1&gt; = &lt;value_1&gt;
  1063. &lt;member_name_2&gt; = &lt;value_2_a&gt;, &lt;value_2_b&gt;
  1064. &lt;member_name_3&gt; = auto()
  1065. </code></pre></div>
  1066. <ul>
  1067. <li><strong>If there are no numeric values before auto(), it returns 1.</strong></li>
  1068. <li><strong>Otherwise it returns an increment of the last numeric value.</strong></li>
  1069. </ul>
  1070. <pre><code class="python language-python hljs">&lt;member&gt; = &lt;enum&gt;.&lt;member_name&gt; <span class="hljs-comment"># Returns a member.</span>
  1071. &lt;member&gt; = &lt;enum&gt;[<span class="hljs-string">'&lt;member_name&gt;'</span>] <span class="hljs-comment"># Returns a member or raises KeyError.</span>
  1072. &lt;member&gt; = &lt;enum&gt;(&lt;value&gt;) <span class="hljs-comment"># Returns a member or raises ValueError.</span>
  1073. &lt;str&gt; = &lt;member&gt;.name <span class="hljs-comment"># Returns member's name.</span>
  1074. &lt;obj&gt; = &lt;member&gt;.value <span class="hljs-comment"># Returns member's value.</span>
  1075. </code></pre>
  1076. <pre><code class="python language-python hljs">list_of_members = list(&lt;enum&gt;)
  1077. member_names = [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1078. member_values = [a.value <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1079. random_member = random.choice(list(&lt;enum&gt;))
  1080. </code></pre>
  1081. <pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_next_member</span><span class="hljs-params">(member)</span>:</span>
  1082. members = list(member.__class__)
  1083. index = (members.index(member) + <span class="hljs-number">1</span>) % len(members)
  1084. <span class="hljs-keyword">return</span> members[index]
  1085. </code></pre>
  1086. <div><h3 id="inline-2">Inline</h3><pre><code class="python language-python hljs">Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, <span class="hljs-string">'fork knife spoon'</span>)
  1087. Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, [<span class="hljs-string">'fork'</span>, <span class="hljs-string">'knife'</span>, <span class="hljs-string">'spoon'</span>])
  1088. Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, {<span class="hljs-string">'fork'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'knife'</span>: <span class="hljs-number">2</span>, <span class="hljs-string">'spoon'</span>: <span class="hljs-number">3</span>})
  1089. </code></pre></div>
  1090. <div><h4 id="userdefinedfunctionscannotbevaluessotheymustbewrapped">User-defined functions cannot be values, so they must be wrapped:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial
  1091. LogicOp = Enum(<span class="hljs-string">'LogicOp'</span>, {<span class="hljs-string">'AND'</span>: partial(<span class="hljs-keyword">lambda</span> l, r: l <span class="hljs-keyword">and</span> r),
  1092. <span class="hljs-string">'OR'</span> : partial(<span class="hljs-keyword">lambda</span> l, r: l <span class="hljs-keyword">or</span> r)})
  1093. </code></pre></div>
  1094. <ul>
  1095. <li><strong>Another solution in this particular case is to use built-in functions and_() and or_() from the module <a href="#operator">operator</a>.</strong></li>
  1096. </ul>
  1097. <div><h2 id="exceptions"><a href="#exceptions" name="exceptions">#</a>Exceptions</h2><div><h3 id="basicexample">Basic Example</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">try</span>:
  1098. &lt;code&gt;
  1099. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1100. &lt;code&gt;
  1101. </code></pre></div></div>
  1102. <div><h3 id="complexexample">Complex Example</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">try</span>:
  1103. &lt;code_1&gt;
  1104. <span class="hljs-keyword">except</span> &lt;exception_a&gt;:
  1105. &lt;code_2_a&gt;
  1106. <span class="hljs-keyword">except</span> &lt;exception_b&gt;:
  1107. &lt;code_2_b&gt;
  1108. <span class="hljs-keyword">else</span>:
  1109. &lt;code_2_c&gt;
  1110. <span class="hljs-keyword">finally</span>:
  1111. &lt;code_3&gt;
  1112. </code></pre></div>
  1113. <div><h3 id="catchingexceptions">Catching Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">except</span> &lt;exception&gt;:
  1114. <span class="hljs-keyword">except</span> &lt;exception&gt; <span class="hljs-keyword">as</span> &lt;name&gt;:
  1115. <span class="hljs-keyword">except</span> (&lt;exception&gt;, ...):
  1116. <span class="hljs-keyword">except</span> (&lt;exception&gt;, ...) <span class="hljs-keyword">as</span> &lt;name&gt;:
  1117. </code></pre></div>
  1118. <ul>
  1119. <li><strong>Also catches subclasses of the exception.</strong></li>
  1120. <li><strong>Use <code class="python hljs"><span class="hljs-string">'traceback.print_exc()'</span></code> to print the error message to stderr.</strong></li>
  1121. </ul>
  1122. <div><h3 id="raisingexceptions">Raising Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> &lt;exception&gt;
  1123. <span class="hljs-keyword">raise</span> &lt;exception&gt;()
  1124. <span class="hljs-keyword">raise</span> &lt;exception&gt;(&lt;el&gt; [, ...])
  1125. </code></pre></div>
  1126. <div><h4 id="reraisingcaughtexception">Re-raising caught exception:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">except</span> &lt;exception&gt; <span class="hljs-keyword">as</span> &lt;name&gt;:
  1127. ...
  1128. <span class="hljs-keyword">raise</span>
  1129. </code></pre></div>
  1130. <div><h3 id="exceptionobject">Exception Object</h3><pre><code class="python language-python hljs">arguments = &lt;name&gt;.args
  1131. exc_type = &lt;name&gt;.__class__
  1132. filename = &lt;name&gt;.__traceback__.tb_frame.f_code.co_filename
  1133. func_name = &lt;name&gt;.__traceback__.tb_frame.f_code.co_name
  1134. line = linecache.getline(filename, &lt;name&gt;.__traceback__.tb_lineno)
  1135. error_msg = traceback.format_exception(exc_type, &lt;name&gt;, &lt;name&gt;.__traceback__)
  1136. </code></pre></div>
  1137. <div><h3 id="builtinexceptions">Built-in Exceptions</h3><pre><code class="text language-text">BaseException
  1138. ├── SystemExit <span class="hljs-comment"># Raised by the sys.exit() function.</span>
  1139. ├── KeyboardInterrupt <span class="hljs-comment"># Raised when the user hits the interrupt key (ctrl-c).</span>
  1140. └── Exception <span class="hljs-comment"># User-defined exceptions should be derived from this class.</span>
  1141. ├── ArithmeticError <span class="hljs-comment"># Base class for arithmetic errors.</span>
  1142. │ └── ZeroDivisionError <span class="hljs-comment"># Raised when dividing by zero.</span>
  1143. ├── AttributeError <span class="hljs-comment"># Raised when an attribute is missing.</span>
  1144. ├── EOFError <span class="hljs-comment"># Raised by input() when it hits end-of-file condition.</span>
  1145. ├── LookupError <span class="hljs-comment"># Raised when a look-up on a collection fails.</span>
  1146. │ ├── IndexError <span class="hljs-comment"># Raised when a sequence index is out of range.</span>
  1147. │ └── KeyError <span class="hljs-comment"># Raised when a dictionary key or set element is not found.</span>
  1148. ├── NameError <span class="hljs-comment"># Raised when a variable name is not found.</span>
  1149. ├── OSError <span class="hljs-comment"># Failures such as “file not found” or “disk full”.</span>
  1150. │ └── FileNotFoundError <span class="hljs-comment"># When a file or directory is requested but doesn't exist.</span>
  1151. ├── RuntimeError <span class="hljs-comment"># Raised by errors that don't fall in other categories.</span>
  1152. │ └── RecursionError <span class="hljs-comment"># Raised when the maximum recursion depth is exceeded.</span>
  1153. ├── StopIteration <span class="hljs-comment"># Raised by next() when run on an empty iterator.</span>
  1154. ├── TypeError <span class="hljs-comment"># Raised when an argument is of wrong type.</span>
  1155. └── ValueError <span class="hljs-comment"># When an argument is of right type but inappropriate value.</span>
  1156. └── UnicodeError <span class="hljs-comment"># Raised when encoding/decoding strings to/from bytes fails.</span>
  1157. </code></pre></div>
  1158. <div><h4 id="collectionsandtheirexceptions">Collections and their exceptions:</h4><pre><code class="text language-text">┏━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┯━━━━━━━━━━━━┓
  1159. ┃ │ list │ dict │ set ┃
  1160. ┠───────────┼────────────┼────────────┼────────────┨
  1161. ┃ getitem() │ IndexError │ KeyError │ ┃
  1162. ┃ pop() │ IndexError │ KeyError │ KeyError ┃
  1163. ┃ remove() │ ValueError │ │ KeyError ┃
  1164. ┃ index() │ ValueError │ │ ┃
  1165. ┗━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┷━━━━━━━━━━━━┛
  1166. </code></pre></div>
  1167. <div><h4 id="usefulbuiltinexceptions">Useful built-in exceptions:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> TypeError(<span class="hljs-string">'Argument is of wrong type!'</span>)
  1168. <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">'Argument is of right type but inappropriate value!'</span>)
  1169. <span class="hljs-keyword">raise</span> RuntimeError(<span class="hljs-string">'None of above!'</span>)
  1170. </code></pre></div>
  1171. <div><h3 id="userdefinedexceptions">User-defined Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyError</span><span class="hljs-params">(Exception)</span>:</span>
  1172. <span class="hljs-keyword">pass</span>
  1173. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyInputError</span><span class="hljs-params">(MyError)</span>:</span>
  1174. <span class="hljs-keyword">pass</span>
  1175. </code></pre></div>
  1176. <div><h2 id="exit"><a href="#exit" name="exit">#</a>Exit</h2><p><strong>Exits the interpreter by raising SystemExit exception.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sys
  1177. sys.exit() <span class="hljs-comment"># Exits with exit code 0 (success).</span>
  1178. sys.exit(&lt;el&gt;) <span class="hljs-comment"># Prints to stderr and exits with 1.</span>
  1179. sys.exit(&lt;int&gt;) <span class="hljs-comment"># Exits with passed exit code.</span>
  1180. </code></pre></div>
  1181. <div class="pagebreak"></div><div><h2 id="print"><a href="#print" name="print">#</a>Print</h2><pre><code class="python language-python hljs">print(&lt;el_1&gt;, ..., sep=<span class="hljs-string">' '</span>, end=<span class="hljs-string">'\n'</span>, file=sys.stdout, flush=<span class="hljs-keyword">False</span>)
  1182. </code></pre></div>
  1183. <ul>
  1184. <li><strong>Use <code class="python hljs"><span class="hljs-string">'file=sys.stderr'</span></code> for messages about errors.</strong></li>
  1185. <li><strong>Use <code class="python hljs"><span class="hljs-string">'flush=True'</span></code> to forcibly flush the stream.</strong></li>
  1186. </ul>
  1187. <div><h3 id="prettyprint">Pretty Print</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> pprint <span class="hljs-keyword">import</span> pprint
  1188. pprint(&lt;collection&gt;, width=<span class="hljs-number">80</span>, depth=<span class="hljs-keyword">None</span>, compact=<span class="hljs-keyword">False</span>, sort_dicts=<span class="hljs-keyword">True</span>)
  1189. </code></pre></div>
  1190. <ul>
  1191. <li><strong>Levels deeper than 'depth' get replaced by '…'.</strong></li>
  1192. </ul>
  1193. <div><h2 id="input"><a href="#input" name="input">#</a>Input</h2><p><strong>Reads a line from user input or pipe if present.</strong></p><pre><code class="python language-python hljs">&lt;str&gt; = input(prompt=<span class="hljs-keyword">None</span>)
  1194. </code></pre></div>
  1195. <ul>
  1196. <li><strong>Trailing newline gets stripped.</strong></li>
  1197. <li><strong>Prompt string is printed to the standard output before reading input.</strong></li>
  1198. <li><strong>Raises EOFError when user hits EOF (ctrl-d/z) or input stream gets exhausted.</strong></li>
  1199. </ul>
  1200. <div><h2 id="commandlinearguments"><a href="#commandlinearguments" name="commandlinearguments">#</a>Command Line Arguments</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sys
  1201. script_name = sys.argv[<span class="hljs-number">0</span>]
  1202. arguments = sys.argv[<span class="hljs-number">1</span>:]
  1203. </code></pre></div>
  1204. <div><h3 id="argumentparser">Argument Parser</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> argparse <span class="hljs-keyword">import</span> ArgumentParser, FileType
  1205. p = ArgumentParser(description=&lt;str&gt;)
  1206. p.add_argument(<span class="hljs-string">'-&lt;short_name&gt;'</span>, <span class="hljs-string">'--&lt;name&gt;'</span>, action=<span class="hljs-string">'store_true'</span>) <span class="hljs-comment"># Flag</span>
  1207. p.add_argument(<span class="hljs-string">'-&lt;short_name&gt;'</span>, <span class="hljs-string">'--&lt;name&gt;'</span>, type=&lt;type&gt;) <span class="hljs-comment"># Option</span>
  1208. p.add_argument(<span class="hljs-string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="hljs-number">1</span>) <span class="hljs-comment"># First argument</span>
  1209. p.add_argument(<span class="hljs-string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="hljs-string">'+'</span>) <span class="hljs-comment"># Remaining arguments</span>
  1210. p.add_argument(<span class="hljs-string">'&lt;name&gt;'</span>, type=&lt;type&gt;, nargs=<span class="hljs-string">'*'</span>) <span class="hljs-comment"># Optional arguments</span>
  1211. args = p.parse_args() <span class="hljs-comment"># Exits on error.</span>
  1212. value = args.&lt;name&gt;
  1213. </code></pre></div>
  1214. <ul>
  1215. <li><strong>Use <code class="python hljs"><span class="hljs-string">'help=&lt;str&gt;'</span></code> to set argument description.</strong></li>
  1216. <li><strong>Use <code class="python hljs"><span class="hljs-string">'default=&lt;el&gt;'</span></code> to set the default value.</strong></li>
  1217. <li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files.</strong></li>
  1218. </ul>
  1219. <div><h2 id="open"><a href="#open" name="open">#</a>Open</h2><p><strong>Opens the file and returns a corresponding file object.</strong></p><pre><code class="python language-python hljs">&lt;file&gt; = open(<span class="hljs-string">'&lt;path&gt;'</span>, mode=<span class="hljs-string">'r'</span>, encoding=<span class="hljs-keyword">None</span>, newline=<span class="hljs-keyword">None</span>)
  1220. </code></pre></div>
  1221. <ul>
  1222. <li><strong><code class="python hljs"><span class="hljs-string">'encoding=None'</span></code> means that the default encoding is used, which is platform dependent. Best practice is to use <code class="python hljs"><span class="hljs-string">'encoding="utf-8"'</span></code> whenever possible.</strong></li>
  1223. <li><strong><code class="python hljs"><span class="hljs-string">'newline=None'</span></code> means all different end of line combinations are converted to '\n' on read, while on write all '\n' characters are converted to system's default line separator.</strong></li>
  1224. <li><strong><code class="python hljs"><span class="hljs-string">'newline=""'</span></code> means no conversions take place, but input is still broken into chunks by readline() and readlines() on either '\n', '\r' or '\r\n'.</strong></li>
  1225. </ul>
  1226. <div><h3 id="modes">Modes</h3><ul>
  1227. <li><strong><code class="python hljs"><span class="hljs-string">'r'</span></code> - Read (default).</strong></li>
  1228. <li><strong><code class="python hljs"><span class="hljs-string">'w'</span></code> - Write (truncate).</strong></li>
  1229. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - Write or fail if the file already exists.</strong></li>
  1230. <li><strong><code class="python hljs"><span class="hljs-string">'a'</span></code> - Append.</strong></li>
  1231. <li><strong><code class="python hljs"><span class="hljs-string">'w+'</span></code> - Read and write (truncate).</strong></li>
  1232. <li><strong><code class="python hljs"><span class="hljs-string">'r+'</span></code> - Read and write from the start.</strong></li>
  1233. <li><strong><code class="python hljs"><span class="hljs-string">'a+'</span></code> - Read and write from the end.</strong></li>
  1234. <li><strong><code class="python hljs"><span class="hljs-string">'t'</span></code> - Text mode (default).</strong></li>
  1235. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - Binary mode.</strong></li>
  1236. </ul><div><h3 id="exceptions-1">Exceptions</h3><ul>
  1237. <li><strong><code class="python hljs"><span class="hljs-string">'FileNotFoundError'</span></code> can be raised when reading with <code class="python hljs"><span class="hljs-string">'r'</span></code> or <code class="python hljs"><span class="hljs-string">'r+'</span></code>.</strong></li>
  1238. <li><strong><code class="python hljs"><span class="hljs-string">'FileExistsError'</span></code> can be raised when writing with <code class="python hljs"><span class="hljs-string">'x'</span></code>.</strong></li>
  1239. <li><strong><code class="python hljs"><span class="hljs-string">'IsADirectoryError'</span></code> and <code class="python hljs"><span class="hljs-string">'PermissionError'</span></code> can be raised by any.</strong></li>
  1240. <li><strong><code class="python hljs"><span class="hljs-string">'OSError'</span></code> is the parent class of all listed exceptions.</strong></li>
  1241. </ul><div><h3 id="fileobject">File Object</h3><pre><code class="python language-python hljs">&lt;file&gt;.seek(<span class="hljs-number">0</span>) <span class="hljs-comment"># Moves to the start of the file.</span>
  1242. &lt;file&gt;.seek(offset) <span class="hljs-comment"># Moves 'offset' chars/bytes from the start.</span>
  1243. &lt;file&gt;.seek(<span class="hljs-number">0</span>, <span class="hljs-number">2</span>) <span class="hljs-comment"># Moves to the end of the file.</span>
  1244. &lt;bin_file&gt;.seek(±offset, &lt;anchor&gt;) <span class="hljs-comment"># Anchor: 0 start, 1 current position, 2 end.</span>
  1245. </code></pre></div></div></div>
  1246. <pre><code class="python language-python hljs">&lt;str/bytes&gt; = &lt;file&gt;.read(size=<span class="hljs-number">-1</span>) <span class="hljs-comment"># Reads 'size' chars/bytes or until EOF.</span>
  1247. &lt;str/bytes&gt; = &lt;file&gt;.readline() <span class="hljs-comment"># Returns a line or empty string/bytes on EOF.</span>
  1248. &lt;list&gt; = &lt;file&gt;.readlines() <span class="hljs-comment"># Returns a list of remaining lines.</span>
  1249. &lt;str/bytes&gt; = next(&lt;file&gt;) <span class="hljs-comment"># Returns a line using buffer. Do not mix.</span>
  1250. </code></pre>
  1251. <pre><code class="python language-python hljs">&lt;file&gt;.write(&lt;str/bytes&gt;) <span class="hljs-comment"># Writes a string or bytes object.</span>
  1252. &lt;file&gt;.writelines(&lt;collection&gt;) <span class="hljs-comment"># Writes a coll. of strings or bytes objects.</span>
  1253. &lt;file&gt;.flush() <span class="hljs-comment"># Flushes write buffer.</span>
  1254. </code></pre>
  1255. <ul>
  1256. <li><strong>Methods do not add or strip trailing newlines, even writelines().</strong></li>
  1257. </ul>
  1258. <div><h3 id="readtextfromfile">Read Text from File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
  1259. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1260. <span class="hljs-keyword">return</span> file.readlines()
  1261. </code></pre></div>
  1262. <div><h3 id="writetexttofile">Write Text to File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_file</span><span class="hljs-params">(filename, text)</span>:</span>
  1263. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'w'</span>, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1264. file.write(text)
  1265. </code></pre></div>
  1266. <div><h2 id="path"><a href="#path" name="path">#</a>Path</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> getcwd, path, listdir
  1267. <span class="hljs-keyword">from</span> glob <span class="hljs-keyword">import</span> glob
  1268. </code></pre></div>
  1269. <pre><code class="python language-python hljs">&lt;str&gt; = getcwd() <span class="hljs-comment"># Returns the current working directory.</span>
  1270. &lt;str&gt; = path.join(&lt;path&gt;, ...) <span class="hljs-comment"># Joins two or more pathname components.</span>
  1271. &lt;str&gt; = path.abspath(&lt;path&gt;) <span class="hljs-comment"># Returns absolute path.</span>
  1272. </code></pre>
  1273. <pre><code class="python language-python hljs">&lt;str&gt; = path.basename(&lt;path&gt;) <span class="hljs-comment"># Returns final component of the path.</span>
  1274. &lt;str&gt; = path.dirname(&lt;path&gt;) <span class="hljs-comment"># Returns path without the final component.</span>
  1275. &lt;tup.&gt; = path.splitext(&lt;path&gt;) <span class="hljs-comment"># Splits on last period of the final component.</span>
  1276. </code></pre>
  1277. <pre><code class="python language-python hljs">&lt;list&gt; = listdir(path=<span class="hljs-string">'.'</span>) <span class="hljs-comment"># Returns filenames located at path.</span>
  1278. &lt;list&gt; = glob(<span class="hljs-string">'&lt;pattern&gt;'</span>) <span class="hljs-comment"># Returns paths matching the wildcard pattern.</span>
  1279. </code></pre>
  1280. <pre><code class="python language-python hljs">&lt;bool&gt; = path.exists(&lt;path&gt;) <span class="hljs-comment"># Or: &lt;Path&gt;.exists()</span>
  1281. &lt;bool&gt; = path.isfile(&lt;path&gt;) <span class="hljs-comment"># Or: &lt;DirEntry/Path&gt;.is_file()</span>
  1282. &lt;bool&gt; = path.isdir(&lt;path&gt;) <span class="hljs-comment"># Or: &lt;DirEntry/Path&gt;.is_dir()</span>
  1283. </code></pre>
  1284. <div><h3 id="direntry">DirEntry</h3><p><strong>Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type information.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> scandir
  1285. </code></pre></div>
  1286. <pre><code class="python language-python hljs">&lt;iter&gt; = scandir(path=<span class="hljs-string">'.'</span>) <span class="hljs-comment"># Returns DirEntry objects located at path.</span>
  1287. &lt;str&gt; = &lt;DirEntry&gt;.path <span class="hljs-comment"># Returns path as a string.</span>
  1288. &lt;str&gt; = &lt;DirEntry&gt;.name <span class="hljs-comment"># Returns final component as a string.</span>
  1289. &lt;file&gt; = open(&lt;DirEntry&gt;) <span class="hljs-comment"># Opens the file and returns file object.</span>
  1290. </code></pre>
  1291. <div><h3 id="pathobject">Path Object</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path
  1292. </code></pre></div>
  1293. <pre><code class="python language-python hljs">&lt;Path&gt; = Path(&lt;path&gt; [, ...]) <span class="hljs-comment"># Accepts strings, Paths and DirEntry objects.</span>
  1294. &lt;Path&gt; = &lt;path&gt; / &lt;path&gt; [/ ...] <span class="hljs-comment"># One of the paths must be a Path object.</span>
  1295. </code></pre>
  1296. <pre><code class="python language-python hljs">&lt;Path&gt; = Path() <span class="hljs-comment"># Returns relative cwd. Also Path('.').</span>
  1297. &lt;Path&gt; = Path.cwd() <span class="hljs-comment"># Returns absolute cwd. Also Path().resolve().</span>
  1298. &lt;Path&gt; = &lt;Path&gt;.resolve() <span class="hljs-comment"># Returns absolute Path without symlinks.</span>
  1299. </code></pre>
  1300. <pre><code class="python language-python hljs">&lt;Path&gt; = &lt;Path&gt;.parent <span class="hljs-comment"># Returns Path without final component.</span>
  1301. &lt;str&gt; = &lt;Path&gt;.name <span class="hljs-comment"># Returns final component as a string.</span>
  1302. &lt;str&gt; = &lt;Path&gt;.stem <span class="hljs-comment"># Returns final component without extension.</span>
  1303. &lt;str&gt; = &lt;Path&gt;.suffix <span class="hljs-comment"># Returns final component's extension.</span>
  1304. &lt;tup.&gt; = &lt;Path&gt;.parts <span class="hljs-comment"># Returns all components as strings.</span>
  1305. </code></pre>
  1306. <pre><code class="python language-python hljs">&lt;iter&gt; = &lt;Path&gt;.iterdir() <span class="hljs-comment"># Returns dir contents as Path objects.</span>
  1307. &lt;iter&gt; = &lt;Path&gt;.glob(<span class="hljs-string">'&lt;pattern&gt;'</span>) <span class="hljs-comment"># Returns Paths matching the wildcard pattern.</span>
  1308. </code></pre>
  1309. <pre><code class="python language-python hljs">&lt;str&gt; = str(&lt;Path&gt;) <span class="hljs-comment"># Returns path as a string.</span>
  1310. &lt;file&gt; = open(&lt;Path&gt;) <span class="hljs-comment"># Opens the file and returns file object.</span>
  1311. </code></pre>
  1312. <div><h2 id="oscommands"><a href="#oscommands" name="oscommands">#</a>OS Commands</h2><div><h3 id="filesanddirectories">Files and Directories</h3><ul>
  1313. <li><strong>Paths can be either strings, Paths or DirEntry objects.</strong></li>
  1314. <li><strong>Functions report OS related errors by raising either OSError or one of its <a href="#exceptions-1">subclasses</a>.</strong></li>
  1315. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os, shutil
  1316. </code></pre></div></div>
  1317. <pre><code class="python language-python hljs">os.chdir(&lt;path&gt;) <span class="hljs-comment"># Changes the current working directory.</span>
  1318. os.mkdir(&lt;path&gt;, mode=<span class="hljs-number">0o777</span>) <span class="hljs-comment"># Creates a directory. Mode is in octal.</span>
  1319. </code></pre>
  1320. <pre><code class="python language-python hljs">shutil.copy(from, to) <span class="hljs-comment"># Copies the file. 'to' can exist or be a dir.</span>
  1321. shutil.copytree(from, to) <span class="hljs-comment"># Copies the directory. 'to' must not exist.</span>
  1322. </code></pre>
  1323. <pre><code class="python language-python hljs">os.rename(from, to) <span class="hljs-comment"># Renames/moves the file or directory.</span>
  1324. os.replace(from, to) <span class="hljs-comment"># Same, but overwrites 'to' if it exists.</span>
  1325. </code></pre>
  1326. <pre><code class="python language-python hljs">os.remove(&lt;path&gt;) <span class="hljs-comment"># Deletes the file.</span>
  1327. os.rmdir(&lt;path&gt;) <span class="hljs-comment"># Deletes the empty directory.</span>
  1328. shutil.rmtree(&lt;path&gt;) <span class="hljs-comment"># Deletes the directory.</span>
  1329. </code></pre>
  1330. <div><h3 id="shellcommands">Shell Commands</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os
  1331. &lt;str&gt; = os.popen(<span class="hljs-string">'&lt;shell_command&gt;'</span>).read()
  1332. </code></pre></div>
  1333. <div><h4 id="sends11tothebasiccalculatorandcapturesitsoutput">Sends '1 + 1' to the basic calculator and captures its output:</h4><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> subprocess <span class="hljs-keyword">import</span> run
  1334. <span class="hljs-meta">&gt;&gt;&gt; </span>run(<span class="hljs-string">'bc'</span>, input=<span class="hljs-string">'1 + 1\n'</span>, capture_output=<span class="hljs-keyword">True</span>, encoding=<span class="hljs-string">'utf-8'</span>)
  1335. CompletedProcess(args=<span class="hljs-string">'bc'</span>, returncode=<span class="hljs-number">0</span>, stdout=<span class="hljs-string">'2\n'</span>, stderr=<span class="hljs-string">''</span>)
  1336. </code></pre></div>
  1337. <div><h4 id="sendstestintothebasiccalculatorrunninginstandardmodeandsavesitsoutputtotestout">Sends test.in to the basic calculator running in standard mode and saves its output to test.out:</h4><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> shlex <span class="hljs-keyword">import</span> split
  1338. <span class="hljs-meta">&gt;&gt;&gt; </span>os.popen(<span class="hljs-string">'echo 1 + 1 &gt; test.in'</span>)
  1339. <span class="hljs-meta">&gt;&gt;&gt; </span>run(split(<span class="hljs-string">'bc -s'</span>), stdin=open(<span class="hljs-string">'test.in'</span>), stdout=open(<span class="hljs-string">'test.out'</span>, <span class="hljs-string">'w'</span>))
  1340. CompletedProcess(args=[<span class="hljs-string">'bc'</span>, <span class="hljs-string">'-s'</span>], returncode=<span class="hljs-number">0</span>)
  1341. <span class="hljs-meta">&gt;&gt;&gt; </span>open(<span class="hljs-string">'test.out'</span>).read()
  1342. <span class="hljs-string">'2\n'</span>
  1343. </code></pre></div>
  1344. <div><h2 id="json"><a href="#json" name="json">#</a>JSON</h2><p><strong>Text file format for storing collections of strings and numbers.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> json
  1345. &lt;str&gt; = json.dumps(&lt;object&gt;, ensure_ascii=<span class="hljs-keyword">True</span>, indent=<span class="hljs-keyword">None</span>)
  1346. &lt;object&gt; = json.loads(&lt;str&gt;)
  1347. </code></pre></div>
  1348. <div><h3 id="readobjectfromjsonfile">Read Object from JSON File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_json_file</span><span class="hljs-params">(filename)</span>:</span>
  1349. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1350. <span class="hljs-keyword">return</span> json.load(file)
  1351. </code></pre></div>
  1352. <div><h3 id="writeobjecttojsonfile">Write Object to JSON File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_json_file</span><span class="hljs-params">(filename, an_object)</span>:</span>
  1353. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'w'</span>, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1354. json.dump(an_object, file, ensure_ascii=<span class="hljs-keyword">False</span>, indent=<span class="hljs-number">2</span>)
  1355. </code></pre></div>
  1356. <div><h2 id="pickle"><a href="#pickle" name="pickle">#</a>Pickle</h2><p><strong>Binary file format for storing objects.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> pickle
  1357. &lt;bytes&gt; = pickle.dumps(&lt;object&gt;)
  1358. &lt;object&gt; = pickle.loads(&lt;bytes&gt;)
  1359. </code></pre></div>
  1360. <div><h3 id="readobjectfromfile">Read Object from File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_pickle_file</span><span class="hljs-params">(filename)</span>:</span>
  1361. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1362. <span class="hljs-keyword">return</span> pickle.load(file)
  1363. </code></pre></div>
  1364. <div><h3 id="writeobjecttofile">Write Object to File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_pickle_file</span><span class="hljs-params">(filename, an_object)</span>:</span>
  1365. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1366. pickle.dump(an_object, file)
  1367. </code></pre></div>
  1368. <div><h2 id="csv"><a href="#csv" name="csv">#</a>CSV</h2><p><strong>Text file format for storing spreadsheets.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> csv
  1369. </code></pre></div>
  1370. <div><h3 id="read">Read</h3><pre><code class="python language-python hljs">&lt;reader&gt; = csv.reader(&lt;file&gt;) <span class="hljs-comment"># Also: `dialect='excel', delimiter=','`.</span>
  1371. &lt;list&gt; = next(&lt;reader&gt;) <span class="hljs-comment"># Returns next row as a list of strings.</span>
  1372. &lt;list&gt; = list(&lt;reader&gt;) <span class="hljs-comment"># Returns list of remaining rows.</span>
  1373. </code></pre></div>
  1374. <ul>
  1375. <li><strong>File must be opened with <code class="python hljs"><span class="hljs-string">'newline=""'</span></code> argument, or newlines embedded inside quoted fields will not be interpreted correctly!</strong></li>
  1376. </ul>
  1377. <div><h3 id="write">Write</h3><pre><code class="python language-python hljs">&lt;writer&gt; = csv.writer(&lt;file&gt;) <span class="hljs-comment"># Also: `dialect='excel', delimiter=','`.</span>
  1378. &lt;writer&gt;.writerow(&lt;collection&gt;) <span class="hljs-comment"># Encodes objects using `str(&lt;el&gt;)`.</span>
  1379. &lt;writer&gt;.writerows(&lt;coll_of_coll&gt;) <span class="hljs-comment"># Appends multiple rows.</span>
  1380. </code></pre></div>
  1381. <ul>
  1382. <li><strong>File must be opened with <code class="python hljs"><span class="hljs-string">'newline=""'</span></code> argument, or '\r' will be added in front of every '\n' on platforms that use '\r\n' line endings!</strong></li>
  1383. </ul>
  1384. <div><h3 id="parameters">Parameters</h3><ul>
  1385. <li><strong><code class="python hljs"><span class="hljs-string">'dialect'</span></code> - Master parameter that sets the default values.</strong></li>
  1386. <li><strong><code class="python hljs"><span class="hljs-string">'delimiter'</span></code> - A one-character string used to separate fields.</strong></li>
  1387. <li><strong><code class="python hljs"><span class="hljs-string">'quotechar'</span></code> - Character for quoting fields that contain special characters.</strong></li>
  1388. <li><strong><code class="python hljs"><span class="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields get doubled or escaped.</strong></li>
  1389. <li><strong><code class="python hljs"><span class="hljs-string">'skipinitialspace'</span></code> - Whether whitespace after delimiter gets stripped.</strong></li>
  1390. <li><strong><code class="python hljs"><span class="hljs-string">'lineterminator'</span></code> - Specifies how writer terminates rows.</strong></li>
  1391. <li><strong><code class="python hljs"><span class="hljs-string">'quoting'</span></code> - Controls the amount of quoting: 0 - as necessary, 1 - all.</strong></li>
  1392. <li><strong><code class="python hljs"><span class="hljs-string">'escapechar'</span></code> - Character for escaping 'quotechar' if 'doublequote' is False.</strong></li>
  1393. </ul><div><h3 id="dialects">Dialects</h3><pre><code class="text language-text">┏━━━━━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┯━━━━━━━━━━━━━━┓
  1394. ┃ │ excel │ excel-tab │ unix ┃
  1395. ┠──────────────────┼──────────────┼──────────────┼──────────────┨
  1396. ┃ delimiter │ ',' │ '\t' │ ',' ┃
  1397. ┃ quotechar │ '"' │ '"' │ '"' ┃
  1398. ┃ doublequote │ True │ True │ True ┃
  1399. ┃ skipinitialspace │ False │ False │ False ┃
  1400. ┃ lineterminator │ '\r\n' │ '\r\n' │ '\n' ┃
  1401. ┃ quoting │ 0 │ 0 │ 1 ┃
  1402. ┃ escapechar │ None │ None │ None ┃
  1403. ┗━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━┛
  1404. </code></pre></div></div>
  1405. <div><h3 id="readrowsfromcsvfile">Read Rows from CSV File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_csv_file</span><span class="hljs-params">(filename)</span>:</span>
  1406. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
  1407. <span class="hljs-keyword">return</span> list(csv.reader(file))
  1408. </code></pre></div>
  1409. <div><h3 id="writerowstocsvfile">Write Rows to CSV File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_csv_file</span><span class="hljs-params">(filename, rows)</span>:</span>
  1410. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'w'</span>, encoding=<span class="hljs-string">'utf-8'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
  1411. writer = csv.writer(file)
  1412. writer.writerows(rows)
  1413. </code></pre></div>
  1414. <div><h2 id="sqlite"><a href="#sqlite" name="sqlite">#</a>SQLite</h2><p><strong>Server-less database engine that stores each database into a separate file.</strong></p><div><h3 id="connect">Connect</h3><p><strong>Opens a connection to the database file. Creates a new file if path doesn't exist.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sqlite3
  1415. &lt;con&gt; = sqlite3.connect(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Also ':memory:'.</span>
  1416. &lt;con&gt;.close()
  1417. </code></pre></div></div>
  1418. <div><h3 id="read-1">Read</h3><p><strong>Returned values can be of type str, int, float, bytes or None.</strong></p><pre><code class="python language-python hljs">&lt;cursor&gt; = &lt;con&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>) <span class="hljs-comment"># Can raise a subclass of sqlite3.Error.</span>
  1419. &lt;tuple&gt; = &lt;cursor&gt;.fetchone() <span class="hljs-comment"># Returns next row. Also next(&lt;cursor&gt;).</span>
  1420. &lt;list&gt; = &lt;cursor&gt;.fetchall() <span class="hljs-comment"># Returns remaining rows. Also list(&lt;cursor&gt;).</span>
  1421. </code></pre></div>
  1422. <div><h3 id="write-1">Write</h3><pre><code class="python language-python hljs">&lt;con&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1423. &lt;con&gt;.commit()
  1424. </code></pre></div>
  1425. <div><h4 id="or">Or:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">with</span> &lt;con&gt;:
  1426. &lt;con&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1427. </code></pre></div>
  1428. <div><h3 id="placeholders">Placeholders</h3><ul>
  1429. <li><strong>Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.</strong></li>
  1430. <li><strong>Bools will be stored and returned as ints and dates as <a href="#encode">ISO formatted strings</a>.</strong></li>
  1431. </ul><pre><code class="python language-python hljs">&lt;con&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;list/tuple&gt;) <span class="hljs-comment"># Replaces '?'s in query with values.</span>
  1432. &lt;con&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;dict/namedtuple&gt;) <span class="hljs-comment"># Replaces ':&lt;key&gt;'s with values.</span>
  1433. &lt;con&gt;.executemany(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;coll_of_above&gt;) <span class="hljs-comment"># Runs execute() many times.</span>
  1434. </code></pre></div>
  1435. <div><h3 id="example">Example</h3><p><strong>In this example values are not actually saved because <code class="python hljs"><span class="hljs-string">'con.commit()'</span></code> is omitted!</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>con = sqlite3.connect(<span class="hljs-string">'test.db'</span>)
  1436. <span class="hljs-meta">&gt;&gt;&gt; </span>con.execute(<span class="hljs-string">'create table person (person_id integer primary key, name, height)'</span>)
  1437. <span class="hljs-meta">&gt;&gt;&gt; </span>con.execute(<span class="hljs-string">'insert into person values (null, ?, ?)'</span>, (<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)).lastrowid
  1438. <span class="hljs-number">1</span>
  1439. <span class="hljs-meta">&gt;&gt;&gt; </span>con.execute(<span class="hljs-string">'select * from person'</span>).fetchall()
  1440. [(<span class="hljs-number">1</span>, <span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)]
  1441. </code></pre></div>
  1442. <div><h3 id="mysql">MySQL</h3><p><strong>Has a very similar interface, with differences listed below.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install mysql-connector</span>
  1443. <span class="hljs-keyword">from</span> mysql <span class="hljs-keyword">import</span> connector
  1444. &lt;con&gt; = connector.connect(host=&lt;str&gt;, …) <span class="hljs-comment"># `user=&lt;str&gt;, password=&lt;str&gt;, database=&lt;str&gt;`.</span>
  1445. &lt;cursor&gt; = &lt;con&gt;.cursor() <span class="hljs-comment"># Only cursor has execute method.</span>
  1446. &lt;cursor&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>) <span class="hljs-comment"># Can raise a subclass of connector.Error.</span>
  1447. &lt;cursor&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;list/tuple&gt;) <span class="hljs-comment"># Replaces '%s's in query with values.</span>
  1448. &lt;cursor&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;dict/namedtuple&gt;) <span class="hljs-comment"># Replaces '%(&lt;key&gt;)s's with values.</span>
  1449. </code></pre></div>
  1450. <div><h2 id="bytes"><a href="#bytes" name="bytes">#</a>Bytes</h2><p><strong>Bytes object is an immutable sequence of single bytes. Mutable version is called bytearray.</strong></p><pre><code class="python language-python hljs">&lt;bytes&gt; = <span class="hljs-string">b'&lt;str&gt;'</span> <span class="hljs-comment"># Only accepts ASCII characters and \x00 - \xff.</span>
  1451. &lt;int&gt; = &lt;bytes&gt;[&lt;index&gt;] <span class="hljs-comment"># Returns int in range from 0 to 255.</span>
  1452. &lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;] <span class="hljs-comment"># Returns bytes even if it has only one element.</span>
  1453. &lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;) <span class="hljs-comment"># Joins elements using bytes object as separator.</span>
  1454. </code></pre></div>
  1455. <div><h3 id="encode-1">Encode</h3><pre><code class="python language-python hljs">&lt;bytes&gt; = bytes(&lt;coll_of_ints&gt;) <span class="hljs-comment"># Ints must be in range from 0 to 255.</span>
  1456. &lt;bytes&gt; = bytes(&lt;str&gt;, <span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Or: &lt;str&gt;.encode('utf-8')</span>
  1457. &lt;bytes&gt; = &lt;int&gt;.to_bytes(n_bytes, …) <span class="hljs-comment"># `byteorder='big/little', signed=False`.</span>
  1458. &lt;bytes&gt; = bytes.fromhex(<span class="hljs-string">'&lt;hex&gt;'</span>) <span class="hljs-comment"># Hex numbers can be separated by spaces.</span>
  1459. </code></pre></div>
  1460. <div><h3 id="decode-1">Decode</h3><pre><code class="python language-python hljs">&lt;list&gt; = list(&lt;bytes&gt;) <span class="hljs-comment"># Returns ints in range from 0 to 255.</span>
  1461. &lt;str&gt; = str(&lt;bytes&gt;, <span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Or: &lt;bytes&gt;.decode('utf-8')</span>
  1462. &lt;int&gt; = int.from_bytes(&lt;bytes&gt;, …) <span class="hljs-comment"># `byteorder='big/little', signed=False`.</span>
  1463. <span class="hljs-string">'&lt;hex&gt;'</span> = &lt;bytes&gt;.hex() <span class="hljs-comment"># Returns a string of hexadecimal numbers.</span>
  1464. </code></pre></div>
  1465. <div><h3 id="readbytesfromfile">Read Bytes from File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_bytes</span><span class="hljs-params">(filename)</span>:</span>
  1466. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1467. <span class="hljs-keyword">return</span> file.read()
  1468. </code></pre></div>
  1469. <div><h3 id="writebytestofile">Write Bytes to File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_bytes</span><span class="hljs-params">(filename, bytes_obj)</span>:</span>
  1470. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1471. file.write(bytes_obj)
  1472. </code></pre></div>
  1473. <div><h2 id="struct"><a href="#struct" name="struct">#</a>Struct</h2><ul>
  1474. <li><strong>Module that performs conversions between a sequence of numbers and a bytes object.</strong></li>
  1475. <li><strong>Machine’s native type sizes and byte order are used by default.</strong></li>
  1476. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> struct <span class="hljs-keyword">import</span> pack, unpack, iter_unpack
  1477. &lt;bytes&gt; = pack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;num_1&gt; [, &lt;num_2&gt;, ...])
  1478. &lt;tuple&gt; = unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1479. &lt;tuples&gt; = iter_unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1480. </code></pre></div>
  1481. <div><h3 id="example-1">Example</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>pack(<span class="hljs-string">'&gt;hhl'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  1482. <span class="hljs-string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>
  1483. <span class="hljs-meta">&gt;&gt;&gt; </span>unpack(<span class="hljs-string">'&gt;hhl'</span>, <span class="hljs-string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>)
  1484. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  1485. </code></pre></div>
  1486. <div><h3 id="format-2">Format</h3><div><h4 id="forstandardtypesizesstartformatstringwith">For standard type sizes start format string with:</h4><ul>
  1487. <li><strong><code class="python hljs"><span class="hljs-string">'='</span></code> - native byte order</strong></li>
  1488. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;'</span></code> - little-endian</strong></li>
  1489. <li><strong><code class="python hljs"><span class="hljs-string">'&gt;'</span></code> - big-endian (also <code class="python hljs"><span class="hljs-string">'!'</span></code>)</strong></li>
  1490. </ul></div></div><div><h4 id="integertypesuseacapitalletterforunsignedtypestandardsizesareinbrackets">Integer types. Use a capital letter for unsigned type. Standard sizes are in brackets:</h4><ul>
  1491. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - pad byte</strong></li>
  1492. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - char (1)</strong></li>
  1493. <li><strong><code class="python hljs"><span class="hljs-string">'h'</span></code> - short (2)</strong></li>
  1494. <li><strong><code class="python hljs"><span class="hljs-string">'i'</span></code> - int (4)</strong></li>
  1495. <li><strong><code class="python hljs"><span class="hljs-string">'l'</span></code> - long (4)</strong></li>
  1496. <li><strong><code class="python hljs"><span class="hljs-string">'q'</span></code> - long long (8)</strong></li>
  1497. </ul></div><div><h4 id="floatingpointtypes">Floating point types:</h4><ul>
  1498. <li><strong><code class="python hljs"><span class="hljs-string">'f'</span></code> - float (4)</strong></li>
  1499. <li><strong><code class="python hljs"><span class="hljs-string">'d'</span></code> - double (8)</strong></li>
  1500. </ul></div>
  1501. <div><h2 id="array"><a href="#array" name="array">#</a>Array</h2><p><strong>List that can only hold numbers of a predefined type. Available types and their sizes in bytes are listed above.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> array <span class="hljs-keyword">import</span> array
  1502. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;collection&gt;) <span class="hljs-comment"># Array from collection of numbers.</span>
  1503. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;bytes&gt;) <span class="hljs-comment"># Array from bytes object.</span>
  1504. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;array&gt;) <span class="hljs-comment"># Treats array as a sequence of numbers.</span>
  1505. &lt;bytes&gt; = bytes(&lt;array&gt;) <span class="hljs-comment"># Or: &lt;array&gt;.tobytes()</span>
  1506. </code></pre></div>
  1507. <div><h2 id="memoryview"><a href="#memoryview" name="memoryview">#</a>Memory View</h2><ul>
  1508. <li><strong>A sequence object that points to the memory of another object.</strong></li>
  1509. <li><strong>Each element can reference a single or multiple consecutive bytes, depending on format.</strong></li>
  1510. <li><strong>Order and number of elements can be changed with slicing.</strong></li>
  1511. </ul><pre><code class="python language-python hljs">&lt;mview&gt; = memoryview(&lt;bytes/bytearray/array&gt;) <span class="hljs-comment"># Immutable if bytes, else mutable.</span>
  1512. &lt;real&gt; = &lt;mview&gt;[&lt;index&gt;] <span class="hljs-comment"># Returns an int or a float.</span>
  1513. &lt;mview&gt; = &lt;mview&gt;[&lt;slice&gt;] <span class="hljs-comment"># Mview with rearranged elements.</span>
  1514. &lt;mview&gt; = &lt;mview&gt;.cast(<span class="hljs-string">'&lt;typecode&gt;'</span>) <span class="hljs-comment"># Casts memoryview to the new format.</span>
  1515. &lt;mview&gt;.release() <span class="hljs-comment"># Releases the object's memory buffer.</span>
  1516. </code></pre></div>
  1517. <div><h3 id="decode-2">Decode</h3><pre><code class="python language-python hljs">&lt;bin_file&gt;.write(&lt;mview&gt;) <span class="hljs-comment"># Writes mview to the binary file.</span>
  1518. &lt;bytes&gt; = bytes(&lt;mview&gt;) <span class="hljs-comment"># Creates a new bytes object.</span>
  1519. &lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_mviews&gt;) <span class="hljs-comment"># Joins mviews using bytes object as sep.</span>
  1520. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;mview&gt;) <span class="hljs-comment"># Treats mview as a sequence of numbers.</span>
  1521. </code></pre></div>
  1522. <pre><code class="python language-python hljs">&lt;list&gt; = list(&lt;mview&gt;) <span class="hljs-comment"># Returns list of ints or floats.</span>
  1523. &lt;str&gt; = str(&lt;mview&gt;, <span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Treats mview as a bytes object.</span>
  1524. &lt;int&gt; = int.from_bytes(&lt;mview&gt;, …) <span class="hljs-comment"># `byteorder='big/little', signed=False`.</span>
  1525. <span class="hljs-string">'&lt;hex&gt;'</span> = &lt;mview&gt;.hex() <span class="hljs-comment"># Treats mview as a bytes object.</span>
  1526. </code></pre>
  1527. <div><h2 id="deque"><a href="#deque" name="deque">#</a>Deque</h2><p><strong>A thread-safe list with efficient appends and pops from either side. Pronounced "deck".</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
  1528. &lt;deque&gt; = deque(&lt;collection&gt;, maxlen=<span class="hljs-keyword">None</span>)
  1529. </code></pre></div>
  1530. <pre><code class="python language-python hljs">&lt;deque&gt;.appendleft(&lt;el&gt;) <span class="hljs-comment"># Opposite element is dropped if full.</span>
  1531. &lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Collection gets reversed.</span>
  1532. &lt;el&gt; = &lt;deque&gt;.popleft() <span class="hljs-comment"># Raises IndexError if empty.</span>
  1533. &lt;deque&gt;.rotate(n=<span class="hljs-number">1</span>) <span class="hljs-comment"># Rotates elements to the right.</span>
  1534. </code></pre>
  1535. <div><h2 id="threading"><a href="#threading" name="threading">#</a>Threading</h2><ul>
  1536. <li><strong>CPython interpreter can only run a single thread at a time.</strong></li>
  1537. <li><strong>That is why using multiple threads won't result in a faster execution, unless at least one of the threads contains an I/O operation.</strong></li>
  1538. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> threading <span class="hljs-keyword">import</span> Thread, RLock, Semaphore, Event, Barrier
  1539. </code></pre></div>
  1540. <div><h3 id="thread">Thread</h3><pre><code class="python language-python hljs">&lt;Thread&gt; = Thread(target=&lt;function&gt;) <span class="hljs-comment"># Use `args=&lt;collection&gt;` to set arguments.</span>
  1541. &lt;Thread&gt;.start() <span class="hljs-comment"># Starts the thread.</span>
  1542. &lt;bool&gt; = &lt;Thread&gt;.is_alive() <span class="hljs-comment"># Checks if thread has finished executing.</span>
  1543. &lt;Thread&gt;.join() <span class="hljs-comment"># Waits for thread to finish.</span>
  1544. </code></pre></div>
  1545. <ul>
  1546. <li><strong>Use <code class="python hljs"><span class="hljs-string">'kwargs=&lt;dict&gt;'</span></code> to pass keyword arguments to the function.</strong></li>
  1547. <li><strong>Use <code class="python hljs"><span class="hljs-string">'daemon=True'</span></code>, or the program will not be able to exit while the thread is alive.</strong></li>
  1548. </ul>
  1549. <div><h3 id="lock">Lock</h3><pre><code class="python language-python hljs">&lt;lock&gt; = RLock()
  1550. &lt;lock&gt;.acquire() <span class="hljs-comment"># Waits for lock to be available.</span>
  1551. &lt;lock&gt;.release() <span class="hljs-comment"># Makes the lock available again.</span>
  1552. </code></pre></div>
  1553. <div><h4 id="or-1">Or:</h4><pre><code class="python language-python hljs">lock = RLock()
  1554. <span class="hljs-keyword">with</span> lock:
  1555. ...
  1556. </code></pre></div>
  1557. <div><h3 id="semaphoreeventbarrier">Semaphore, Event, Barrier</h3><pre><code class="python language-python hljs">&lt;Semaphore&gt; = Semaphore(value=<span class="hljs-number">1</span>) <span class="hljs-comment"># Lock that can be acquired 'value' times.</span>
  1558. &lt;Event&gt; = Event() <span class="hljs-comment"># Method wait() blocks until set() is called.</span>
  1559. &lt;Barrier&gt; = Barrier(n_times) <span class="hljs-comment"># Method wait() blocks until it's called 'n_times'.</span>
  1560. </code></pre></div>
  1561. <div><h3 id="threadpoolexecutor">Thread Pool Executor</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> concurrent.futures <span class="hljs-keyword">import</span> ThreadPoolExecutor
  1562. <span class="hljs-keyword">with</span> ThreadPoolExecutor(max_workers=<span class="hljs-keyword">None</span>) <span class="hljs-keyword">as</span> executor: <span class="hljs-comment"># Does not exit until done.</span>
  1563. &lt;iter&gt; = executor.map(<span class="hljs-keyword">lambda</span> x: x + <span class="hljs-number">1</span>, range(<span class="hljs-number">3</span>)) <span class="hljs-comment"># (1, 2, 3)</span>
  1564. &lt;iter&gt; = executor.map(<span class="hljs-keyword">lambda</span> x, y: x + y, <span class="hljs-string">'abc'</span>, <span class="hljs-string">'123'</span>) <span class="hljs-comment"># ('a1', 'b2', 'c3')</span>
  1565. &lt;Future&gt; = executor.submit(&lt;function&gt; [, &lt;arg_1&gt;, ...]) <span class="hljs-comment"># Also visible outside block.</span>
  1566. </code></pre></div>
  1567. <div><h4 id="future">Future:</h4><pre><code class="python language-python hljs">&lt;bool&gt; = &lt;Future&gt;.done() <span class="hljs-comment"># Checks if thread has finished executing.</span>
  1568. &lt;obj&gt; = &lt;Future&gt;.result() <span class="hljs-comment"># Waits for thread to finish and returns result.</span>
  1569. </code></pre></div>
  1570. <div><h3 id="queue">Queue</h3><p><strong>A thread-safe FIFO queue. For LIFO queue use LifoQueue.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> queue <span class="hljs-keyword">import</span> Queue
  1571. &lt;Queue&gt; = Queue(maxsize=<span class="hljs-number">0</span>)
  1572. </code></pre></div>
  1573. <pre><code class="python language-python hljs">&lt;Queue&gt;.put(&lt;el&gt;) <span class="hljs-comment"># Blocks until queue stops being full.</span>
  1574. &lt;Queue&gt;.put_nowait(&lt;el&gt;) <span class="hljs-comment"># Raises queue.Full exception if full.</span>
  1575. &lt;el&gt; = &lt;Queue&gt;.get() <span class="hljs-comment"># Blocks until queue stops being empty.</span>
  1576. &lt;el&gt; = &lt;Queue&gt;.get_nowait() <span class="hljs-comment"># Raises queue.Empty exception if empty.</span>
  1577. </code></pre>
  1578. <div><h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2><p><strong>Module of functions that provide the functionality of operators.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> add, sub, mul, truediv, floordiv, mod, pow, neg, abs
  1579. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge
  1580. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> and_, or_, not_
  1581. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller
  1582. </code></pre></div>
  1583. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  1584. elementwise_sum = map(op.add, list_a, list_b)
  1585. sorted_by_second = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>))
  1586. sorted_by_both = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>))
  1587. product_of_elems = functools.reduce(op.mul, &lt;collection&gt;)
  1588. LogicOp = enum.Enum(<span class="hljs-string">'LogicOp'</span>, {<span class="hljs-string">'AND'</span>: op.and_, <span class="hljs-string">'OR'</span> : op.or_})
  1589. last_el = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;)
  1590. </code></pre>
  1591. <div><h2 id="introspection"><a href="#introspection" name="introspection">#</a>Introspection</h2><p><strong>Inspecting code at runtime.</strong></p><div><h3 id="variables">Variables</h3><pre><code class="python language-python hljs">&lt;list&gt; = dir() <span class="hljs-comment"># Names of local variables (incl. functions).</span>
  1592. &lt;dict&gt; = vars() <span class="hljs-comment"># Dict of local variables. Also locals().</span>
  1593. &lt;dict&gt; = globals() <span class="hljs-comment"># Dict of global variables.</span>
  1594. </code></pre></div></div>
  1595. <div><h3 id="attributes-1">Attributes</h3><pre><code class="python language-python hljs">&lt;list&gt; = dir(&lt;object&gt;) <span class="hljs-comment"># Names of object's attributes (incl. methods).</span>
  1596. &lt;dict&gt; = vars(&lt;object&gt;) <span class="hljs-comment"># Dict of object's fields. Also &lt;obj&gt;.__dict__.</span>
  1597. &lt;bool&gt; = hasattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>) <span class="hljs-comment"># Checks if getattr() raises an error.</span>
  1598. value = getattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>) <span class="hljs-comment"># Raises AttributeError if attribute is missing.</span>
  1599. setattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>, value) <span class="hljs-comment"># Only works on objects with __dict__ attribute.</span>
  1600. delattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>) <span class="hljs-comment"># Equivalent to `del &lt;object&gt;.&lt;attr_name&gt;`.</span>
  1601. </code></pre></div>
  1602. <div><h3 id="parameters-1">Parameters</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> inspect <span class="hljs-keyword">import</span> signature
  1603. &lt;sig&gt; = signature(&lt;function&gt;)
  1604. no_of_params = len(&lt;sig&gt;.parameters)
  1605. param_names = list(&lt;sig&gt;.parameters.keys())
  1606. param_kinds = [a.kind <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;sig&gt;.parameters.values()]
  1607. </code></pre></div>
  1608. <div><h2 id="metaprograming"><a href="#metaprograming" name="metaprograming">#</a>Metaprograming</h2><p><strong>Code that generates code.</strong></p><div><h3 id="type-1">Type</h3><p><strong>Type is the root class. If only passed an object it returns its type (class). Otherwise it creates a new class.</strong></p><pre><code class="python language-python hljs"><code class="python language-python hljs">&lt;class&gt; = type(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;parents_tuple&gt;, &lt;attributes_dict&gt;)</code></code></pre></div></div>
  1609. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>Z = type(<span class="hljs-string">'Z'</span>, (), {<span class="hljs-string">'a'</span>: <span class="hljs-string">'abcde'</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">12345</span>})
  1610. <span class="hljs-meta">&gt;&gt;&gt; </span>z = Z()
  1611. </code></pre>
  1612. <div><h3 id="metaclass">Meta Class</h3><p><strong>A class that creates classes.</strong></p><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_meta_class</span><span class="hljs-params">(name, parents, attrs)</span>:</span>
  1613. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1614. <span class="hljs-keyword">return</span> type(name, parents, attrs)
  1615. </code></pre></div>
  1616. <div><h4 id="or-2">Or:</h4><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyMetaClass</span><span class="hljs-params">(type)</span>:</span>
  1617. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span><span class="hljs-params">(cls, name, parents, attrs)</span>:</span>
  1618. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1619. <span class="hljs-keyword">return</span> type.__new__(cls, name, parents, attrs)
  1620. </code></pre></div>
  1621. <ul>
  1622. <li><strong>New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.</strong></li>
  1623. <li><strong>It receives the same arguments as init(), except for the first one that specifies the desired type of the returned instance (MyMetaClass in our case).</strong></li>
  1624. <li><strong>Like in our case, new() can also be called directly, usually from a new() method of a child class (</strong><code class="python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__new__</span><span class="hljs-params">(cls)</span>:</span> <span class="hljs-keyword">return</span> super().__new__(cls)</code><strong>).</strong></li>
  1625. <li><strong>The only difference between the examples above is that my_meta_class() returns a class of type type, while MyMetaClass() returns a class of type MyMetaClass.</strong></li>
  1626. </ul>
  1627. <div><h3 id="metaclassattribute">Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has the 'metaclass' attribute defined. If not, it recursively checks if any of his parents has it defined and eventually comes to type().</strong></p><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span><span class="hljs-params">(metaclass=MyMetaClass)</span>:</span>
  1628. b = <span class="hljs-number">12345</span>
  1629. </code></pre></div>
  1630. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>MyClass.a, MyClass.b
  1631. (<span class="hljs-string">'abcde'</span>, <span class="hljs-number">12345</span>)
  1632. </code></pre>
  1633. <div><h3 id="typediagram">Type Diagram</h3><pre><code class="python language-python hljs">type(MyClass) == MyMetaClass <span class="hljs-comment"># MyClass is an instance of MyMetaClass.</span>
  1634. type(MyMetaClass) == type <span class="hljs-comment"># MyMetaClass is an instance of type.</span>
  1635. </code></pre></div>
  1636. <pre><code class="text language-text">┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
  1637. ┃ Classes │ Metaclasses ┃
  1638. ┠─────────────┼─────────────┨
  1639. ┃ MyClass ──→ MyMetaClass ┃
  1640. ┃ │ ↓ ┃
  1641. ┃ object ─────→ type ←╮ ┃
  1642. ┃ │ ↑ ╰──╯ ┃
  1643. ┃ str ──────────╯ ┃
  1644. ┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
  1645. </code></pre>
  1646. <div><h3 id="inheritancediagram">Inheritance Diagram</h3><pre><code class="python language-python hljs">MyClass.__base__ == object <span class="hljs-comment"># MyClass is a subclass of object.</span>
  1647. MyMetaClass.__base__ == type <span class="hljs-comment"># MyMetaClass is a subclass of type.</span>
  1648. </code></pre></div>
  1649. <pre><code class="text language-text">┏━━━━━━━━━━━━━┯━━━━━━━━━━━━━┓
  1650. ┃ Classes │ Metaclasses ┃
  1651. ┠─────────────┼─────────────┨
  1652. ┃ MyClass │ MyMetaClass ┃
  1653. ┃ ↓ │ ↓ ┃
  1654. ┃ object ←───── type ┃
  1655. ┃ ↑ │ ┃
  1656. ┃ str │ ┃
  1657. ┗━━━━━━━━━━━━━┷━━━━━━━━━━━━━┛
  1658. </code></pre>
  1659. <div><h2 id="eval"><a href="#eval" name="eval">#</a>Eval</h2><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> ast <span class="hljs-keyword">import</span> literal_eval
  1660. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'1 + 2'</span>)
  1661. <span class="hljs-number">3</span>
  1662. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'[1, 2, 3]'</span>)
  1663. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  1664. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'abs(1)'</span>)
  1665. ValueError: malformed node or string
  1666. </code></pre></div>
  1667. <div><h2 id="coroutines"><a href="#coroutines" name="coroutines">#</a>Coroutines</h2><ul>
  1668. <li><strong>Coroutines have a lot in common with threads, but unlike threads, they only give up control when they call another coroutine and they don’t use as much memory.</strong></li>
  1669. <li><strong>Coroutine definition starts with <code class="python hljs"><span class="hljs-string">'async'</span></code> and its call with <code class="python hljs"><span class="hljs-string">'await'</span></code>.</strong></li>
  1670. <li><strong><code class="python hljs"><span class="hljs-string">'asyncio.run(&lt;coroutine&gt;)'</span></code> is the main entry point for asynchronous programs.</strong></li>
  1671. <li><strong>Functions wait(), gather() and as_completed() can be used when multiple coroutines need to be started at the same time.</strong></li>
  1672. <li><strong>Asyncio module also provides its own <a href="#queue">Queue</a>, <a href="#semaphoreeventbarrier">Event</a>, <a href="#lock">Lock</a> and <a href="#semaphore-event-barrier">Semaphore</a> classes.</strong></li>
  1673. </ul><div><h4 id="runsaterminalgamewhereyoucontrolanasteriskthatmustavoidnumbers">Runs a terminal game where you control an asterisk that must avoid numbers:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> asyncio, collections, curses, enum, random
  1674. P = collections.namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'x y'</span>) <span class="hljs-comment"># Position</span>
  1675. D = enum.Enum(<span class="hljs-string">'D'</span>, <span class="hljs-string">'n e s w'</span>) <span class="hljs-comment"># Direction</span>
  1676. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">(screen)</span>:</span>
  1677. curses.curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>
  1678. screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>
  1679. asyncio.run(main_coroutine(screen)) <span class="hljs-comment"># Starts running asyncio code.</span>
  1680. <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main_coroutine</span><span class="hljs-params">(screen)</span>:</span>
  1681. state = {<span class="hljs-string">'*'</span>: P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), **{id_: P(<span class="hljs-number">30</span>, <span class="hljs-number">10</span>) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)}}
  1682. moves = asyncio.Queue()
  1683. coros = (*(random_controller(id_, moves) <span class="hljs-keyword">for</span> id_ <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>)),
  1684. human_controller(screen, moves),
  1685. model(moves, state, *screen.getmaxyx()),
  1686. view(state, screen))
  1687. <span class="hljs-keyword">await</span> asyncio.wait(coros, return_when=asyncio.FIRST_COMPLETED)
  1688. <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">random_controller</span><span class="hljs-params">(id_, moves)</span>:</span>
  1689. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1690. moves.put_nowait((id_, random.choice(list(D))))
  1691. <span class="hljs-keyword">await</span> asyncio.sleep(random.random() / <span class="hljs-number">2</span>)
  1692. <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">human_controller</span><span class="hljs-params">(screen, moves)</span>:</span>
  1693. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1694. ch = screen.getch()
  1695. key_mappings = {<span class="hljs-number">259</span>: D.n, <span class="hljs-number">261</span>: D.e, <span class="hljs-number">258</span>: D.s, <span class="hljs-number">260</span>: D.w}
  1696. <span class="hljs-keyword">if</span> ch <span class="hljs-keyword">in</span> key_mappings:
  1697. moves.put_nowait((<span class="hljs-string">'*'</span>, key_mappings[ch]))
  1698. <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.01</span>)
  1699. <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">model</span><span class="hljs-params">(moves, state, height, width)</span>:</span>
  1700. <span class="hljs-keyword">while</span> state[<span class="hljs-string">'*'</span>] <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> {p <span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items() <span class="hljs-keyword">if</span> id_ != <span class="hljs-string">'*'</span>}:
  1701. id_, d = <span class="hljs-keyword">await</span> moves.get()
  1702. p = state[id_]
  1703. deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}
  1704. new_p = P(*[sum(a) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> zip(p, deltas[d])])
  1705. <span class="hljs-keyword">if</span> <span class="hljs-number">0</span> &lt;= new_p.x &lt; width<span class="hljs-number">-1</span> <span class="hljs-keyword">and</span> <span class="hljs-number">0</span> &lt;= new_p.y &lt; height:
  1706. state[id_] = new_p
  1707. <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">view</span><span class="hljs-params">(state, screen)</span>:</span>
  1708. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1709. screen.clear()
  1710. <span class="hljs-keyword">for</span> id_, p <span class="hljs-keyword">in</span> state.items():
  1711. screen.addstr(p.y, p.x, str(id_))
  1712. <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">0.01</span>)
  1713. curses.wrapper(main)
  1714. </code></pre></div></div>
  1715. <p><br></p>
  1716. <div><h1 id="libraries">Libraries</h1><div><h2 id="progressbar"><a href="#progressbar" name="progressbar">#</a>Progress Bar</h2><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install tqdm</span>
  1717. <span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm
  1718. <span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep
  1719. <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> tqdm([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]):
  1720. sleep(<span class="hljs-number">0.2</span>)
  1721. </code></pre></div></div>
  1722. <div><h2 id="plot"><a href="#plot" name="plot">#</a>Plot</h2><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install matplotlib</span>
  1723. <span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot
  1724. pyplot.plot(&lt;y_data&gt; [, label=&lt;str&gt;])
  1725. pyplot.plot(&lt;x_data&gt;, &lt;y_data&gt;)
  1726. pyplot.legend() <span class="hljs-comment"># Adds a legend.</span>
  1727. pyplot.savefig(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Saves the figure.</span>
  1728. pyplot.show() <span class="hljs-comment"># Displays the figure.</span>
  1729. pyplot.clf() <span class="hljs-comment"># Clears the figure.</span>
  1730. </code></pre></div>
  1731. <div><h2 id="table"><a href="#table" name="table">#</a>Table</h2><div><h4 id="printsacsvfileasanasciitable">Prints a CSV file as an ASCII table:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install tabulate</span>
  1732. <span class="hljs-keyword">import</span> csv, tabulate
  1733. <span class="hljs-keyword">with</span> open(<span class="hljs-string">'test.csv'</span>, encoding=<span class="hljs-string">'utf-8'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
  1734. rows = csv.reader(file)
  1735. header = [a.title() <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> next(rows)]
  1736. table = tabulate.tabulate(rows, header)
  1737. print(table)
  1738. </code></pre></div></div>
  1739. <div><h2 id="curses"><a href="#curses" name="curses">#</a>Curses</h2><div><h4 id="clearstheterminalprintsamessageandwaitsfortheesckeypress">Clears the terminal, prints a message and waits for the ESC key press:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> wrapper, curs_set, ascii
  1740. <span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT
  1741. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1742. wrapper(draw)
  1743. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen)</span>:</span>
  1744. curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>
  1745. screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>
  1746. screen.clear()
  1747. screen.addstr(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Press ESC to quit.'</span>) <span class="hljs-comment"># Coordinates are y, x.</span>
  1748. <span class="hljs-keyword">while</span> screen.getch() != ascii.ESC:
  1749. <span class="hljs-keyword">pass</span>
  1750. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_border</span><span class="hljs-params">(screen)</span>:</span>
  1751. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1752. P = namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'x y'</span>)
  1753. height, width = screen.getmaxyx()
  1754. <span class="hljs-keyword">return</span> P(width<span class="hljs-number">-1</span>, height<span class="hljs-number">-1</span>)
  1755. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1756. main()
  1757. </code></pre></div></div>
  1758. <div><h2 id="logging"><a href="#logging" name="logging">#</a>Logging</h2><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install loguru</span>
  1759. <span class="hljs-keyword">from</span> loguru <span class="hljs-keyword">import</span> logger
  1760. </code></pre></div>
  1761. <pre><code class="python language-python hljs">logger.add(<span class="hljs-string">'debug_{time}.log'</span>, colorize=<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Connects a log file.</span>
  1762. logger.add(<span class="hljs-string">'error_{time}.log'</span>, level=<span class="hljs-string">'ERROR'</span>) <span class="hljs-comment"># Another file for errors or higher.</span>
  1763. logger.&lt;level&gt;(<span class="hljs-string">'A logging message.'</span>)
  1764. </code></pre>
  1765. <ul>
  1766. <li><strong>Levels: <code class="python hljs"><span class="hljs-string">'debug'</span></code>, <code class="python hljs"><span class="hljs-string">'info'</span></code>, <code class="python hljs"><span class="hljs-string">'success'</span></code>, <code class="python hljs"><span class="hljs-string">'warning'</span></code>, <code class="python hljs"><span class="hljs-string">'error'</span></code>, <code class="python hljs"><span class="hljs-string">'critical'</span></code>.</strong></li>
  1767. </ul>
  1768. <div><h3 id="exceptions-2">Exceptions</h3><p><strong>Exception description, stack trace and values of variables are appended automatically.</strong></p><pre><code class="python language-python hljs"><span class="hljs-keyword">try</span>:
  1769. ...
  1770. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1771. logger.exception(<span class="hljs-string">'An error happened.'</span>)
  1772. </code></pre></div>
  1773. <div><h3 id="rotation">Rotation</h3><p><strong>Argument that sets a condition when a new log file is created.</strong></p><pre><code class="python language-python hljs">rotation=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;datetime.time&gt;|&lt;str&gt;
  1774. </code></pre></div>
  1775. <ul>
  1776. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max file size in bytes.</strong></li>
  1777. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1778. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;time&gt;'</span></code> - Time of day.</strong></li>
  1779. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;str&gt;'</span></code> - Any of above as a string: <code class="python hljs"><span class="hljs-string">'100 MB'</span></code>, <code class="python hljs"><span class="hljs-string">'1 month'</span></code>, <code class="python hljs"><span class="hljs-string">'monday at 12:00'</span></code>, …</strong></li>
  1780. </ul>
  1781. <div><h3 id="retention">Retention</h3><p><strong>Sets a condition which old log files get deleted.</strong></p><pre><code class="python language-python hljs">retention=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;str&gt;
  1782. </code></pre></div>
  1783. <ul>
  1784. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max number of files.</strong></li>
  1785. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1786. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;str&gt;'</span></code> - Max age as a string: <code class="python hljs"><span class="hljs-string">'1 week, 3 days'</span></code>, <code class="python hljs"><span class="hljs-string">'2 months'</span></code>, …</strong></li>
  1787. </ul>
  1788. <div><h2 id="scraping"><a href="#scraping" name="scraping">#</a>Scraping</h2><div><h4 id="scrapespythonsurlversionnumberandlogofromwikipediapage">Scrapes Python's URL, version number and logo from Wikipedia page:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests beautifulsoup4</span>
  1789. <span class="hljs-keyword">import</span> requests, sys
  1790. <span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
  1791. URL = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span>
  1792. <span class="hljs-keyword">try</span>:
  1793. html = requests.get(URL).text
  1794. doc = BeautifulSoup(html, <span class="hljs-string">'html.parser'</span>)
  1795. table = doc.find(<span class="hljs-string">'table'</span>, class_=<span class="hljs-string">'infobox vevent'</span>)
  1796. rows = table.find_all(<span class="hljs-string">'tr'</span>)
  1797. link = rows[<span class="hljs-number">11</span>].find(<span class="hljs-string">'a'</span>)[<span class="hljs-string">'href'</span>]
  1798. ver = rows[<span class="hljs-number">6</span>].find(<span class="hljs-string">'div'</span>).text.split()[<span class="hljs-number">0</span>]
  1799. url_i = rows[<span class="hljs-number">0</span>].find(<span class="hljs-string">'img'</span>)[<span class="hljs-string">'src'</span>]
  1800. image = requests.get(<span class="hljs-string">f'https:<span class="hljs-subst">{url_i}</span>'</span>).content
  1801. <span class="hljs-keyword">with</span> open(<span class="hljs-string">'test.png'</span>, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1802. file.write(image)
  1803. print(link, ver)
  1804. <span class="hljs-keyword">except</span> requests.exceptions.ConnectionError:
  1805. print(<span class="hljs-string">"You've got problems with connection."</span>, file=sys.stderr)
  1806. </code></pre></div></div>
  1807. <div><h2 id="web"><a href="#web" name="web">#</a>Web</h2><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install bottle</span>
  1808. <span class="hljs-keyword">from</span> bottle <span class="hljs-keyword">import</span> run, route, static_file, template, post, request, response
  1809. <span class="hljs-keyword">import</span> json
  1810. </code></pre></div>
  1811. <div><h3 id="run">Run</h3><pre><code class="python language-python hljs">run(host=<span class="hljs-string">'localhost'</span>, port=<span class="hljs-number">8080</span>) <span class="hljs-comment"># Runs locally.</span>
  1812. run(host=<span class="hljs-string">'0.0.0.0'</span>, port=<span class="hljs-number">80</span>) <span class="hljs-comment"># Runs globally.</span>
  1813. </code></pre></div>
  1814. <div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/img/&lt;image&gt;')</span>
  1815. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_image</span><span class="hljs-params">(image)</span>:</span>
  1816. <span class="hljs-keyword">return</span> static_file(image, <span class="hljs-string">'img_dir/'</span>, mimetype=<span class="hljs-string">'image/png'</span>)
  1817. </code></pre></div>
  1818. <div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/&lt;sport&gt;')</span>
  1819. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_page</span><span class="hljs-params">(sport)</span>:</span>
  1820. <span class="hljs-keyword">return</span> template(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
  1821. </code></pre></div>
  1822. <div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@post('/odds/&lt;sport&gt;')</span>
  1823. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">odds_handler</span><span class="hljs-params">(sport)</span>:</span>
  1824. team = request.forms.get(<span class="hljs-string">'team'</span>)
  1825. home_odds, away_odds = <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>
  1826. response.headers[<span class="hljs-string">'Content-Type'</span>] = <span class="hljs-string">'application/json'</span>
  1827. response.headers[<span class="hljs-string">'Cache-Control'</span>] = <span class="hljs-string">'no-cache'</span>
  1828. <span class="hljs-keyword">return</span> json.dumps([team, home_odds, away_odds])
  1829. </code></pre></div>
  1830. <div><h4 id="test">Test:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests</span>
  1831. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests
  1832. <span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:8080/odds/football'</span>
  1833. <span class="hljs-meta">&gt;&gt;&gt; </span>data = {<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>}
  1834. <span class="hljs-meta">&gt;&gt;&gt; </span>response = requests.post(url, data=data)
  1835. <span class="hljs-meta">&gt;&gt;&gt; </span>response.json()
  1836. [<span class="hljs-string">'arsenal f.c.'</span>, <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>]
  1837. </code></pre></div>
  1838. <div><h2 id="profiling"><a href="#profiling" name="profiling">#</a>Profiling</h2><div><h3 id="stopwatch">Stopwatch</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> time
  1839. start_time = time() <span class="hljs-comment"># Seconds since the Epoch.</span>
  1840. ...
  1841. duration = time() - start_time
  1842. </code></pre></div></div>
  1843. <div><h4 id="highperformance">High performance:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> perf_counter
  1844. start_time = perf_counter() <span class="hljs-comment"># Seconds since restart.</span>
  1845. ...
  1846. duration = perf_counter() - start_time
  1847. </code></pre></div>
  1848. <div><h3 id="timingasnippet">Timing a Snippet</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> timeit <span class="hljs-keyword">import</span> timeit
  1849. <span class="hljs-meta">&gt;&gt;&gt; </span>timeit(<span class="hljs-string">'"-".join(str(a) for a in range(100))'</span>,
  1850. <span class="hljs-meta">... </span> number=<span class="hljs-number">10000</span>, globals=globals(), setup=<span class="hljs-string">'pass'</span>)
  1851. <span class="hljs-number">0.34986</span>
  1852. </code></pre></div>
  1853. <div><h3 id="profilingbyline">Profiling by Line</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install line_profiler memory_profiler</span>
  1854. <span class="hljs-meta">@profile</span>
  1855. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1856. a = [*range(<span class="hljs-number">10000</span>)]
  1857. b = {*range(<span class="hljs-number">10000</span>)}
  1858. main()
  1859. </code></pre></div>
  1860. <pre><code class="text language-text">$ kernprof -lv test.py
  1861. Line # Hits Time Per Hit % Time Line Contents
  1862. =======================================================
  1863. 1 @profile
  1864. 2 def main():
  1865. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1866. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1867. </code></pre>
  1868. <pre><code class="text language-text">$ python3 -m memory_profiler test.py
  1869. Line # Mem usage Increment Line Contents
  1870. =======================================================
  1871. 1 35.387 MiB 35.387 MiB @profile
  1872. 2 def main():
  1873. 3 35.734 MiB 0.348 MiB a = [*range(10000)]
  1874. 4 36.160 MiB 0.426 MiB b = {*range(10000)}
  1875. </code></pre>
  1876. <div><h3 id="callgraph">Call Graph</h3><div><h4 id="generatesapngimageofacallgraphwithhighlightedbottlenecks">Generates a PNG image of a call graph with highlighted bottlenecks:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pycallgraph</span>
  1877. <span class="hljs-keyword">from</span> pycallgraph <span class="hljs-keyword">import</span> output, PyCallGraph
  1878. <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
  1879. time_str = datetime.now().strftime(<span class="hljs-string">'%Y%m%d%H%M%S'</span>)
  1880. filename = <span class="hljs-string">f'profile-<span class="hljs-subst">{time_str}</span>.png'</span>
  1881. drawer = output.GraphvizOutput(output_file=filename)
  1882. <span class="hljs-keyword">with</span> PyCallGraph(drawer):
  1883. &lt;code_to_be_profiled&gt;
  1884. </code></pre></div></div>
  1885. <div><h2 id="numpy"><a href="#numpy" name="numpy">#</a>NumPy</h2><p><strong>Array manipulation mini-language. It can run up to one hundred times faster than the equivalent Python code.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install numpy</span>
  1886. <span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
  1887. </code></pre></div>
  1888. <pre><code class="python language-python hljs">&lt;array&gt; = np.array(&lt;list&gt;)
  1889. &lt;array&gt; = np.arange(from_inclusive, to_exclusive, ±step_size)
  1890. &lt;array&gt; = np.ones(&lt;shape&gt;)
  1891. &lt;array&gt; = np.random.randint(from_inclusive, to_exclusive, &lt;shape&gt;)
  1892. </code></pre>
  1893. <pre><code class="python language-python hljs">&lt;array&gt;.shape = &lt;shape&gt;
  1894. &lt;view&gt; = &lt;array&gt;.reshape(&lt;shape&gt;)
  1895. &lt;view&gt; = np.broadcast_to(&lt;array&gt;, &lt;shape&gt;)
  1896. </code></pre>
  1897. <pre><code class="python language-python hljs">&lt;array&gt; = &lt;array&gt;.sum(axis)
  1898. indexes = &lt;array&gt;.argmin(axis)
  1899. </code></pre>
  1900. <ul>
  1901. <li><strong>Shape is a tuple of dimension sizes.</strong></li>
  1902. <li><strong>Axis is the index of a dimension that gets collapsed. The leftmost dimension has index 0.</strong></li>
  1903. </ul>
  1904. <div><h3 id="indexing">Indexing</h3><pre><code class="bash language-bash hljs">&lt;el&gt; = &lt;2d_array&gt;[0, 0] <span class="hljs-comment"># First element.</span>
  1905. &lt;1d_view&gt; = &lt;2d_array&gt;[0] <span class="hljs-comment"># First row.</span>
  1906. &lt;1d_view&gt; = &lt;2d_array&gt;[:, 0] <span class="hljs-comment"># First column. Also [..., 0].</span>
  1907. &lt;3d_view&gt; = &lt;2d_array&gt;[None, :, :] <span class="hljs-comment"># Expanded by dimension of size 1.</span>
  1908. </code></pre></div>
  1909. <pre><code class="bash language-bash hljs">&lt;1d_array&gt; = &lt;2d_array&gt;[&lt;1d_row_indexes&gt;, &lt;1d_column_indexes&gt;]
  1910. &lt;2d_array&gt; = &lt;2d_array&gt;[&lt;2d_row_indexes&gt;, &lt;2d_column_indexes&gt;]
  1911. </code></pre>
  1912. <pre><code class="bash language-bash hljs">&lt;2d_bools&gt; = &lt;2d_array&gt; &gt; 0
  1913. &lt;1d_array&gt; = &lt;2d_array&gt;[&lt;2d_bools&gt;]
  1914. </code></pre>
  1915. <ul>
  1916. <li><strong>If row and column indexes differ in shape, they are combined with broadcasting.</strong></li>
  1917. </ul>
  1918. <div><h3 id="broadcasting">Broadcasting</h3><p><strong>Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.</strong></p><pre><code class="python language-python hljs">left = [[<span class="hljs-number">0.1</span>], [<span class="hljs-number">0.6</span>], [<span class="hljs-number">0.8</span>]] <span class="hljs-comment"># Shape: (3, 1)</span>
  1919. right = [ <span class="hljs-number">0.1</span> , <span class="hljs-number">0.6</span> , <span class="hljs-number">0.8</span> ] <span class="hljs-comment"># Shape: (3)</span>
  1920. </code></pre></div>
  1921. <div><h4 id="1ifarrayshapesdifferinlengthleftpadtheshortershapewithones">1. If array shapes differ in length, left-pad the shorter shape with ones:</h4><pre><code class="python language-python hljs">left = [[<span class="hljs-number">0.1</span>], [<span class="hljs-number">0.6</span>], [<span class="hljs-number">0.8</span>]] <span class="hljs-comment"># Shape: (3, 1)</span>
  1922. right = [[<span class="hljs-number">0.1</span> , <span class="hljs-number">0.6</span> , <span class="hljs-number">0.8</span>]] <span class="hljs-comment"># Shape: (1, 3) &lt;- !</span>
  1923. </code></pre></div>
  1924. <div><h4 id="2ifanydimensionsdifferinsizeexpandtheonesthathavesize1byduplicatingtheirelements">2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:</h4><pre><code class="python language-python hljs">left = [[<span class="hljs-number">0.1</span>, <span class="hljs-number">0.1</span>, <span class="hljs-number">0.1</span>], [<span class="hljs-number">0.6</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.6</span>], [<span class="hljs-number">0.8</span>, <span class="hljs-number">0.8</span>, <span class="hljs-number">0.8</span>]] <span class="hljs-comment"># Shape: (3, 3) &lt;- !</span>
  1925. right = [[<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>], [<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>], [<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>]] <span class="hljs-comment"># Shape: (3, 3) &lt;- !</span>
  1926. </code></pre></div>
  1927. <div><h4 id="3ifneithernonmatchingdimensionhassize1raiseanerror">3. If neither non-matching dimension has size 1, raise an error.</h4><div><h3 id="example-2">Example</h3><div><h4 id="foreachpointreturnsindexofitsnearestpoint010608121">For each point returns index of its nearest point (<code class="python hljs">[<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>] =&gt; [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]</code>):</h4><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>points = np.array([<span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>])
  1928. [ <span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>]
  1929. <span class="hljs-meta">&gt;&gt;&gt; </span>wrapped_points = points.reshape(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>)
  1930. [[ <span class="hljs-number">0.1</span>],
  1931. [ <span class="hljs-number">0.6</span>],
  1932. [ <span class="hljs-number">0.8</span>]]
  1933. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = wrapped_points - points
  1934. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">-0.5</span>, <span class="hljs-number">-0.7</span>],
  1935. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">-0.2</span>],
  1936. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1937. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = np.abs(distances)
  1938. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1939. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">0.2</span>],
  1940. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1941. <span class="hljs-meta">&gt;&gt;&gt; </span>i = np.arange(<span class="hljs-number">3</span>)
  1942. [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
  1943. <span class="hljs-meta">&gt;&gt;&gt; </span>distances[i, i] = np.inf
  1944. [[ inf, <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1945. [ <span class="hljs-number">0.5</span>, inf, <span class="hljs-number">0.2</span>],
  1946. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, inf]]
  1947. <span class="hljs-meta">&gt;&gt;&gt; </span>distances.argmin(<span class="hljs-number">1</span>)
  1948. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]
  1949. </code></pre></div></div></div>
  1950. <div><h2 id="image"><a href="#image" name="image">#</a>Image</h2><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pillow</span>
  1951. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image
  1952. </code></pre></div>
  1953. <pre><code class="python language-python hljs">&lt;Image&gt; = Image.new(<span class="hljs-string">'&lt;mode&gt;'</span>, (width, height))
  1954. &lt;Image&gt; = Image.open(<span class="hljs-string">'&lt;path&gt;'</span>)
  1955. &lt;Image&gt; = &lt;Image&gt;.convert(<span class="hljs-string">'&lt;mode&gt;'</span>)
  1956. &lt;Image&gt;.save(<span class="hljs-string">'&lt;path&gt;'</span>)
  1957. &lt;Image&gt;.show()
  1958. </code></pre>
  1959. <pre><code class="python language-python hljs">&lt;tuple/int&gt; = &lt;Image&gt;.getpixel((x, y)) <span class="hljs-comment"># Returns a pixel.</span>
  1960. &lt;Image&gt;.putpixel((x, y), &lt;tuple/int&gt;) <span class="hljs-comment"># Writes a pixel to the image.</span>
  1961. &lt;ImagingCore&gt; = &lt;Image&gt;.getdata() <span class="hljs-comment"># Returns a sequence of pixels.</span>
  1962. &lt;Image&gt;.putdata(&lt;list/ImagingCore&gt;) <span class="hljs-comment"># Writes a sequence of pixels.</span>
  1963. &lt;Image&gt;.paste(&lt;Image&gt;, (x, y)) <span class="hljs-comment"># Writes an image to the image.</span>
  1964. </code></pre>
  1965. <pre><code class="bash language-bash hljs">&lt;2d_array&gt; = np.array(&lt;Image&gt;) <span class="hljs-comment"># Creates NumPy array from greyscale image.</span>
  1966. &lt;3d_array&gt; = np.array(&lt;Image&gt;) <span class="hljs-comment"># Creates NumPy array from color image.</span>
  1967. &lt;Image&gt; = Image.fromarray(&lt;array&gt;) <span class="hljs-comment"># Creates image from NumPy array of floats.</span>
  1968. </code></pre>
  1969. <div><h3 id="modes-1">Modes</h3><ul>
  1970. <li><strong><code class="python hljs"><span class="hljs-string">'1'</span></code> - 1-bit pixels, black and white, stored with one pixel per byte.</strong></li>
  1971. <li><strong><code class="python hljs"><span class="hljs-string">'L'</span></code> - 8-bit pixels, greyscale.</strong></li>
  1972. <li><strong><code class="python hljs"><span class="hljs-string">'RGB'</span></code> - 3x8-bit pixels, true color.</strong></li>
  1973. <li><strong><code class="python hljs"><span class="hljs-string">'RGBA'</span></code> - 4x8-bit pixels, true color with transparency mask.</strong></li>
  1974. <li><strong><code class="python hljs"><span class="hljs-string">'HSV'</span></code> - 3x8-bit pixels, Hue, Saturation, Value color space.</strong></li>
  1975. </ul><div><h3 id="examples">Examples</h3><div><h4 id="createsapngimageofarainbowgradient">Creates a PNG image of a rainbow gradient:</h4><pre><code class="python language-python hljs">WIDTH, HEIGHT = <span class="hljs-number">100</span>, <span class="hljs-number">100</span>
  1976. size = WIDTH * HEIGHT
  1977. hues = [<span class="hljs-number">255</span> * i/size <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(size)]
  1978. img = Image.new(<span class="hljs-string">'HSV'</span>, (WIDTH, HEIGHT))
  1979. img.putdata([(int(h), <span class="hljs-number">255</span>, <span class="hljs-number">255</span>) <span class="hljs-keyword">for</span> h <span class="hljs-keyword">in</span> hues])
  1980. img.convert(<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1981. </code></pre></div></div></div>
  1982. <div><h4 id="addsnoisetoapngimage">Adds noise to a PNG image:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint
  1983. add_noise = <span class="hljs-keyword">lambda</span> value: max(<span class="hljs-number">0</span>, min(<span class="hljs-number">255</span>, value + randint(<span class="hljs-number">-20</span>, <span class="hljs-number">20</span>)))
  1984. img = Image.open(<span class="hljs-string">'test.png'</span>).convert(<span class="hljs-string">'HSV'</span>)
  1985. img.putdata([(add_noise(h), s, v) <span class="hljs-keyword">for</span> h, s, v <span class="hljs-keyword">in</span> img.getdata()])
  1986. img.convert(<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1987. </code></pre></div>
  1988. <div><h3 id="drawing">Drawing</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> ImageDraw
  1989. </code></pre></div>
  1990. <pre><code class="python language-python hljs">&lt;ImageDraw&gt; = ImageDraw.Draw(&lt;Image&gt;)
  1991. &lt;ImageDraw&gt;.point((x, y), fill=<span class="hljs-keyword">None</span>)
  1992. &lt;ImageDraw&gt;.line((x1, y1, x2, y2 [, ...]), fill=<span class="hljs-keyword">None</span>, width=<span class="hljs-number">0</span>, joint=<span class="hljs-keyword">None</span>)
  1993. &lt;ImageDraw&gt;.arc((x1, y1, x2, y2), from_deg, to_deg, fill=<span class="hljs-keyword">None</span>, width=<span class="hljs-number">0</span>)
  1994. &lt;ImageDraw&gt;.rectangle((x1, y1, x2, y2), fill=<span class="hljs-keyword">None</span>, outline=<span class="hljs-keyword">None</span>, width=<span class="hljs-number">0</span>)
  1995. &lt;ImageDraw&gt;.polygon((x1, y1, x2, y2 [, ...]), fill=<span class="hljs-keyword">None</span>, outline=<span class="hljs-keyword">None</span>)
  1996. &lt;ImageDraw&gt;.ellipse((x1, y1, x2, y2), fill=<span class="hljs-keyword">None</span>, outline=<span class="hljs-keyword">None</span>, width=<span class="hljs-number">0</span>)
  1997. </code></pre>
  1998. <ul>
  1999. <li><strong>Use <code class="python hljs"><span class="hljs-string">'fill=&lt;color&gt;'</span></code> to set the primary color.</strong></li>
  2000. <li><strong>Use <code class="python hljs"><span class="hljs-string">'outline=&lt;color&gt;'</span></code> to set the secondary color.</strong></li>
  2001. <li><strong>Color can be specified as a tuple, int, <code class="python hljs"><span class="hljs-string">'#rrggbb'</span></code> string or a color name.</strong></li>
  2002. </ul>
  2003. <div><h2 id="animation"><a href="#animation" name="animation">#</a>Animation</h2><div><h4 id="createsagifofabouncingball">Creates a GIF of a bouncing ball:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pillow imageio</span>
  2004. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageDraw
  2005. <span class="hljs-keyword">import</span> imageio
  2006. WIDTH, R = <span class="hljs-number">126</span>, <span class="hljs-number">10</span>
  2007. frames = []
  2008. <span class="hljs-keyword">for</span> velocity <span class="hljs-keyword">in</span> range(<span class="hljs-number">15</span>):
  2009. y = sum(range(velocity+<span class="hljs-number">1</span>))
  2010. frame = Image.new(<span class="hljs-string">'L'</span>, (WIDTH, WIDTH))
  2011. draw = ImageDraw.Draw(frame)
  2012. draw.ellipse((WIDTH/<span class="hljs-number">2</span>-R, y, WIDTH/<span class="hljs-number">2</span>+R, y+R*<span class="hljs-number">2</span>), fill=<span class="hljs-string">'white'</span>)
  2013. frames.append(frame)
  2014. frames += reversed(frames[<span class="hljs-number">1</span>:<span class="hljs-number">-1</span>])
  2015. imageio.mimsave(<span class="hljs-string">'test.gif'</span>, frames, duration=<span class="hljs-number">0.03</span>)
  2016. </code></pre></div></div>
  2017. <div><h2 id="audio"><a href="#audio" name="audio">#</a>Audio</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> wave
  2018. </code></pre></div>
  2019. <pre><code class="python language-python hljs">&lt;Wave_read&gt; = wave.open(<span class="hljs-string">'&lt;path&gt;'</span>, <span class="hljs-string">'rb'</span>) <span class="hljs-comment"># Opens the WAV file.</span>
  2020. framerate = &lt;Wave_read&gt;.getframerate() <span class="hljs-comment"># Number of frames per second.</span>
  2021. nchannels = &lt;Wave_read&gt;.getnchannels() <span class="hljs-comment"># Number of samples per frame.</span>
  2022. sampwidth = &lt;Wave_read&gt;.getsampwidth() <span class="hljs-comment"># Sample size in bytes.</span>
  2023. nframes = &lt;Wave_read&gt;.getnframes() <span class="hljs-comment"># Number of frames.</span>
  2024. &lt;params&gt; = &lt;Wave_read&gt;.getparams() <span class="hljs-comment"># Immutable collection of above.</span>
  2025. &lt;bytes&gt; = &lt;Wave_read&gt;.readframes(nframes) <span class="hljs-comment"># Returns next 'nframes' frames.</span>
  2026. </code></pre>
  2027. <pre><code class="python language-python hljs">&lt;Wave_write&gt; = wave.open(<span class="hljs-string">'&lt;path&gt;'</span>, <span class="hljs-string">'wb'</span>) <span class="hljs-comment"># Truncates existing file.</span>
  2028. &lt;Wave_write&gt;.setframerate(&lt;int&gt;) <span class="hljs-comment"># 44100 for CD, 48000 for video.</span>
  2029. &lt;Wave_write&gt;.setnchannels(&lt;int&gt;) <span class="hljs-comment"># 1 for mono, 2 for stereo.</span>
  2030. &lt;Wave_write&gt;.setsampwidth(&lt;int&gt;) <span class="hljs-comment"># 2 for CD quality sound.</span>
  2031. &lt;Wave_write&gt;.setparams(&lt;params&gt;) <span class="hljs-comment"># Sets all parameters.</span>
  2032. &lt;Wave_write&gt;.writeframes(&lt;bytes&gt;) <span class="hljs-comment"># Appends frames to the file.</span>
  2033. </code></pre>
  2034. <ul>
  2035. <li><strong>Bytes object contains a sequence of frames, each consisting of one or more samples.</strong></li>
  2036. <li><strong>In a stereo signal, the first sample of a frame belongs to the left channel.</strong></li>
  2037. <li><strong>Each sample consists of one or more bytes that, when converted to an integer, indicate the displacement of a speaker membrane at a given moment.</strong></li>
  2038. <li><strong>If sample width is one, then the integer should be encoded unsigned.</strong></li>
  2039. <li><strong>For all other sizes, the integer should be encoded signed with little-endian byte order.</strong></li>
  2040. </ul>
  2041. <div><h3 id="samplevalues">Sample Values</h3><pre><code class="text language-text">┏━━━━━━━━━━━┯━━━━━━━━━━━━━┯━━━━━━┯━━━━━━━━━━━━━┓
  2042. ┃ sampwidth │ min │ zero │ max ┃
  2043. ┠───────────┼─────────────┼──────┼─────────────┨
  2044. ┃ 1 │ 0 │ 128 │ 255 ┃
  2045. ┃ 2 │ -32768 │ 0 │ 32767 ┃
  2046. ┃ 3 │ -8388608 │ 0 │ 8388607 ┃
  2047. ┃ 4 │ -2147483648 │ 0 │ 2147483647 ┃
  2048. ┗━━━━━━━━━━━┷━━━━━━━━━━━━━┷━━━━━━┷━━━━━━━━━━━━━┛
  2049. </code></pre></div>
  2050. <div><h3 id="readfloatsamplesfromwavfile">Read Float Samples from WAV File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_wav_file</span><span class="hljs-params">(filename)</span>:</span>
  2051. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_int</span><span class="hljs-params">(a_bytes)</span>:</span>
  2052. an_int = int.from_bytes(a_bytes, <span class="hljs-string">'little'</span>, signed=width!=<span class="hljs-number">1</span>)
  2053. <span class="hljs-keyword">return</span> an_int - <span class="hljs-number">128</span> * (width == <span class="hljs-number">1</span>)
  2054. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  2055. width = file.getsampwidth()
  2056. frames = file.readframes(<span class="hljs-number">-1</span>)
  2057. byte_samples = (frames[i: i + width] <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">0</span>, len(frames), width))
  2058. <span class="hljs-keyword">return</span> [get_int(b) / pow(<span class="hljs-number">2</span>, width * <span class="hljs-number">8</span> - <span class="hljs-number">1</span>) <span class="hljs-keyword">for</span> b <span class="hljs-keyword">in</span> byte_samples]
  2059. </code></pre></div>
  2060. <div><h3 id="writefloatsamplestowavfile">Write Float Samples to WAV File</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">write_to_wav_file</span><span class="hljs-params">(filename, float_samples, nchannels=<span class="hljs-number">1</span>, sampwidth=<span class="hljs-number">2</span>, framerate=<span class="hljs-number">44100</span>)</span>:</span>
  2061. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_bytes</span><span class="hljs-params">(a_float)</span>:</span>
  2062. a_float = max(<span class="hljs-number">-1</span>, min(<span class="hljs-number">1</span> - <span class="hljs-number">2e-16</span>, a_float))
  2063. a_float += sampwidth == <span class="hljs-number">1</span>
  2064. a_float *= pow(<span class="hljs-number">2</span>, sampwidth * <span class="hljs-number">8</span> - <span class="hljs-number">1</span>)
  2065. <span class="hljs-keyword">return</span> int(a_float).to_bytes(sampwidth, <span class="hljs-string">'little'</span>, signed=sampwidth!=<span class="hljs-number">1</span>)
  2066. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  2067. file.setnchannels(nchannels)
  2068. file.setsampwidth(sampwidth)
  2069. file.setframerate(framerate)
  2070. file.writeframes(<span class="hljs-string">b''</span>.join(get_bytes(f) <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> float_samples))
  2071. </code></pre></div>
  2072. <div><h3 id="examples-1">Examples</h3><div><h4 id="savesasinewavetoamonowavfile">Saves a sine wave to a mono WAV file:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> pi, sin
  2073. samples_f = (sin(i * <span class="hljs-number">2</span> * pi * <span class="hljs-number">440</span> / <span class="hljs-number">44100</span>) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">100000</span>))
  2074. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, samples_f)
  2075. </code></pre></div></div>
  2076. <div><h4 id="addsnoisetoamonowavfile">Adds noise to a mono WAV file:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random
  2077. add_noise = <span class="hljs-keyword">lambda</span> value: value + (random() - <span class="hljs-number">0.5</span>) * <span class="hljs-number">0.03</span>
  2078. samples_f = (add_noise(f) <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> read_wav_file(<span class="hljs-string">'test.wav'</span>))
  2079. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, samples_f)
  2080. </code></pre></div>
  2081. <div><h4 id="playsawavfile">Plays a WAV file:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install simpleaudio</span>
  2082. <span class="hljs-keyword">from</span> simpleaudio <span class="hljs-keyword">import</span> play_buffer
  2083. <span class="hljs-keyword">with</span> wave.open(<span class="hljs-string">'test.wav'</span>, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  2084. p = file.getparams()
  2085. frames = file.readframes(<span class="hljs-number">-1</span>)
  2086. play_buffer(frames, p.nchannels, p.sampwidth, p.framerate)
  2087. </code></pre></div>
  2088. <div><h3 id="texttospeech">Text to Speech</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pyttsx3</span>
  2089. <span class="hljs-keyword">import</span> pyttsx3
  2090. engine = pyttsx3.init()
  2091. engine.say(<span class="hljs-string">'Sally sells seashells by the seashore.'</span>)
  2092. engine.runAndWait()
  2093. </code></pre></div>
  2094. <div><h2 id="synthesizer"><a href="#synthesizer" name="synthesizer">#</a>Synthesizer</h2><div><h4 id="playspopcornbygershonkingsley">Plays Popcorn by Gershon Kingsley:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install simpleaudio</span>
  2095. <span class="hljs-keyword">import</span> simpleaudio, math, struct
  2096. <span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain, repeat
  2097. F = <span class="hljs-number">44100</span>
  2098. P1 = <span class="hljs-string">'71♪,69,,71♪,66,,62♪,66,,59♪,,,'</span>
  2099. P2 = <span class="hljs-string">'71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'</span>
  2100. get_pause = <span class="hljs-keyword">lambda</span> seconds: repeat(<span class="hljs-number">0</span>, int(seconds * F))
  2101. sin_f = <span class="hljs-keyword">lambda</span> i, hz: math.sin(i * <span class="hljs-number">2</span> * math.pi * hz / F)
  2102. get_wave = <span class="hljs-keyword">lambda</span> hz, seconds: (sin_f(i, hz) <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(int(seconds * F)))
  2103. get_hz = <span class="hljs-keyword">lambda</span> key: <span class="hljs-number">8.176</span> * <span class="hljs-number">2</span> ** (int(key) / <span class="hljs-number">12</span>)
  2104. parse_note = <span class="hljs-keyword">lambda</span> note: (get_hz(note[:<span class="hljs-number">2</span>]), <span class="hljs-number">0.25</span> <span class="hljs-keyword">if</span> <span class="hljs-string">'♪'</span> <span class="hljs-keyword">in</span> note <span class="hljs-keyword">else</span> <span class="hljs-number">0.125</span>)
  2105. get_samples = <span class="hljs-keyword">lambda</span> note: get_wave(*parse_note(note)) <span class="hljs-keyword">if</span> note <span class="hljs-keyword">else</span> get_pause(<span class="hljs-number">0.125</span>)
  2106. samples_f = chain.from_iterable(get_samples(n) <span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> <span class="hljs-string">f'<span class="hljs-subst">{P1}</span><span class="hljs-subst">{P1}</span><span class="hljs-subst">{P2}</span>'</span>.split(<span class="hljs-string">','</span>))
  2107. samples_b = <span class="hljs-string">b''</span>.join(struct.pack(<span class="hljs-string">'&lt;h'</span>, int(f * <span class="hljs-number">30000</span>)) <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> samples_f)
  2108. simpleaudio.play_buffer(samples_b, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, F)
  2109. </code></pre></div></div>
  2110. <div><h2 id="pygame"><a href="#pygame" name="pygame">#</a>Pygame</h2><div><h3 id="basicexample-1">Basic Example</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pygame</span>
  2111. <span class="hljs-keyword">import</span> pygame <span class="hljs-keyword">as</span> pg
  2112. pg.init()
  2113. screen = pg.display.set_mode((<span class="hljs-number">500</span>, <span class="hljs-number">500</span>))
  2114. rect = pg.Rect(<span class="hljs-number">240</span>, <span class="hljs-number">240</span>, <span class="hljs-number">20</span>, <span class="hljs-number">20</span>)
  2115. <span class="hljs-keyword">while</span> all(event.type != pg.QUIT <span class="hljs-keyword">for</span> event <span class="hljs-keyword">in</span> pg.event.get()):
  2116. deltas = {pg.K_UP: (<span class="hljs-number">0</span>, <span class="hljs-number">-3</span>), pg.K_RIGHT: (<span class="hljs-number">3</span>, <span class="hljs-number">0</span>), pg.K_DOWN: (<span class="hljs-number">0</span>, <span class="hljs-number">3</span>), pg.K_LEFT: (<span class="hljs-number">-3</span>, <span class="hljs-number">0</span>)}
  2117. <span class="hljs-keyword">for</span> delta <span class="hljs-keyword">in</span> (deltas.get(i) <span class="hljs-keyword">for</span> i, on <span class="hljs-keyword">in</span> enumerate(pg.key.get_pressed()) <span class="hljs-keyword">if</span> on):
  2118. rect = rect.move(delta) <span class="hljs-keyword">if</span> delta <span class="hljs-keyword">else</span> rect
  2119. screen.fill((<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>))
  2120. pg.draw.rect(screen, (<span class="hljs-number">255</span>, <span class="hljs-number">255</span>, <span class="hljs-number">255</span>), rect)
  2121. pg.display.flip()
  2122. </code></pre></div></div>
  2123. <div><h3 id="rectangle">Rectangle</h3><p><strong>Object for storing rectangular coordinates.</strong></p><pre><code class="python language-python hljs">&lt;Rect&gt; = pg.Rect(x, y, width, height) <span class="hljs-comment"># X and y are coordinates of topleft corner.</span>
  2124. &lt;int&gt; = &lt;Rect&gt;.x/y/centerx/centery/… <span class="hljs-comment"># Top, right, bottom, left.</span>
  2125. &lt;tup.&gt; = &lt;Rect&gt;.topleft/center/… <span class="hljs-comment"># Topright, bottomright, bottomleft.</span>
  2126. &lt;Rect&gt; = &lt;Rect&gt;.move((x, y)) <span class="hljs-comment"># Use move_ip() to move in place.</span>
  2127. </code></pre></div>
  2128. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;Rect&gt;.collidepoint((x, y)) <span class="hljs-comment"># Tests if a point is inside a rectangle.</span>
  2129. &lt;bool&gt; = &lt;Rect&gt;.colliderect(&lt;Rect&gt;) <span class="hljs-comment"># Tests if two rectangles overlap.</span>
  2130. &lt;int&gt; = &lt;Rect&gt;.collidelist(&lt;list_of_Rect&gt;) <span class="hljs-comment"># Returns index of first colliding Rect or -1.</span>
  2131. &lt;list&gt; = &lt;Rect&gt;.collidelistall(&lt;list_of_Rect&gt;) <span class="hljs-comment"># Returns indexes of all colliding Rects.</span>
  2132. </code></pre>
  2133. <div><h3 id="surface">Surface</h3><p><strong>Object for representing images.</strong></p><pre><code class="python language-python hljs">&lt;Surf&gt; = pg.display.set_mode((width, height)) <span class="hljs-comment"># Returns the display surface.</span>
  2134. &lt;Surf&gt; = pg.Surface((width, height)) <span class="hljs-comment"># Creates a new surface.</span>
  2135. &lt;Surf&gt; = pg.image.load(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Loads the image.</span>
  2136. &lt;Surf&gt; = &lt;Surf&gt;.subsurface(&lt;Rect&gt;) <span class="hljs-comment"># Returns a subsurface.</span>
  2137. </code></pre></div>
  2138. <pre><code class="python language-python hljs">&lt;Surf&gt;.fill(color) <span class="hljs-comment"># Fills the whole surface.</span>
  2139. &lt;Surf&gt;.set_at((x, y), color) <span class="hljs-comment"># Updates pixel.</span>
  2140. &lt;Surf&gt;.blit(&lt;Surface&gt;, (x, y)) <span class="hljs-comment"># Draws passed surface to the surface.</span>
  2141. </code></pre>
  2142. <pre><code class="python language-python hljs">&lt;Surf&gt; = pg.transform.flip(&lt;Surf&gt;, xbool, ybool)
  2143. &lt;Surf&gt; = pg.transform.rotate(&lt;Surf&gt;, degrees)
  2144. &lt;Surf&gt; = pg.transform.scale(&lt;Surf&gt;, (width, height))
  2145. </code></pre>
  2146. <pre><code class="python language-python hljs">pg.draw.line(&lt;Surf&gt;, color, (x1, y1), (x2, y2), width)
  2147. pg.draw.arc(&lt;Surf&gt;, color, &lt;Rect&gt;, from_radians, to_radians)
  2148. pg.draw.rect(&lt;Surf&gt;, color, &lt;Rect&gt;)
  2149. pg.draw.polygon(&lt;Surf&gt;, color, points)
  2150. pg.draw.ellipse(&lt;Surf&gt;, color, &lt;Rect&gt;)
  2151. </code></pre>
  2152. <div><h3 id="font">Font</h3><pre><code class="python language-python hljs">&lt;Font&gt; = pg.font.SysFont(<span class="hljs-string">'&lt;name&gt;'</span>, size, bold=<span class="hljs-keyword">False</span>, italic=<span class="hljs-keyword">False</span>)
  2153. &lt;Font&gt; = pg.font.Font(<span class="hljs-string">'&lt;path&gt;'</span>, size)
  2154. &lt;Surf&gt; = &lt;Font&gt;.render(text, antialias, color, background=<span class="hljs-keyword">None</span>)
  2155. </code></pre></div>
  2156. <div><h3 id="sound">Sound</h3><pre><code class="python language-python hljs">&lt;Sound&gt; = pg.mixer.Sound(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Loads the WAV file.</span>
  2157. &lt;Sound&gt;.play() <span class="hljs-comment"># Starts playing the sound.</span>
  2158. </code></pre></div>
  2159. <div><h3 id="basicmariobrothersexample">Basic Mario Brothers Example</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> collections, dataclasses, enum, io, pygame, urllib.request, itertools <span class="hljs-keyword">as</span> it
  2160. <span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint
  2161. P = collections.namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'x y'</span>) <span class="hljs-comment"># Position</span>
  2162. D = enum.Enum(<span class="hljs-string">'D'</span>, <span class="hljs-string">'n e s w'</span>) <span class="hljs-comment"># Direction</span>
  2163. SIZE, MAX_SPEED = <span class="hljs-number">50</span>, P(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>) <span class="hljs-comment"># Screen size, Speed limit</span>
  2164. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  2165. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_screen</span><span class="hljs-params">()</span>:</span>
  2166. pygame.init()
  2167. <span class="hljs-keyword">return</span> pygame.display.set_mode(<span class="hljs-number">2</span> * [SIZE*<span class="hljs-number">16</span>])
  2168. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_images</span><span class="hljs-params">()</span>:</span>
  2169. url = <span class="hljs-string">'https://gto76.github.io/python-cheatsheet/web/mario_bros.png'</span>
  2170. img = pygame.image.load(io.BytesIO(urllib.request.urlopen(url).read()))
  2171. <span class="hljs-keyword">return</span> [img.subsurface(get_rect(x, <span class="hljs-number">0</span>)) <span class="hljs-keyword">for</span> x <span class="hljs-keyword">in</span> range(img.get_width() // <span class="hljs-number">16</span>)]
  2172. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_mario</span><span class="hljs-params">()</span>:</span>
  2173. Mario = dataclasses.make_dataclass(<span class="hljs-string">'Mario'</span>, <span class="hljs-string">'rect spd facing_left frame_cycle'</span>.split())
  2174. <span class="hljs-keyword">return</span> Mario(get_rect(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>), P(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-keyword">False</span>, it.cycle(range(<span class="hljs-number">3</span>)))
  2175. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_tiles</span><span class="hljs-params">()</span>:</span>
  2176. positions = [p <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> it.product(range(SIZE), repeat=<span class="hljs-number">2</span>) <span class="hljs-keyword">if</span> {*p} &amp; {<span class="hljs-number">0</span>, SIZE<span class="hljs-number">-1</span>}] + \
  2177. [(randint(<span class="hljs-number">1</span>, SIZE<span class="hljs-number">-2</span>), randint(<span class="hljs-number">2</span>, SIZE<span class="hljs-number">-2</span>)) <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(SIZE**<span class="hljs-number">2</span> // <span class="hljs-number">10</span>)]
  2178. <span class="hljs-keyword">return</span> [get_rect(*p) <span class="hljs-keyword">for</span> p <span class="hljs-keyword">in</span> positions]
  2179. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_rect</span><span class="hljs-params">(x, y)</span>:</span>
  2180. <span class="hljs-keyword">return</span> pygame.Rect(x*<span class="hljs-number">16</span>, y*<span class="hljs-number">16</span>, <span class="hljs-number">16</span>, <span class="hljs-number">16</span>)
  2181. run(get_screen(), get_images(), get_mario(), get_tiles())
  2182. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">run</span><span class="hljs-params">(screen, images, mario, tiles)</span>:</span>
  2183. clock = pygame.time.Clock()
  2184. <span class="hljs-keyword">while</span> all(event.type != pygame.QUIT <span class="hljs-keyword">for</span> event <span class="hljs-keyword">in</span> pygame.event.get()):
  2185. keys = {pygame.K_UP: D.n, pygame.K_RIGHT: D.e, pygame.K_DOWN: D.s, pygame.K_LEFT: D.w}
  2186. pressed = {keys.get(i) <span class="hljs-keyword">for</span> i, on <span class="hljs-keyword">in</span> enumerate(pygame.key.get_pressed()) <span class="hljs-keyword">if</span> on}
  2187. update_speed(mario, tiles, pressed)
  2188. update_position(mario, tiles)
  2189. draw(screen, images, mario, tiles, pressed)
  2190. clock.tick(<span class="hljs-number">28</span>)
  2191. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_speed</span><span class="hljs-params">(mario, tiles, pressed)</span>:</span>
  2192. x, y = mario.spd
  2193. x += <span class="hljs-number">2</span> * ((D.e <span class="hljs-keyword">in</span> pressed) - (D.w <span class="hljs-keyword">in</span> pressed))
  2194. x -= x // abs(x) <span class="hljs-keyword">if</span> x <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>
  2195. y += <span class="hljs-number">1</span> <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles) <span class="hljs-keyword">else</span> (<span class="hljs-number">-10</span> <span class="hljs-keyword">if</span> D.n <span class="hljs-keyword">in</span> pressed <span class="hljs-keyword">else</span> <span class="hljs-number">0</span>)
  2196. mario.spd = P(*[max(-limit, min(limit, s)) <span class="hljs-keyword">for</span> limit, s <span class="hljs-keyword">in</span> zip(MAX_SPEED, P(x, y))])
  2197. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">update_position</span><span class="hljs-params">(mario, tiles)</span>:</span>
  2198. new_p = mario.rect.topleft
  2199. larger_speed = max(abs(s) <span class="hljs-keyword">for</span> s <span class="hljs-keyword">in</span> mario.spd)
  2200. <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(larger_speed):
  2201. mario.spd = stop_on_collision(mario.spd, get_boundaries(mario.rect, tiles))
  2202. new_p = P(*[a + s/larger_speed <span class="hljs-keyword">for</span> a, s <span class="hljs-keyword">in</span> zip(new_p, mario.spd)])
  2203. mario.rect.topleft = new_p
  2204. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_boundaries</span><span class="hljs-params">(rect, tiles)</span>:</span>
  2205. deltas = {D.n: P(<span class="hljs-number">0</span>, <span class="hljs-number">-1</span>), D.e: P(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>), D.s: P(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>), D.w: P(<span class="hljs-number">-1</span>, <span class="hljs-number">0</span>)}
  2206. <span class="hljs-keyword">return</span> {d <span class="hljs-keyword">for</span> d, delta <span class="hljs-keyword">in</span> deltas.items() <span class="hljs-keyword">if</span> rect.move(delta).collidelist(tiles) != <span class="hljs-number">-1</span>}
  2207. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">stop_on_collision</span><span class="hljs-params">(spd, bounds)</span>:</span>
  2208. <span class="hljs-keyword">return</span> P(x=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.w <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.e <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.x &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.x,
  2209. y=<span class="hljs-number">0</span> <span class="hljs-keyword">if</span> (D.n <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &lt; <span class="hljs-number">0</span>) <span class="hljs-keyword">or</span> (D.s <span class="hljs-keyword">in</span> bounds <span class="hljs-keyword">and</span> spd.y &gt; <span class="hljs-number">0</span>) <span class="hljs-keyword">else</span> spd.y)
  2210. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen, images, mario, tiles, pressed)</span>:</span>
  2211. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_frame_index</span><span class="hljs-params">()</span>:</span>
  2212. <span class="hljs-keyword">if</span> D.s <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> get_boundaries(mario.rect, tiles):
  2213. <span class="hljs-keyword">return</span> <span class="hljs-number">4</span>
  2214. <span class="hljs-keyword">return</span> next(mario.frame_cycle) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> <span class="hljs-number">6</span>
  2215. screen.fill((<span class="hljs-number">85</span>, <span class="hljs-number">168</span>, <span class="hljs-number">255</span>))
  2216. mario.facing_left = (D.w <span class="hljs-keyword">in</span> pressed) <span class="hljs-keyword">if</span> {D.w, D.e} &amp; pressed <span class="hljs-keyword">else</span> mario.facing_left
  2217. screen.blit(images[get_frame_index() + mario.facing_left * <span class="hljs-number">9</span>], mario.rect)
  2218. <span class="hljs-keyword">for</span> rect <span class="hljs-keyword">in</span> tiles:
  2219. screen.blit(images[<span class="hljs-number">18</span> <span class="hljs-keyword">if</span> {*rect.topleft} &amp; {<span class="hljs-number">0</span>, (SIZE<span class="hljs-number">-1</span>)*<span class="hljs-number">16</span>} <span class="hljs-keyword">else</span> <span class="hljs-number">19</span>], rect)
  2220. pygame.display.flip()
  2221. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  2222. main()
  2223. </code></pre></div>
  2224. <div><h2 id="basicscripttemplate"><a href="#basicscripttemplate" name="basicscripttemplate">#</a>Basic Script Template</h2><pre><code class="python language-python hljs"><span class="hljs-comment">#!/usr/bin/env python3</span>
  2225. <span class="hljs-comment">#</span>
  2226. <span class="hljs-comment"># Usage: .py</span>
  2227. <span class="hljs-comment">#</span>
  2228. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  2229. <span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  2230. <span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  2231. <span class="hljs-keyword">from</span> sys <span class="hljs-keyword">import</span> argv
  2232. <span class="hljs-keyword">import</span> re
  2233. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  2234. <span class="hljs-keyword">pass</span>
  2235. <span class="hljs-comment">###</span>
  2236. <span class="hljs-comment">## UTIL</span>
  2237. <span class="hljs-comment">#</span>
  2238. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
  2239. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  2240. <span class="hljs-keyword">return</span> file.readlines()
  2241. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  2242. main()
  2243. </code></pre></div>
  2244. <footer>
  2245. <aside>March 15, 2020</aside>
  2246. <a href="../" rel="author">Jure Šorn</a>
  2247. </footer>
  2248. <br>
  2249. <br>
  2250. <br>
  2251. <script src="web/jquery-3.4.0.min.js"></script>
  2252. <script src="web/script_2.js"></script>
  2253. <script type="text/javascript" src="https://transactions.sendowl.com/assets/sendowl.js" ></script>
  2254. </body>
  2255. </html>