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.

2460 lines
206 KiB

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
5 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
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
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
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
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
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
5 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
4 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
4 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
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
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
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
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
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
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
4 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
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
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
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
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
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
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
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
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
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
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
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
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
5 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
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
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
  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. </head>
  17. <style>
  18. @import url(web/style.css);
  19. .join,
  20. .link,
  21. .node rect {
  22. fill: none;
  23. stroke: #636363;
  24. stroke-width: 1.5px;
  25. }
  26. .link {
  27. stroke: #969696;
  28. }
  29. .node rect {
  30. fill: white;
  31. }
  32. .link path,
  33. .node rect,
  34. .node text,
  35. .join {
  36. -webkit-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  37. -moz-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  38. -ms-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  39. -o-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  40. transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  41. }
  42. .node .element rect {
  43. fill: #bdbdbd;
  44. stroke: none;
  45. }
  46. .node .null rect {
  47. fill: none;
  48. stroke: none;
  49. }
  50. .node .null text {
  51. fill: #636363;
  52. }
  53. .node .selection rect {
  54. stroke: #e6550d;
  55. }
  56. .node .data rect {
  57. stroke: #3182bd;
  58. }
  59. .node .datum rect {
  60. fill: #d9d9d9;
  61. stroke: none;
  62. }
  63. .node .code text {
  64. font-family: monospace;
  65. }
  66. .node .key rect {
  67. fill: #a1d99b;
  68. stroke: none;
  69. }
  70. .link .to-key,
  71. .join {
  72. stroke: #a1d99b;
  73. }
  74. .join {
  75. stroke-dasharray: 2,2;
  76. }
  77. .link .to-null {
  78. stroke-dasharray: .5,3.5;
  79. stroke-linecap: round;
  80. }
  81. .link .from-data {
  82. stroke: #3182bd;
  83. }
  84. .play circle {
  85. fill: #fff;
  86. stroke: #000;
  87. stroke-width: 3px;
  88. }
  89. .play:hover path {
  90. fill: #f00;
  91. }
  92. .play.mousedown circle {
  93. fill: #f00;
  94. }
  95. .play.mousedown path {
  96. fill: #fff;
  97. }
  98. .play rect {
  99. fill: none;
  100. pointer-events: all;
  101. cursor: pointer;
  102. }
  103. code span {
  104. -webkit-transition: background 250ms linear;
  105. -moz-transition: background 250ms linear;
  106. -ms-transition: background 250ms linear;
  107. -o-transition: background 250ms linear;
  108. transition: background 250ms linear;
  109. }
  110. pre.prettyprint, code.prettyprint {
  111. background-color: #222;
  112. border-radius: 8px;
  113. font-size: 15px;
  114. }
  115. pre.prettyprint {
  116. width: 90%;
  117. margin: 0.5em;
  118. padding: 1em;
  119. white-space: pre-wrap;
  120. }
  121. #return-to-top {
  122. position: fixed;
  123. bottom: 20px;
  124. right: 20px;
  125. background: rgb(0, 0, 0);
  126. background: rgba(0, 0, 0, 0.2);
  127. width: 50px;
  128. height: 50px;
  129. display: block;
  130. text-decoration: none;
  131. -webkit-border-radius: 35px;
  132. -moz-border-radius: 35px;
  133. border-radius: 35px;
  134. display: none;
  135. -webkit-transition: all 0.3s linear;
  136. -moz-transition: all 0.3s ease;
  137. -ms-transition: all 0.3s ease;
  138. -o-transition: all 0.3s ease;
  139. transition: all 0.3s ease;
  140. }
  141. #return-to-top i {
  142. color: #fff;
  143. margin: 0;
  144. position: relative;
  145. left: 16px;
  146. top: 13px;
  147. font-size: 19px;
  148. -webkit-transition: all 0.3s ease;
  149. -moz-transition: all 0.3s ease;
  150. -ms-transition: all 0.3s ease;
  151. -o-transition: all 0.3s ease;
  152. transition: all 0.3s ease;
  153. }
  154. #return-to-top:hover {
  155. background: rgba(0, 0, 0, 0.35);
  156. }
  157. #return-to-top:hover i {
  158. color: #f0f0f0;
  159. }
  160. @media print {
  161. .pagebreak {
  162. page-break-before: always;
  163. }
  164. div {
  165. page-break-inside: avoid;
  166. }
  167. pre {
  168. page-break-inside: avoid;
  169. }
  170. }
  171. </style>
  172. <body>
  173. <header>
  174. <aside>December 15, 2019</aside>
  175. <a href="../" rel="author">Jure Šorn</a>
  176. </header>
  177. <a href="javascript:" id="return-to-top"><i class="icon-chevron-up"></i></a>
  178. <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://gto76.github.io/python-cheatsheet/web/python-cheatsheet-4e31793.pdf">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>.
  179. </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> = {
  180. <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>],
  181. <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>],
  182. <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_Types</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exceptions</a>],
  183. <strong><span class="hljs-string"><span class="hljs-string">'4. System'</span></span></strong>: [<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">Command_Execution</a>],
  184. <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">MemoryView</a>, <a href="#deque">Deque</a>],
  185. <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="#coroutine">Coroutine</a>],
  186. <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>,
  187. <a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#animation">Animation</a>, <a href="#audio">Audio</a>, <a href="#synthesizer">Synthesizer</a>]
  188. }
  189. </code></pre></div></div>
  190. <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>
  191. main()
  192. </code></pre></div>
  193. <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]
  194. </code></pre></div>
  195. <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>
  196. &lt;list&gt;.extend(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;list&gt; += &lt;collection&gt;</span>
  197. </code></pre>
  198. <pre><code class="python language-python hljs">&lt;list&gt;.sort()
  199. &lt;list&gt;.reverse()
  200. &lt;list&gt; = sorted(&lt;collection&gt;)
  201. &lt;iter&gt; = reversed(&lt;list&gt;)
  202. </code></pre>
  203. <pre><code class="python language-python hljs">sum_of_elements = sum(&lt;collection&gt;)
  204. elementwise_sum = [sum(pair) <span class="hljs-keyword">for</span> pair <span class="hljs-keyword">in</span> zip(list_a, list_b)]
  205. sorted_by_second = sorted(&lt;collection&gt;, key=<span class="hljs-keyword">lambda</span> el: el[<span class="hljs-number">1</span>])
  206. 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>]))
  207. flatter_list = list(itertools.chain.from_iterable(&lt;list&gt;))
  208. product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out, x: out * x, &lt;collection&gt;)
  209. list_of_chars = list(&lt;str&gt;)
  210. </code></pre>
  211. <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>
  212. index = &lt;list&gt;.index(&lt;el&gt;) <span class="hljs-comment"># Returns index of first occurrence or raises ValueError.</span>
  213. &lt;list&gt;.insert(index, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
  214. &lt;el&gt; = &lt;list&gt;.pop([index]) <span class="hljs-comment"># Removes and returns item at index or from the end.</span>
  215. &lt;list&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Removes first occurrence of item or raises ValueError.</span>
  216. &lt;list&gt;.clear() <span class="hljs-comment"># Removes all items. Also works on dictionary and set.</span>
  217. </code></pre>
  218. <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>
  219. &lt;view&gt; = &lt;dict&gt;.values() <span class="hljs-comment"># Coll. of values that reflects changes.</span>
  220. &lt;view&gt; = &lt;dict&gt;.items() <span class="hljs-comment"># Coll. of key-value tuples.</span>
  221. </code></pre></div>
  222. <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>
  223. 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>
  224. &lt;dict&gt; = collections.defaultdict(&lt;type&gt;) <span class="hljs-comment"># Creates a dict with default value of type.</span>
  225. &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>
  226. </code></pre>
  227. <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>
  228. &lt;dict&gt; = dict(zip(keys, values)) <span class="hljs-comment"># Creates a dict from two collections.</span>
  229. &lt;dict&gt; = dict.fromkeys(keys [, value]) <span class="hljs-comment"># Creates a dict from collection of keys.</span>
  230. </code></pre>
  231. <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>
  232. value = &lt;dict&gt;.pop(key) <span class="hljs-comment"># Removes item or raises KeyError.</span>
  233. {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>
  234. {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 dictionary filtered by keys.</span>
  235. </code></pre>
  236. <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
  237. <span class="hljs-meta">&gt;&gt;&gt; </span>colors = [<span class="hljs-string">'blue'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>]
  238. <span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter(colors)
  239. <span class="hljs-meta">&gt;&gt;&gt; </span>counter[<span class="hljs-string">'yellow'</span>] += <span class="hljs-number">1</span>
  240. 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>})
  241. <span class="hljs-meta">&gt;&gt;&gt; </span>counter.most_common()[<span class="hljs-number">0</span>]
  242. (<span class="hljs-string">'blue'</span>, <span class="hljs-number">3</span>)
  243. </code></pre></div>
  244. <div><h2 id="set"><a href="#set" name="set">#</a>Set</h2><pre><code class="python language-python hljs">&lt;set&gt; = set()
  245. </code></pre></div>
  246. <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>
  247. &lt;set&gt;.update(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;set&gt; |= &lt;set&gt;</span>
  248. </code></pre>
  249. <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>
  250. &lt;set&gt; = &lt;set&gt;.intersection(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &amp; &lt;set&gt;</span>
  251. &lt;set&gt; = &lt;set&gt;.difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; - &lt;set&gt;</span>
  252. &lt;set&gt; = &lt;set&gt;.symmetric_difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; ^ &lt;set&gt;</span>
  253. &lt;bool&gt; = &lt;set&gt;.issubset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &lt;= &lt;set&gt;</span>
  254. &lt;bool&gt; = &lt;set&gt;.issuperset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &gt;= &lt;set&gt;</span>
  255. </code></pre>
  256. <pre><code class="python language-python hljs">&lt;el&gt; = &lt;set&gt;.pop() <span class="hljs-comment"># Raises KeyError if empty.</span>
  257. &lt;set&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Raises KeyError if missing.</span>
  258. &lt;set&gt;.discard(&lt;el&gt;) <span class="hljs-comment"># Doesn't raise an error.</span>
  259. </code></pre>
  260. <div><h3 id="frozenset">Frozen Set</h3><ul>
  261. <li><strong>Is immutable and hashable.</strong></li>
  262. <li><strong>That means it can be used as a key in a dictionary or as an element in a set.</strong></li>
  263. </ul><pre><code class="python language-python hljs">&lt;frozenset&gt; = frozenset(&lt;collection&gt;)
  264. </code></pre></div>
  265. <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; = ()
  266. &lt;tuple&gt; = (&lt;el&gt;, )
  267. &lt;tuple&gt; = (&lt;el_1&gt;, &lt;el_2&gt; [, ...])
  268. </code></pre></div>
  269. <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
  270. <span class="hljs-meta">&gt;&gt;&gt; </span>Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  271. <span class="hljs-meta">&gt;&gt;&gt; </span>p = Point(<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  272. Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  273. <span class="hljs-meta">&gt;&gt;&gt; </span>p[<span class="hljs-number">0</span>]
  274. <span class="hljs-number">1</span>
  275. <span class="hljs-meta">&gt;&gt;&gt; </span>p.x
  276. <span class="hljs-number">1</span>
  277. <span class="hljs-meta">&gt;&gt;&gt; </span>getattr(p, <span class="hljs-string">'y'</span>)
  278. <span class="hljs-number">2</span>
  279. <span class="hljs-meta">&gt;&gt;&gt; </span>p._fields <span class="hljs-comment"># Or: Point._fields</span>
  280. (<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>)
  281. </code></pre></div>
  282. <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)
  283. &lt;range&gt; = range(from_inclusive, to_exclusive)
  284. &lt;range&gt; = range(from_inclusive, to_exclusive, ±step_size)
  285. </code></pre></div>
  286. <pre><code class="python language-python hljs">from_inclusive = &lt;range&gt;.start
  287. to_exclusive = &lt;range&gt;.stop
  288. </code></pre>
  289. <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]):
  290. ...
  291. </code></pre></div>
  292. <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>
  293. &lt;iter&gt; = iter(&lt;function&gt;, to_exclusive) <span class="hljs-comment"># A sequence of return values until 'to_exclusive'.</span>
  294. &lt;el&gt; = next(&lt;iter&gt; [, default]) <span class="hljs-comment"># Raises StopIteration or returns 'default' on end.</span>
  295. &lt;list&gt; = list(&lt;iter&gt;) <span class="hljs-comment"># Returns a list of iterator's remaining elements.</span>
  296. </code></pre></div>
  297. <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
  298. </code></pre></div>
  299. <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 incremented value endlessly.</span>
  300. &lt;iter&gt; = repeat(&lt;el&gt; [, times]) <span class="hljs-comment"># Returns element endlessly or 'times' times.</span>
  301. &lt;iter&gt; = cycle(&lt;collection&gt;) <span class="hljs-comment"># Repeats the sequence endlessly.</span>
  302. </code></pre>
  303. <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>
  304. &lt;iter&gt; = chain.from_iterable(&lt;collection&gt;) <span class="hljs-comment"># Empties collections inside a collection in order.</span>
  305. </code></pre>
  306. <pre><code class="python language-python hljs">&lt;iter&gt; = islice(&lt;collection&gt;, to_exclusive)
  307. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive [, +step_size])
  308. </code></pre>
  309. <div><h2 id="generator"><a href="#generator" name="generator">#</a>Generator</h2><ul>
  310. <li><strong>Any function that contains a yield statement returns a generator.</strong></li>
  311. <li><strong>Generators and iterators are interchangeable.</strong></li>
  312. </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>
  313. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  314. <span class="hljs-keyword">yield</span> start
  315. start += step
  316. </code></pre></div>
  317. <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>)
  318. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  319. (<span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>)
  320. </code></pre>
  321. <div><h2 id="type"><a href="#type" name="type">#</a>Type</h2><ul>
  322. <li><strong>Everything is an object.</strong></li>
  323. <li><strong>Every object has a type.</strong></li>
  324. <li><strong>Type and class are synonymous.</strong></li>
  325. </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>
  326. &lt;bool&gt; = isinstance(&lt;el&gt;, &lt;type&gt;) <span class="hljs-comment"># Or: issubclass(type(&lt;el&gt;), &lt;type&gt;)</span>
  327. </code></pre></div>
  328. <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
  329. (&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;)
  330. </span></code></pre>
  331. <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
  332. </code></pre></div>
  333. <div><h3 id="abc">ABC</h3><p><strong>An abstract base class introduces virtual subclasses, that don’t inherit from it but are still recognized by isinstance() and issubclass().</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
  334. <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)
  335. <span class="hljs-keyword">True</span>
  336. </code></pre></div>
  337. <pre><code class="text language-text">+------------------+------------+------------+------------+
  338. | | Sequence | Collection | Iterable |
  339. +------------------+------------+------------+------------+
  340. | list, range, str | yes | yes | yes |
  341. | dict, set | | yes | yes |
  342. | iter | | | yes |
  343. +------------------+------------+------------+------------+
  344. </code></pre>
  345. <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
  346. <span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(<span class="hljs-number">123</span>, Number)
  347. <span class="hljs-keyword">True</span>
  348. </code></pre>
  349. <pre><code class="text language-text">+--------------------+----------+----------+----------+----------+----------+
  350. | | Integral | Rational | Real | Complex | Number |
  351. +--------------------+----------+----------+----------+----------+----------+
  352. | int | yes | yes | yes | yes | yes |
  353. | fractions.Fraction | | yes | yes | yes | yes |
  354. | float | | | yes | yes | yes |
  355. | complex | | | | yes | yes |
  356. | decimal.Decimal | | | | | yes |
  357. +--------------------+----------+----------+----------+----------+----------+
  358. </code></pre>
  359. <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>
  360. &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>
  361. </code></pre></div>
  362. <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>
  363. &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>
  364. &lt;list&gt; = &lt;str&gt;.splitlines(keepends=<span class="hljs-keyword">False</span>) <span class="hljs-comment"># Splits on line breaks. Keeps them if 'keepends'.</span>
  365. &lt;str&gt; = &lt;str&gt;.join(&lt;coll_of_strings&gt;) <span class="hljs-comment"># Joins elements using string as separator.</span>
  366. </code></pre>
  367. <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>
  368. &lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  369. &lt;bool&gt; = &lt;str&gt;.endswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  370. &lt;int&gt; = &lt;str&gt;.find(&lt;sub_str&gt;) <span class="hljs-comment"># Returns start index of first match or -1.</span>
  371. &lt;int&gt; = &lt;str&gt;.index(&lt;sub_str&gt;) <span class="hljs-comment"># Same but raises ValueError if missing.</span>
  372. </code></pre>
  373. <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>
  374. &lt;str&gt; = &lt;str&gt;.translate(&lt;table&gt;) <span class="hljs-comment"># Use `str.maketrans(&lt;dict&gt;)` to generate table.</span>
  375. </code></pre>
  376. <pre><code class="python language-python hljs">&lt;str&gt; = chr(&lt;int&gt;) <span class="hljs-comment"># Converts int to unicode char.</span>
  377. &lt;int&gt; = ord(&lt;str&gt;) <span class="hljs-comment"># Converts unicode char to int.</span>
  378. </code></pre>
  379. <ul>
  380. <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>
  381. <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>
  382. </ul>
  383. <div><h3 id="propertymethods">Property Methods</h3><pre><code class="text language-text">+---------------+----------+----------+----------+----------+----------+
  384. | | [ !#$%…] | [a-zA-Z] | [¼½¾…] | [²³¹…] | [0-9] |
  385. +---------------+----------+----------+----------+----------+----------+
  386. | isprintable() | yes | yes | yes | yes | yes |
  387. | isalnum() | | yes | yes | yes | yes |
  388. | isnumeric() | | | yes | yes | yes |
  389. | isdigit() | | | | yes | yes |
  390. | isdecimal() | | | | | yes |
  391. +---------------+----------+----------+----------+----------+----------+
  392. </code></pre></div>
  393. <ul>
  394. <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…]'</span></code>.</strong></li>
  395. </ul>
  396. <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
  397. &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>
  398. &lt;list&gt; = re.findall(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as strings.</span>
  399. &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 keep the matches.</span>
  400. &lt;Match&gt; = re.search(&lt;regex&gt;, text) <span class="hljs-comment"># Searches for first occurrence of the pattern.</span>
  401. &lt;Match&gt; = re.match(&lt;regex&gt;, text) <span class="hljs-comment"># Searches only at the beginning of the text.</span>
  402. &lt;iter&gt; = re.finditer(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as match objects.</span>
  403. </code></pre></div>
  404. <ul>
  405. <li><strong>Search() and match() return None if they can't find a match.</strong></li>
  406. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.IGNORECASE'</span></code> can be used with all functions.</strong></li>
  407. <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>
  408. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.DOTALL'</span></code> makes dot also accept newline.</strong></li>
  409. <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>
  410. <li><strong>Add <code class="python hljs"><span class="hljs-string">'?'</span></code> after an operator to make it non-greedy.</strong></li>
  411. </ul>
  412. <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"># Whole match. Also group(0).</span>
  413. &lt;str&gt; = &lt;Match&gt;.group(<span class="hljs-number">1</span>) <span class="hljs-comment"># Part in first bracket.</span>
  414. &lt;tuple&gt; = &lt;Match&gt;.groups() <span class="hljs-comment"># All bracketed parts.</span>
  415. &lt;int&gt; = &lt;Match&gt;.start() <span class="hljs-comment"># Start index of a match.</span>
  416. &lt;int&gt; = &lt;Match&gt;.end() <span class="hljs-comment"># Exclusive end index of a match.</span>
  417. </code></pre></div>
  418. <div><h3 id="specialsequences">Special Sequences</h3><ul>
  419. <li><strong>By default digits, whitespaces and alphanumerics from all alphabets are matched, unless <code class="python hljs"><span class="hljs-string">'flags=re.ASCII'</span></code> argument is used.</strong></li>
  420. <li><strong>Use capital letter for negation.</strong></li>
  421. </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"># Digit</span>
  422. <span class="hljs-string">'\s'</span> == <span class="hljs-string">'[ \t\n\r\f\v]'</span> <span class="hljs-comment"># Whitespace</span>
  423. <span class="hljs-string">'\w'</span> == <span class="hljs-string">'[a-zA-Z0-9_]'</span> <span class="hljs-comment"># Alphanumeric</span>
  424. </code></pre></div>
  425. <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>
  426. &lt;str&gt; = <span class="hljs-string">'{}, {}'</span>.format(&lt;el_1&gt;, &lt;el_2&gt;)
  427. </code></pre></div>
  428. <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
  429. <span class="hljs-meta">&gt;&gt;&gt; </span>Person = namedtuple(<span class="hljs-string">'Person'</span>, <span class="hljs-string">'name height'</span>)
  430. <span class="hljs-meta">&gt;&gt;&gt; </span>person = Person(<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)
  431. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">f'<span class="hljs-subst">{person.height}</span>'</span>
  432. <span class="hljs-string">'187'</span>
  433. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">'{p.height}'</span>.format(p=person)
  434. <span class="hljs-string">'187'</span>
  435. </code></pre></div>
  436. <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>
  437. {&lt;el&gt;:^<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt; '</span>
  438. {&lt;el&gt;:&gt;<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt;'</span>
  439. </code></pre></div>
  440. <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>
  441. {&lt;el&gt;:&lt;<span class="hljs-number">0</span>} <span class="hljs-comment"># '&lt;el&gt;'</span>
  442. </code></pre>
  443. <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:&lt;<span class="hljs-number">10</span>} <span class="hljs-comment"># "'abcde' "</span>
  444. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">.3</span>} <span class="hljs-comment"># 'abc'</span>
  445. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># 'abc '</span>
  446. </code></pre></div>
  447. <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>
  448. { <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>_} <span class="hljs-comment"># ' 123_456'</span>
  449. { <span class="hljs-number">123456</span>:+<span class="hljs-number">10</span>} <span class="hljs-comment"># ' +123456'</span>
  450. {<span class="hljs-number">-123456</span>:=<span class="hljs-number">10</span>} <span class="hljs-comment"># '- 123456'</span>
  451. { <span class="hljs-number">123456</span>: } <span class="hljs-comment"># ' 123456'</span>
  452. {<span class="hljs-number">-123456</span>: } <span class="hljs-comment"># '-123456'</span>
  453. </code></pre></div>
  454. <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>
  455. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>f} <span class="hljs-comment"># ' 1.235'</span>
  456. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>e} <span class="hljs-comment"># ' 1.235e+00'</span>
  457. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>%} <span class="hljs-comment"># ' 123.456%'</span>
  458. </code></pre></div>
  459. <div><h4 id="comparisonoffloatpresentationtypes">Comparison of float presentation types:</h4><pre><code class="text language-text">+---------------+-----------------+-----------------+-----------------+-----------------+
  460. | | {&lt;float&gt;} | {&lt;float&gt;:f} | {&lt;float&gt;:e} | {&lt;float&gt;:%} |
  461. +---------------+-----------------+-----------------+-----------------+-----------------+
  462. | 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
  463. | 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
  464. | 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
  465. | 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
  466. | 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
  467. | 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
  468. | 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
  469. | 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' |
  470. +---------------+-----------------+-----------------+-----------------+-----------------+
  471. </code></pre></div>
  472. <pre><code class="text language-text">+---------------+-----------------+-----------------+-----------------+-----------------+
  473. | | {&lt;float&gt;:.2} | {&lt;float&gt;:.2f} | {&lt;float&gt;:.2e} | {&lt;float&gt;:.2%} |
  474. +---------------+-----------------+-----------------+-----------------+-----------------+
  475. | 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
  476. | 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
  477. | 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
  478. | 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
  479. | 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
  480. | 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
  481. | 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
  482. | 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' |
  483. +---------------+-----------------+-----------------+-----------------+-----------------+
  484. </code></pre>
  485. <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>
  486. {<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'</span>
  487. {<span class="hljs-number">90</span>:b} <span class="hljs-comment"># '1011010'</span>
  488. </code></pre></div>
  489. <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>
  490. &lt;float&gt; = float(&lt;int/str/bool&gt;) <span class="hljs-comment"># Or: &lt;real&gt;&lt;int&gt;</span>
  491. &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>
  492. &lt;Fraction&gt; = fractions.Fraction(numerator=<span class="hljs-number">0</span>, denominator=<span class="hljs-number">1</span>)
  493. &lt;Decimal&gt; = decimal.Decimal(&lt;str/int/float&gt;)
  494. </code></pre></div></div>
  495. <ul>
  496. <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>
  497. <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>
  498. <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>
  499. </ul>
  500. <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>
  501. &lt;num&gt; = abs(&lt;num&gt;) <span class="hljs-comment"># &lt;float&gt; = abs(&lt;complex&gt;)</span>
  502. &lt;num&gt; = round(&lt;num&gt; [, ±ndigits]) <span class="hljs-comment"># `round(126, -1) == 130`</span>
  503. </code></pre></div>
  504. <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
  505. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians
  506. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2
  507. </code></pre></div>
  508. <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, pvariance, pstdev
  509. </code></pre></div>
  510. <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
  511. &lt;float&gt; = random()
  512. &lt;int&gt; = randint(from_inclusive, to_inclusive)
  513. &lt;el&gt; = choice(&lt;list&gt;)
  514. shuffle(&lt;list&gt;)
  515. </code></pre></div>
  516. <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>
  517. &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>
  518. &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>
  519. <span class="hljs-string">'0b&lt;bin&gt;'</span> = bin(&lt;int&gt;) <span class="hljs-comment"># Or: '0x&lt;hex&gt;' = hex(&lt;int&gt;)</span>
  520. </code></pre></div>
  521. <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>
  522. &lt;int&gt; = &lt;int&gt; | &lt;int&gt; <span class="hljs-comment"># Or</span>
  523. &lt;int&gt; = &lt;int&gt; ^ &lt;int&gt; <span class="hljs-comment"># Xor (0 if both bits equal)</span>
  524. &lt;int&gt; = &lt;int&gt; &lt;&lt; n_bits <span class="hljs-comment"># Shift left</span>
  525. &lt;int&gt; = &lt;int&gt; &gt;&gt; n_bits <span class="hljs-comment"># Shift right</span>
  526. &lt;int&gt; = ~&lt;int&gt; <span class="hljs-comment"># Compliment (flips bits)</span>
  527. </code></pre></div>
  528. <div><h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2><ul>
  529. <li><strong>Every function returns an iterator.</strong></li>
  530. <li><strong>If you want to print the iterator, you need to pass it to the list() function!</strong></li>
  531. </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
  532. </code></pre></div>
  533. <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>)
  534. [(<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>),
  535. (<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>)]
  536. </code></pre>
  537. <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>)
  538. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'2'</span>),
  539. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'2'</span>)]
  540. </code></pre>
  541. <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>)
  542. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>)]
  543. </code></pre>
  544. <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>)
  545. [(<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>),
  546. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  547. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)]
  548. </code></pre>
  549. <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>)
  550. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  551. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  552. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)]
  553. </code></pre>
  554. <div><h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2><ul>
  555. <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>
  556. <li><strong>Time and datetime 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>
  557. <li><strong>If object is naive, it is presumed to be in the system's timezone.</strong></li>
  558. </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
  559. <span class="hljs-keyword">from</span> dateutil.tz <span class="hljs-keyword">import</span> UTC, tzlocal, gettz, resolve_imaginary
  560. </code></pre></div>
  561. <div><h3 id="constructors">Constructors</h3><pre><code class="python language-python apache hljs">&lt;D&gt; = date(year, month, day)
  562. &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>)
  563. &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>, ...)
  564. &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>,
  565. minutes=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>, weeks=<span class="hljs-number">0</span>)
  566. </code></pre></div>
  567. <ul>
  568. <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>
  569. <li><strong><code class="python hljs"><span class="hljs-string">'fold=1'</span></code> means second pass in case of time jumping back for one hour.</strong></li>
  570. <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 missing hour.</strong></li>
  571. </ul>
  572. <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>
  573. &lt;DTn&gt; = DT.utcnow() <span class="hljs-comment"># Naive datetime from current UTC time.</span>
  574. &lt;DTa&gt; = DT.now(&lt;tzinfo&gt;) <span class="hljs-comment"># Aware datetime from current tz time.</span>
  575. </code></pre></div>
  576. <ul>
  577. <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>
  578. </ul>
  579. <div><h3 id="timezone">Timezone</h3><pre><code class="python language-python hljs">&lt;tzinfo&gt; = UTC <span class="hljs-comment"># UTC timezone. London without DST.</span>
  580. &lt;tzinfo&gt; = tzlocal() <span class="hljs-comment"># Local timezone. Also gettz().</span>
  581. &lt;tzinfo&gt; = gettz(<span class="hljs-string">'&lt;Cont.&gt;/&lt;City&gt;'</span>) <span class="hljs-comment"># 'Continent/City_Name' timezone or None.</span>
  582. </code></pre></div>
  583. <pre><code class="python language-python apache hljs">&lt;DTa&gt; = &lt;DT&gt;.astimezone(&lt;tzinfo&gt;) <span class="hljs-comment"># Datetime, converted to passed timezone.</span>
  584. &lt;Ta/DTa&gt; = &lt;T/DT&gt;.replace(tzinfo=&lt;tzinfo&gt;) <span class="hljs-comment"># Unconverted object with new timezone.</span>
  585. </code></pre>
  586. <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>
  587. &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>
  588. &lt;D/DTn&gt; = D/DT.fromordinal(&lt;int&gt;) <span class="hljs-comment"># D/DTn from days since Christ, at midnight.</span>
  589. &lt;DTn&gt; = DT.fromtimestamp(&lt;real&gt;) <span class="hljs-comment"># Local time DTn from seconds since Epoch.</span>
  590. &lt;DTa&gt; = DT.fromtimestamp(&lt;real&gt;, &lt;tz.&gt;) <span class="hljs-comment"># Aware datetime from seconds since Epoch.</span>
  591. </code></pre></div>
  592. <ul>
  593. <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 a space or a <code class="python hljs"><span class="hljs-string">'T'</span></code>. Offset is formatted as: <code class="python hljs"><span class="hljs-string">'HH:MM'</span></code>.</strong></li>
  594. <li><strong>On Unix systems Epoch 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>
  595. </ul>
  596. <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>
  597. &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>
  598. &lt;int&gt; = &lt;D/DT&gt;.toordinal() <span class="hljs-comment"># Days since Christ, ignoring time and tz.</span>
  599. &lt;float&gt; = &lt;DTn&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTn in local time.</span>
  600. &lt;float&gt; = &lt;DTa&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTa.</span>
  601. </code></pre></div>
  602. <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
  603. <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>)
  604. <span class="hljs-meta">&gt;&gt;&gt; </span>dt.strftime(<span class="hljs-string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)
  605. <span class="hljs-string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span>
  606. </code></pre></div>
  607. <ul>
  608. <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>
  609. <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>
  610. </ul>
  611. <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"># Result can fall into missing hour.</span>
  612. &lt;TD&gt; = &lt;D/DT&gt; - &lt;D/DT&gt; <span class="hljs-comment"># Ignores time jumps if they share non tzlocal tz.</span>
  613. &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>
  614. </code></pre></div>
  615. <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>
  616. &lt;function&gt;(&lt;keyword_args&gt;) <span class="hljs-comment"># f(x=0, y=0)</span>
  617. &lt;function&gt;(&lt;positional_args&gt;, &lt;keyword_args&gt;) <span class="hljs-comment"># f(0, y=0)</span>
  618. </code></pre></div></div>
  619. <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>
  620. <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>
  621. <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>
  622. </code></pre></div>
  623. <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>)
  624. 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>}
  625. func(*args, **kwargs)
  626. </code></pre></div></div>
  627. <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>)
  628. </code></pre></div>
  629. <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>
  630. <span class="hljs-keyword">return</span> sum(a)
  631. </code></pre></div>
  632. <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>)
  633. <span class="hljs-number">6</span>
  634. </code></pre>
  635. <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>
  636. <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>
  637. <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>
  638. <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>
  639. </code></pre></div>
  640. <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>
  641. <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>
  642. <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>
  643. <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>
  644. </code></pre>
  645. <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>
  646. <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>
  647. <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>
  648. </code></pre>
  649. <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>
  650. <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>
  651. <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>
  652. <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>
  653. </code></pre>
  654. <div><h3 id="otheruses">Other Uses</h3><pre><code class="python language-python hljs">&lt;list&gt; = [*&lt;collection&gt; [, ...]]
  655. &lt;set&gt; = {*&lt;collection&gt; [, ...]}
  656. &lt;tuple&gt; = (*&lt;collection&gt;, [...])
  657. &lt;dict&gt; = {**&lt;dict&gt; [, ...]}
  658. </code></pre></div>
  659. <pre><code class="python language-python hljs">head, *body, tail = &lt;collection&gt;
  660. </code></pre>
  661. <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;
  662. &lt;function&gt; = <span class="hljs-keyword">lambda</span> &lt;argument_1&gt;, &lt;argument_2&gt;: &lt;return_value&gt;
  663. </code></pre></div></div>
  664. <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>
  665. &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>
  666. &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>
  667. &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>
  668. </code></pre></div>
  669. <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>)]
  670. </code></pre>
  671. <div><h4 id="isthesameas-1">Is the same as:</h4><pre><code class="python language-python hljs">out = []
  672. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  673. <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  674. out.append(i+j)
  675. </code></pre></div>
  676. <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
  677. &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>
  678. &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>
  679. &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>
  680. </code></pre></div>
  681. <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>
  682. &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>
  683. </code></pre></div>
  684. <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;
  685. </code></pre></div>
  686. <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>)]
  687. [<span class="hljs-string">'zero'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  688. </code></pre>
  689. <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
  690. Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  691. point = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
  692. </code></pre></div>
  693. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  694. Direction = Enum(<span class="hljs-string">'Direction'</span>, <span class="hljs-string">'n e s w'</span>)
  695. direction = Direction.n
  696. </code></pre>
  697. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  698. Creature = make_dataclass(<span class="hljs-string">'Creature'</span>, [<span class="hljs-string">'location'</span>, <span class="hljs-string">'direction'</span>])
  699. creature = Creature(Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), Direction.n)
  700. </code></pre>
  701. <div><h2 id="closure"><a href="#closure" name="closure">#</a>Closure</h2><p><strong>We have a closure in Python when:</strong></p><ul>
  702. <li><strong>A nested function references a value of its enclosing function and then</strong></li>
  703. <li><strong>the enclosing function returns the nested function.</strong></li>
  704. </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>
  705. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(b)</span>:</span>
  706. <span class="hljs-keyword">return</span> a * b
  707. <span class="hljs-keyword">return</span> out
  708. </code></pre></div>
  709. <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>)
  710. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  711. <span class="hljs-number">30</span>
  712. </code></pre>
  713. <ul>
  714. <li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
  715. <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>
  716. </ul>
  717. <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
  718. &lt;function&gt; = partial(&lt;function&gt; [, &lt;arg_1&gt;, &lt;arg_2&gt;, ...])
  719. </code></pre></div>
  720. <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
  721. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3 = partial(op.mul, <span class="hljs-number">3</span>)
  722. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  723. <span class="hljs-number">30</span>
  724. </code></pre>
  725. <ul>
  726. <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>
  727. <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>
  728. </ul>
  729. <div><h3 id="nonlocal">Nonlocal</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>
  730. i = <span class="hljs-number">0</span>
  731. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">()</span>:</span>
  732. <span class="hljs-keyword">nonlocal</span> i
  733. i += <span class="hljs-number">1</span>
  734. <span class="hljs-keyword">return</span> i
  735. <span class="hljs-keyword">return</span> out
  736. </code></pre></div>
  737. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = get_counter()
  738. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  739. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  740. </code></pre>
  741. <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>
  742. <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>
  743. ...
  744. </code></pre></div>
  745. <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
  746. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(func)</span>:</span>
  747. <span class="hljs-meta"> @wraps(func)</span>
  748. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  749. print(func.__name__)
  750. <span class="hljs-keyword">return</span> func(*args, **kwargs)
  751. <span class="hljs-keyword">return</span> out
  752. <span class="hljs-meta">@debug</span>
  753. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  754. <span class="hljs-keyword">return</span> x + y
  755. </code></pre></div>
  756. <ul>
  757. <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>
  758. <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>
  759. </ul>
  760. <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
  761. <span class="hljs-meta">@lru_cache(maxsize=None)</span>
  762. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>
  763. <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>)
  764. </code></pre></div>
  765. <ul>
  766. <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>
  767. </ul>
  768. <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
  769. <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>
  770. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>
  771. <span class="hljs-meta"> @wraps(func)</span>
  772. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  773. result = func(*args, **kwargs)
  774. print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>)
  775. <span class="hljs-keyword">return</span> result
  776. <span class="hljs-keyword">return</span> out
  777. <span class="hljs-keyword">return</span> decorator
  778. <span class="hljs-meta">@debug(print_result=True)</span>
  779. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  780. <span class="hljs-keyword">return</span> x + y
  781. </code></pre></div>
  782. <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>
  783. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  784. self.a = a
  785. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span><span class="hljs-params">(self)</span>:</span>
  786. class_name = self.__class__.__name__
  787. <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>
  788. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
  789. <span class="hljs-keyword">return</span> str(self.a)
  790. <span class="hljs-meta"> @classmethod</span>
  791. <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>
  792. <span class="hljs-keyword">return</span> cls.__name__
  793. </code></pre></div>
  794. <ul>
  795. <li><strong>Return value of repr() should be unambiguous and of str() readable.</strong></li>
  796. <li><strong>If only repr() is defined, it will also be used for str().</strong></li>
  797. </ul>
  798. <div><h4 id="strusecases">Str() use cases:</h4><pre><code class="python language-python hljs">print(&lt;el&gt;)
  799. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;}</span>'</span>)
  800. <span class="hljs-keyword">raise</span> Exception(&lt;el&gt;)
  801. loguru.logger.debug(&lt;el&gt;)
  802. csv.writer(&lt;file&gt;).writerow([&lt;el&gt;])
  803. </code></pre></div>
  804. <div><h4 id="reprusecases">Repr() use cases:</h4><pre><code class="python language-python hljs">print([&lt;el&gt;])
  805. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;!r}</span>'</span>)
  806. <span class="hljs-meta">&gt;&gt;&gt; </span>&lt;el&gt;
  807. loguru.logger.exception()
  808. Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span class="hljs-string">'a'</span>]); print(Z(&lt;el&gt;))
  809. </code></pre></div>
  810. <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>
  811. <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>
  812. self.a = a
  813. </code></pre></div>
  814. <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>
  815. <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>
  816. self.name = name
  817. self.age = age
  818. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Person)</span>:</span>
  819. <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>
  820. super().__init__(name, age)
  821. self.staff_num = staff_num
  822. </code></pre></div>
  823. <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>
  824. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>:</span> <span class="hljs-keyword">pass</span>
  825. <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>
  826. </code></pre></div>
  827. <p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong></p>
  828. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>C.mro()
  829. [&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;]
  830. </span></code></pre>
  831. <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>
  832. <span class="hljs-meta"> @property</span>
  833. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  834. <span class="hljs-keyword">return</span> self._a
  835. <span class="hljs-meta"> @a.setter</span>
  836. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self, value)</span>:</span>
  837. self._a = value
  838. </code></pre></div>
  839. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>el = MyClass()
  840. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a = <span class="hljs-number">123</span>
  841. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a
  842. <span class="hljs-number">123</span>
  843. </code></pre>
  844. <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
  845. <span class="hljs-meta">@dataclass(order=False, frozen=False)</span>
  846. <span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>
  847. &lt;attr_name_1&gt;: &lt;type&gt;
  848. &lt;attr_name_2&gt;: &lt;type&gt; = &lt;default_value&gt;
  849. &lt;attr_name_3&gt;: list/dict/set = field(default_factory=list/dict/set)
  850. </code></pre></div>
  851. <ul>
  852. <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>
  853. <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>
  854. <li><strong>Default_factory can be any <a href="#callable">callable</a>.</strong></li>
  855. </ul>
  856. <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
  857. &lt;class&gt; = make_dataclass(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;coll_of_attribute_names&gt;)
  858. &lt;class&gt; = make_dataclass(<span class="hljs-string">'&lt;class_name&gt;'</span>, &lt;coll_of_tuples&gt;)
  859. &lt;tuple&gt; = (<span class="hljs-string">'&lt;attr_name&gt;'</span>, &lt;type&gt; [, &lt;default_value&gt;])</code></code></pre></div>
  860. <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>
  861. __slots__ = [<span class="hljs-string">'a'</span>]
  862. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  863. self.a = <span class="hljs-number">1</span>
  864. </code></pre></div>
  865. <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
  866. &lt;object&gt; = copy(&lt;object&gt;)
  867. &lt;object&gt; = deepcopy(&lt;object&gt;)
  868. </code></pre></div>
  869. <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>
  870. <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>
  871. <li><strong>That means all objects compare not equal by default.</strong></li>
  872. <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>
  873. </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>
  874. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  875. self.a = a
  876. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  877. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  878. <span class="hljs-keyword">return</span> self.a == other.a
  879. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  880. </code></pre></div></div>
  881. <div><h3 id="hashable">Hashable</h3><ul>
  882. <li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
  883. <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>
  884. <li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
  885. </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>
  886. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  887. self._a = copy.deepcopy(a)
  888. <span class="hljs-meta"> @property</span>
  889. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  890. <span class="hljs-keyword">return</span> self._a
  891. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  892. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  893. <span class="hljs-keyword">return</span> self.a == other.a
  894. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  895. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__hash__</span><span class="hljs-params">(self)</span>:</span>
  896. <span class="hljs-keyword">return</span> hash(self.a)
  897. </code></pre></div>
  898. <div><h3 id="sortable">Sortable</h3><ul>
  899. <li><strong>With total_ordering decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.</strong></li>
  900. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> total_ordering
  901. <span class="hljs-meta">@total_ordering</span>
  902. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySortable</span>:</span>
  903. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  904. self.a = a
  905. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  906. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  907. <span class="hljs-keyword">return</span> self.a == other.a
  908. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  909. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__lt__</span><span class="hljs-params">(self, other)</span>:</span>
  910. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  911. <span class="hljs-keyword">return</span> self.a &lt; other.a
  912. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  913. </code></pre></div>
  914. <div><h3 id="iterator-1">Iterator</h3><ul>
  915. <li><strong>Any object that defines methods next() and iter() is an iterator.</strong></li>
  916. <li><strong>Next() should return next item or raise StopIteration.</strong></li>
  917. <li><strong>Iter() should return 'self'.</strong></li>
  918. </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>
  919. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  920. self.i = <span class="hljs-number">0</span>
  921. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__next__</span><span class="hljs-params">(self)</span>:</span>
  922. self.i += <span class="hljs-number">1</span>
  923. <span class="hljs-keyword">return</span> self.i
  924. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  925. <span class="hljs-keyword">return</span> self
  926. </code></pre></div>
  927. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  928. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  929. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  930. </code></pre>
  931. <div><h4 id="pythonhasmanydifferentiteratorobjects">Python has many different iterator objects:</h4><ul>
  932. <li><strong>Iterators returned by the <a href="#iterator">iter()</a> function, such as list_iterator and set_iterator.</strong></li>
  933. <li><strong>Objects returned by the <a href="#itertools">itertools</a> module, such as count, repeat and cycle.</strong></li>
  934. <li><strong>Generators returned by the <a href="#generator">generator functions</a> and <a href="#comprehension">generator expressions</a>.</strong></li>
  935. <li><strong>File objects returned by the <a href="#open">open()</a> function, etc.</strong></li>
  936. </ul><div><h3 id="callable">Callable</h3><ul>
  937. <li><strong>All functions and classes have a call() method, hence are callable.</strong></li>
  938. <li><strong>When this cheatsheet uses <code class="python hljs"><span class="hljs-string">'&lt;function&gt;'</span></code> for an argument, it actually means <code class="python hljs"><span class="hljs-string">'&lt;callable&gt;'</span></code>.</strong></li>
  939. </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>
  940. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  941. self.i = <span class="hljs-number">0</span>
  942. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self)</span>:</span>
  943. self.i += <span class="hljs-number">1</span>
  944. <span class="hljs-keyword">return</span> self.i
  945. </code></pre></div></div>
  946. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  947. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  948. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  949. </code></pre>
  950. <div><h3 id="contextmanager">Context Manager</h3><ul>
  951. <li><strong>Enter() should lock the resources and return an object.</strong></li>
  952. <li><strong>Exit() should release the resources.</strong></li>
  953. </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 class="hljs-params">()</span>:</span>
  954. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, filename)</span>:</span>
  955. self.filename = filename
  956. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span><span class="hljs-params">(self)</span>:</span>
  957. self.file = open(self.filename)
  958. <span class="hljs-keyword">return</span> self.file
  959. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, *args)</span>:</span>
  960. self.file.close()
  961. </code></pre></div>
  962. <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:
  963. <span class="hljs-meta">... </span> file.write(<span class="hljs-string">'Hello World!'</span>)
  964. <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:
  965. <span class="hljs-meta">... </span> print(file.read())
  966. Hello World!
  967. </code></pre>
  968. <div><h2 id="iterableducktypes"><a href="#iterableducktypes" name="iterableducktypes">#</a>Iterable Duck Types</h2><div><h3 id="iterable">Iterable</h3><ul>
  969. <li><strong>Only required method is iter(). It should return an iterator of object's items.</strong></li>
  970. <li><strong>Contains() automatically works on any object that has iter() defined.</strong></li>
  971. </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>
  972. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  973. self.a = a
  974. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  975. <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> self.a:
  976. <span class="hljs-keyword">yield</span> el
  977. </code></pre></div></div>
  978. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>z = MyIterable([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
  979. <span class="hljs-meta">&gt;&gt;&gt; </span>iter(z)
  980. &lt;generator object MyIterable.__iter__&gt;
  981. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">1</span> <span class="hljs-keyword">in</span> z
  982. <span class="hljs-keyword">True</span>
  983. </code></pre>
  984. <div><h3 id="collection">Collection</h3><ul>
  985. <li><strong>Only required methods are iter() and len().</strong></li>
  986. <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>
  987. <li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.</strong></li>
  988. </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>
  989. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  990. self.a = a
  991. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  992. <span class="hljs-keyword">return</span> iter(self.a)
  993. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  994. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  995. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  996. <span class="hljs-keyword">return</span> len(self.a)
  997. </code></pre></div>
  998. <div><h3 id="sequence">Sequence</h3><ul>
  999. <li><strong>Only required methods are len() and getitem().</strong></li>
  1000. <li><strong>Getitem() should return an item at index or raise IndexError.</strong></li>
  1001. <li><strong>Iter() and contains() automatically work on any object that has getitem() defined.</strong></li>
  1002. <li><strong>Reversed() automatically works on any object that has getitem() and len() defined.</strong></li>
  1003. </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>
  1004. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1005. self.a = a
  1006. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  1007. <span class="hljs-keyword">return</span> iter(self.a)
  1008. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  1009. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  1010. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  1011. <span class="hljs-keyword">return</span> len(self.a)
  1012. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  1013. <span class="hljs-keyword">return</span> self.a[i]
  1014. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__reversed__</span><span class="hljs-params">(self)</span>:</span>
  1015. <span class="hljs-keyword">return</span> reversed(self.a)
  1016. </code></pre></div>
  1017. <div><h3 id="collectionsabcsequence">Collections.abc.Sequence</h3><ul>
  1018. <li><strong>It's a richer interface than the basic sequence.</strong></li>
  1019. <li><strong>Extending it generates iter(), contains(), reversed(), index(), and count().</strong></li>
  1020. <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, collections.abc.Sequence)'</span></code> would return False even if MySequence had all the methods defined.</strong></li>
  1021. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyAbcSequence</span><span class="hljs-params">(collections.abc.Sequence)</span>:</span>
  1022. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1023. self.a = 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. </code></pre></div>
  1029. <div><h4 id="tableofrequiredandautomaticallyavailablespecialmethods">Table of required and automatically available special methods:</h4><pre><code class="text language-text">+------------+------------+------------+------------+--------------+
  1030. | | Iterable | Collection | Sequence | abc.Sequence |
  1031. +------------+------------+------------+------------+--------------+
  1032. | iter() | REQ | REQ | yes | yes |
  1033. | contains() | yes | yes | yes | yes |
  1034. | len() | | REQ | REQ | REQ |
  1035. | getitem() | | | REQ | REQ |
  1036. | reversed() | | | yes | yes |
  1037. | index() | | | | yes |
  1038. | count() | | | | yes |
  1039. +------------+------------+------------+------------+--------------+
  1040. </code></pre></div>
  1041. <ul>
  1042. <li><strong>Other ABCs that generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.</strong></li>
  1043. <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>
  1044. </ul>
  1045. <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
  1046. <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>
  1047. &lt;member_name_1&gt; = &lt;value_1&gt;
  1048. &lt;member_name_2&gt; = &lt;value_2_a&gt;, &lt;value_2_b&gt;
  1049. &lt;member_name_3&gt; = auto()
  1050. </code></pre></div>
  1051. <ul>
  1052. <li><strong>If there are no numeric values before auto(), it returns 1.</strong></li>
  1053. <li><strong>Otherwise it returns an increment of the last numeric value.</strong></li>
  1054. </ul>
  1055. <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>
  1056. &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>
  1057. &lt;member&gt; = &lt;enum&gt;(&lt;value&gt;) <span class="hljs-comment"># Returns a member or raises ValueError.</span>
  1058. name = &lt;member&gt;.name
  1059. value = &lt;member&gt;.value
  1060. </code></pre>
  1061. <pre><code class="python language-python hljs">list_of_members = list(&lt;enum&gt;)
  1062. member_names = [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1063. member_values = [a.value <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1064. random_member = random.choice(list(&lt;enum&gt;))
  1065. </code></pre>
  1066. <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>
  1067. members = list(member.__class__)
  1068. index = (members.index(member) + <span class="hljs-number">1</span>) % len(members)
  1069. <span class="hljs-keyword">return</span> members[index]
  1070. </code></pre>
  1071. <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'</span>, <span class="hljs-string">'knife'</span>, <span class="hljs-string">'spoon'</span>])
  1072. Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, <span class="hljs-string">'fork knife spoon'</span>)
  1073. 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>})
  1074. </code></pre></div>
  1075. <div><h4 id="functionscannotbevaluessotheymustbewrapped">Functions can not 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
  1076. 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),
  1077. <span class="hljs-string">'OR'</span> : partial(<span class="hljs-keyword">lambda</span> l, r: l <span class="hljs-keyword">or</span> r)})
  1078. </code></pre></div>
  1079. <ul>
  1080. <li><strong>Another solution in this particular case, is to use <code class="python hljs"><span class="hljs-string">'and_'</span></code> and <code class="python hljs"><span class="hljs-string">'or_'</span></code> functions from module <a href="#operator">operator</a>.</strong></li>
  1081. </ul>
  1082. <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>:
  1083. &lt;code&gt;
  1084. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1085. &lt;code&gt;
  1086. </code></pre></div></div>
  1087. <div><h3 id="complexexample">Complex Example</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">try</span>:
  1088. &lt;code_1&gt;
  1089. <span class="hljs-keyword">except</span> &lt;exception_a&gt;:
  1090. &lt;code_2_a&gt;
  1091. <span class="hljs-keyword">except</span> &lt;exception_b&gt;:
  1092. &lt;code_2_b&gt;
  1093. <span class="hljs-keyword">else</span>:
  1094. &lt;code_2_c&gt;
  1095. <span class="hljs-keyword">finally</span>:
  1096. &lt;code_3&gt;
  1097. </code></pre></div>
  1098. <div><h3 id="catchingexceptions">Catching Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">except</span> &lt;exception&gt;:
  1099. <span class="hljs-keyword">except</span> &lt;exception&gt; <span class="hljs-keyword">as</span> &lt;name&gt;:
  1100. <span class="hljs-keyword">except</span> (&lt;exception&gt;, ...):
  1101. <span class="hljs-keyword">except</span> (&lt;exception&gt;, ...) <span class="hljs-keyword">as</span> &lt;name&gt;:
  1102. </code></pre></div>
  1103. <ul>
  1104. <li><strong>Also catches subclasses of the exception.</strong></li>
  1105. </ul>
  1106. <div><h3 id="raisingexceptions">Raising Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> &lt;exception&gt;
  1107. <span class="hljs-keyword">raise</span> &lt;exception&gt;()
  1108. <span class="hljs-keyword">raise</span> &lt;exception&gt;(&lt;el&gt;)
  1109. <span class="hljs-keyword">raise</span> &lt;exception&gt;(&lt;el&gt;, ...)
  1110. </code></pre></div>
  1111. <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;:
  1112. &lt;code&gt;
  1113. <span class="hljs-keyword">raise</span>
  1114. </code></pre></div>
  1115. <div><h4 id="usefulbuiltinexceptions">Useful built-in exceptions:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">'Argument is of right type but inappropriate value!'</span>)
  1116. <span class="hljs-keyword">raise</span> TypeError(<span class="hljs-string">'Argument is of wrong type!'</span>)
  1117. <span class="hljs-keyword">raise</span> RuntimeError(<span class="hljs-string">'None of above!'</span>)
  1118. </code></pre></div>
  1119. <div><h3 id="commonbuiltinexceptions">Common Built-in Exceptions</h3><pre><code class="text language-text">BaseException
  1120. +-- SystemExit # Raised by the sys.exit() function.
  1121. +-- KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
  1122. +-- Exception # User-defined exceptions should be derived from this class.
  1123. +-- StopIteration # Raised by next() when run on an empty iterator.
  1124. +-- ArithmeticError # Base class for arithmetic errors.
  1125. | +-- ZeroDivisionError # Raised when dividing by zero.
  1126. +-- AttributeError # Raised when an attribute is missing.
  1127. +-- EOFError # Raised by input() when it hits end-of-file condition.
  1128. +-- LookupError # Raised when a look-up on a sequence or dict fails.
  1129. | +-- IndexError # Raised when a sequence index is out of range.
  1130. | +-- KeyError # Raised when a dictionary key is not found.
  1131. +-- NameError # Raised when a variable name is not found.
  1132. +-- OSError # Failures such as “file not found” or “disk full”.
  1133. | +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
  1134. +-- RuntimeError # Raised by errors that don't fall in other categories.
  1135. | +-- RecursionError # Raised when the the maximum recursion depth is exceeded.
  1136. +-- TypeError # Raised when an argument is of wrong type.
  1137. +-- ValueError # When an argument is of right type but inappropriate value.
  1138. +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
  1139. </code></pre></div>
  1140. <div><h4 id="collectionsandtheirexceptions">Collections and their exceptions:</h4><pre><code class="text language-text">+-----------+------------+------------+------------+
  1141. | | list | dict | set |
  1142. +-----------+------------+------------+------------+
  1143. | getitem() | IndexError | KeyError | |
  1144. | pop() | IndexError | KeyError | KeyError |
  1145. | remove() | ValueError | | KeyError |
  1146. | index() | ValueError | | |
  1147. +-----------+------------+------------+------------+
  1148. </code></pre></div>
  1149. <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>
  1150. <span class="hljs-keyword">pass</span>
  1151. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyInputError</span><span class="hljs-params">(MyError)</span>:</span>
  1152. <span class="hljs-keyword">pass</span>
  1153. </code></pre></div>
  1154. <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>)
  1155. </code></pre></div>
  1156. <ul>
  1157. <li><strong>Use <code class="python hljs"><span class="hljs-string">'file=sys.stderr'</span></code> for errors.</strong></li>
  1158. <li><strong>Use <code class="python hljs"><span class="hljs-string">'flush=True'</span></code> to forcibly flush the stream.</strong></li>
  1159. </ul>
  1160. <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
  1161. pprint(&lt;collection&gt;, width=<span class="hljs-number">80</span>, depth=<span class="hljs-keyword">None</span>)
  1162. </code></pre></div>
  1163. <ul>
  1164. <li><strong>Levels deeper than 'depth' get replaced by '…'.</strong></li>
  1165. </ul>
  1166. <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>)
  1167. </code></pre></div>
  1168. <ul>
  1169. <li><strong>Trailing newline gets stripped.</strong></li>
  1170. <li><strong>Prompt string is printed to the standard output before reading input.</strong></li>
  1171. <li><strong>Raises EOFError when user hits EOF or input stream gets exhausted.</strong></li>
  1172. </ul>
  1173. <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
  1174. script_name = sys.argv[<span class="hljs-number">0</span>]
  1175. arguments = sys.argv[<span class="hljs-number">1</span>:]
  1176. </code></pre></div>
  1177. <div><h3 id="argparse">Argparse</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> argparse <span class="hljs-keyword">import</span> ArgumentParser, FileType
  1178. p = ArgumentParser(description=&lt;str&gt;)
  1179. 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>
  1180. 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>
  1181. 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>
  1182. 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>
  1183. 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>
  1184. args = p.parse_args() <span class="hljs-comment"># Exits on error.</span>
  1185. value = args.&lt;name&gt;
  1186. </code></pre></div>
  1187. <ul>
  1188. <li><strong>Use <code class="python hljs"><span class="hljs-string">'help=&lt;str&gt;'</span></code> to set argument description.</strong></li>
  1189. <li><strong>Use <code class="python hljs"><span class="hljs-string">'default=&lt;el&gt;'</span></code> to set the default value.</strong></li>
  1190. <li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files.</strong></li>
  1191. </ul>
  1192. <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>)
  1193. </code></pre></div>
  1194. <ul>
  1195. <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>
  1196. <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>
  1197. <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>
  1198. </ul>
  1199. <div><h3 id="modes">Modes</h3><ul>
  1200. <li><strong><code class="python hljs"><span class="hljs-string">'r'</span></code> - Read (default).</strong></li>
  1201. <li><strong><code class="python hljs"><span class="hljs-string">'w'</span></code> - Write (truncate).</strong></li>
  1202. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - Write or fail if the file already exists.</strong></li>
  1203. <li><strong><code class="python hljs"><span class="hljs-string">'a'</span></code> - Append.</strong></li>
  1204. <li><strong><code class="python hljs"><span class="hljs-string">'w+'</span></code> - Read and write (truncate).</strong></li>
  1205. <li><strong><code class="python hljs"><span class="hljs-string">'r+'</span></code> - Read and write from the start.</strong></li>
  1206. <li><strong><code class="python hljs"><span class="hljs-string">'a+'</span></code> - Read and write from the end.</strong></li>
  1207. <li><strong><code class="python hljs"><span class="hljs-string">'t'</span></code> - Text mode (default).</strong></li>
  1208. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - Binary mode.</strong></li>
  1209. </ul><div><h3 id="exceptions-1">Exceptions</h3><ul>
  1210. <li><strong><code class="python hljs"><span class="hljs-string">'FileNotFoundError'</span></code> can be risen 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>
  1211. <li><strong><code class="python hljs"><span class="hljs-string">'FileExistsError'</span></code> can be risen when writing with <code class="python hljs"><span class="hljs-string">'x'</span></code>.</strong></li>
  1212. <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 risen by any.</strong></li>
  1213. <li><strong><code class="python hljs"><span class="hljs-string">'OSError'</span></code> is the parent class of all listed exceptions.</strong></li>
  1214. </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>
  1215. &lt;file&gt;.seek(offset) <span class="hljs-comment"># Moves 'offset' chars/bytes from the start.</span>
  1216. &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>
  1217. &lt;bin_file&gt;.seek(±offset, &lt;anchor&gt;) <span class="hljs-comment"># Anchor: 0 start, 1 current pos., 2 end.</span>
  1218. </code></pre></div></div></div>
  1219. <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>
  1220. &lt;str/bytes&gt; = &lt;file&gt;.readline() <span class="hljs-comment"># Returns a line or empty string on EOF.</span>
  1221. &lt;list&gt; = &lt;file&gt;.readlines() <span class="hljs-comment"># Returns a list of remaining lines.</span>
  1222. &lt;str/bytes&gt; = next(&lt;file&gt;) <span class="hljs-comment"># Returns a line using buffer. Do not mix.</span>
  1223. </code></pre>
  1224. <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>
  1225. &lt;file&gt;.writelines(&lt;collection&gt;) <span class="hljs-comment"># Writes a coll. of strings or bytes objects.</span>
  1226. &lt;file&gt;.flush() <span class="hljs-comment"># Flushes write buffer.</span>
  1227. </code></pre>
  1228. <ul>
  1229. <li><strong>Methods do not add or strip trailing newlines, even writelines().</strong></li>
  1230. </ul>
  1231. <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>
  1232. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1233. <span class="hljs-keyword">return</span> file.readlines()
  1234. </code></pre></div>
  1235. <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>
  1236. <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:
  1237. file.write(text)
  1238. </code></pre></div>
  1239. <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
  1240. <span class="hljs-keyword">from</span> glob <span class="hljs-keyword">import</span> glob
  1241. </code></pre></div>
  1242. <pre><code class="python language-python hljs">&lt;str&gt; = getcwd() <span class="hljs-comment"># Returns the current working directory.</span>
  1243. </code></pre>
  1244. <pre><code class="python language-python hljs">&lt;bool&gt; = path.exists(<span class="hljs-string">'&lt;path&gt;'</span>)
  1245. &lt;bool&gt; = path.isfile(<span class="hljs-string">'&lt;path&gt;'</span>)
  1246. &lt;bool&gt; = path.isdir(<span class="hljs-string">'&lt;path&gt;'</span>)
  1247. </code></pre>
  1248. <pre><code class="python language-python hljs">&lt;list&gt; = listdir(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># List of filenames located at path.</span>
  1249. &lt;list&gt; = glob(<span class="hljs-string">'&lt;pattern&gt;'</span>) <span class="hljs-comment"># Filenames matching the wildcard pattern.</span>
  1250. </code></pre>
  1251. <div><h3 id="pathlib">Pathlib</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path
  1252. </code></pre></div>
  1253. <pre><code class="python language-python hljs">cwd = Path()
  1254. &lt;Path&gt; = Path(<span class="hljs-string">'&lt;path&gt;'</span> [, <span class="hljs-string">'&lt;path&gt;'</span>, &lt;Path&gt;, ...])
  1255. &lt;Path&gt; = &lt;Path&gt; / <span class="hljs-string">'&lt;dir&gt;'</span> / <span class="hljs-string">'&lt;file&gt;'</span>
  1256. </code></pre>
  1257. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;Path&gt;.exists()
  1258. &lt;bool&gt; = &lt;Path&gt;.is_file()
  1259. &lt;bool&gt; = &lt;Path&gt;.is_dir()
  1260. </code></pre>
  1261. <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>
  1262. &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>
  1263. </code></pre>
  1264. <pre><code class="python language-python hljs">&lt;str&gt; = str(&lt;Path&gt;) <span class="hljs-comment"># Path as a string.</span>
  1265. &lt;str&gt; = &lt;Path&gt;.name <span class="hljs-comment"># Final component.</span>
  1266. &lt;str&gt; = &lt;Path&gt;.stem <span class="hljs-comment"># Final component without extension.</span>
  1267. &lt;str&gt; = &lt;Path&gt;.suffix <span class="hljs-comment"># Final component's extension.</span>
  1268. &lt;tup.&gt; = &lt;Path&gt;.parts <span class="hljs-comment"># All components as strings.</span>
  1269. </code></pre>
  1270. <pre><code class="python language-python hljs">&lt;Path&gt; = &lt;Path&gt;.resolve() <span class="hljs-comment"># Returns absolute path without symlinks.</span>
  1271. &lt;Path&gt; = &lt;Path&gt;.parent <span class="hljs-comment"># Returns path without final component.</span>
  1272. &lt;file&gt; = open(&lt;Path&gt;) <span class="hljs-comment"># Opens the file and returns a file object.</span>
  1273. </code></pre>
  1274. <div><h2 id="oscommands"><a href="#oscommands" name="oscommands">#</a>OS Commands</h2><div><h3 id="filesanddirectories">Files and Directories</h3><ul>
  1275. <li><strong>Paths can be either strings, Paths, or DirEntry objects.</strong></li>
  1276. <li><strong>Functions report OS related errors by raising either OSError or one of its <a href="#exceptions-1">subclasses</a>.</strong></li>
  1277. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os, shutil
  1278. </code></pre></div></div>
  1279. <pre><code class="python language-python hljs">os.chdir(&lt;path&gt;) <span class="hljs-comment"># Changes current working directory.</span>
  1280. os.mkdir(&lt;path&gt;, mode=<span class="hljs-number">0o777</span>) <span class="hljs-comment"># Creates a directory. Mode is in octal.</span>
  1281. </code></pre>
  1282. <pre><code class="python language-python hljs">shutil.copy(from, to) <span class="hljs-comment"># Copies the file.</span>
  1283. shutil.copytree(from, to) <span class="hljs-comment"># Copies the entire directory tree.</span>
  1284. </code></pre>
  1285. <pre><code class="python language-python hljs">os.rename(from, to) <span class="hljs-comment"># Renames the file or directory.</span>
  1286. os.replace(from, to) <span class="hljs-comment"># Same, but overwrites 'to' if it exists.</span>
  1287. </code></pre>
  1288. <pre><code class="python language-python hljs">os.remove(&lt;path&gt;) <span class="hljs-comment"># Deletes the file.</span>
  1289. os.rmdir(&lt;path&gt;) <span class="hljs-comment"># Deletes empty directory.</span>
  1290. shutil.rmtree(&lt;path&gt;) <span class="hljs-comment"># Deletes the entire directory tree.</span>
  1291. </code></pre>
  1292. <pre><code class="python language-python hljs">&lt;iter&gt; = os.scandir(path=<span class="hljs-string">'.'</span>) <span class="hljs-comment"># Returns os.DirEntry objects located at path.</span>
  1293. </code></pre>
  1294. <div><h4 id="direntry">DirEntry:</h4><pre><code class="python language-python hljs">&lt;bool&gt; = &lt;DirEntry&gt;.is_file()
  1295. &lt;bool&gt; = &lt;DirEntry&gt;.is_dir()
  1296. </code></pre></div>
  1297. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;DirEntry&gt;.path <span class="hljs-comment"># Path as a string.</span>
  1298. &lt;str&gt; = &lt;DirEntry&gt;.name <span class="hljs-comment"># Final component.</span>
  1299. </code></pre>
  1300. <pre><code class="python language-python hljs">&lt;Path&gt; = Path(&lt;DirEntry&gt;) <span class="hljs-comment"># Path object.</span>
  1301. &lt;file&gt; = open(&lt;DirEntry&gt;) <span class="hljs-comment"># File object.</span>
  1302. </code></pre>
  1303. <div><h3 id="shellcommands">Shell Commands</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os
  1304. &lt;str&gt; = os.popen(<span class="hljs-string">'&lt;shell_command&gt;'</span>).read()
  1305. </code></pre></div>
  1306. <div><h4 id="usingsubprocess">Using subprocess:</h4><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> subprocess, shlex
  1307. <span class="hljs-meta">&gt;&gt;&gt; </span>a = subprocess.run(shlex.split(<span class="hljs-string">'ls -a'</span>), stdout=subprocess.PIPE)
  1308. <span class="hljs-meta">&gt;&gt;&gt; </span>a.stdout
  1309. <span class="hljs-string">b'.\n..\nfile1.txt\nfile2.txt\n'</span>
  1310. <span class="hljs-meta">&gt;&gt;&gt; </span>a.returncode
  1311. <span class="hljs-number">0</span>
  1312. </code></pre></div>
  1313. <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
  1314. &lt;str&gt; = json.dumps(&lt;object&gt;, ensure_ascii=<span class="hljs-keyword">True</span>, indent=<span class="hljs-keyword">None</span>)
  1315. &lt;object&gt; = json.loads(&lt;str&gt;)
  1316. </code></pre></div>
  1317. <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>
  1318. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1319. <span class="hljs-keyword">return</span> json.load(file)
  1320. </code></pre></div>
  1321. <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>
  1322. <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:
  1323. json.dump(an_object, file, ensure_ascii=<span class="hljs-keyword">False</span>, indent=<span class="hljs-number">2</span>)
  1324. </code></pre></div>
  1325. <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
  1326. &lt;bytes&gt; = pickle.dumps(&lt;object&gt;)
  1327. &lt;object&gt; = pickle.loads(&lt;bytes&gt;)
  1328. </code></pre></div>
  1329. <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>
  1330. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1331. <span class="hljs-keyword">return</span> pickle.load(file)
  1332. </code></pre></div>
  1333. <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>
  1334. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1335. pickle.dump(an_object, file)
  1336. </code></pre></div>
  1337. <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
  1338. </code></pre></div>
  1339. <div><h3 id="read">Read</h3><pre><code class="python language-python hljs">&lt;reader&gt; = csv.reader(&lt;file&gt;, dialect=<span class="hljs-string">'excel'</span>, delimiter=<span class="hljs-string">','</span>)
  1340. &lt;list&gt; = next(&lt;reader&gt;) <span class="hljs-comment"># Returns next row as a list of strings.</span>
  1341. &lt;list&gt; = list(&lt;reader&gt;) <span class="hljs-comment"># Returns list of remaining rows.</span>
  1342. </code></pre></div>
  1343. <ul>
  1344. <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>
  1345. </ul>
  1346. <div><h3 id="write">Write</h3><pre><code class="python language-python hljs">&lt;writer&gt; = csv.writer(&lt;file&gt;, dialect=<span class="hljs-string">'excel'</span>, delimiter=<span class="hljs-string">','</span>)
  1347. &lt;writer&gt;.writerow(&lt;collection&gt;) <span class="hljs-comment"># Encodes objects using `str(&lt;el&gt;)`.</span>
  1348. &lt;writer&gt;.writerows(&lt;coll_of_coll&gt;) <span class="hljs-comment"># Appends multiple rows.</span>
  1349. </code></pre></div>
  1350. <ul>
  1351. <li><strong>File must be opened with <code class="python hljs"><span class="hljs-string">'newline=""'</span></code> argument, or an extra '\r' will be added on platforms that use '\r\n' linendings!</strong></li>
  1352. </ul>
  1353. <div><h3 id="parameters">Parameters</h3><ul>
  1354. <li><strong><code class="python hljs"><span class="hljs-string">'dialect'</span></code> - Master parameter that sets the default values.</strong></li>
  1355. <li><strong><code class="python hljs"><span class="hljs-string">'delimiter'</span></code> - A one-character string used to separate fields.</strong></li>
  1356. <li><strong><code class="python hljs"><span class="hljs-string">'quotechar'</span></code> - Character for quoting fields that contain special characters.</strong></li>
  1357. <li><strong><code class="python hljs"><span class="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields get doubled or escaped.</strong></li>
  1358. <li><strong><code class="python hljs"><span class="hljs-string">'skipinitialspace'</span></code> - Whether whitespace after delimiter gets stripped.</strong></li>
  1359. <li><strong><code class="python hljs"><span class="hljs-string">'lineterminator'</span></code> - How does writer terminate lines.</strong></li>
  1360. <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>
  1361. <li><strong><code class="python hljs"><span class="hljs-string">'escapechar'</span></code> - Character for escaping 'quotechar' if 'doublequote' is false.</strong></li>
  1362. </ul><div><h3 id="dialects">Dialects</h3><pre><code class="text language-text">+------------------+--------------+--------------+--------------+
  1363. | | excel | excel_tab | unix_dialect |
  1364. +------------------+--------------+--------------+--------------+
  1365. | delimiter | ',' | '\t' | ',' |
  1366. | quotechar | '"' | '"' | '"' |
  1367. | doublequote | True | True | True |
  1368. | skipinitialspace | False | False | False |
  1369. | lineterminator | '\r\n' | '\r\n' | '\n' |
  1370. | quoting | 0 | 0 | 1 |
  1371. | escapechar | None | None | None |
  1372. +------------------+--------------+--------------+--------------+
  1373. </code></pre></div></div>
  1374. <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>
  1375. <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:
  1376. <span class="hljs-keyword">return</span> list(csv.reader(file))
  1377. </code></pre></div>
  1378. <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>
  1379. <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:
  1380. writer = csv.writer(file)
  1381. writer.writerows(rows)
  1382. </code></pre></div>
  1383. <div><h2 id="sqlite"><a href="#sqlite" name="sqlite">#</a>SQLite</h2><p><strong>Server-less database engine that stores each database into 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
  1384. db = sqlite3.connect(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Also ':memory:'.</span>
  1385. ...
  1386. db.close()
  1387. </code></pre></div></div>
  1388. <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; = db.execute(<span class="hljs-string">'&lt;query&gt;'</span>) <span class="hljs-comment"># Can raise sqlite3.OperationalError.</span>
  1389. &lt;tuple&gt; = &lt;cursor&gt;.fetchone() <span class="hljs-comment"># Returns next row. Also next(&lt;cursor&gt;).</span>
  1390. &lt;list&gt; = &lt;cursor&gt;.fetchall() <span class="hljs-comment"># Returns remaining rows.</span>
  1391. </code></pre></div>
  1392. <div><h3 id="write-1">Write</h3><pre><code class="python language-python hljs">db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1393. db.commit()
  1394. </code></pre></div>
  1395. <div><h4 id="or">Or:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">with</span> db:
  1396. db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1397. </code></pre></div>
  1398. <div><h3 id="placeholders">Placeholders</h3><ul>
  1399. <li><strong>Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.</strong></li>
  1400. <li><strong>Bools will be stored and returned as ints and dates as <a href="#encode">ISO formatted strings</a>.</strong></li>
  1401. </ul><pre><code class="python language-python hljs">db.execute(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;list/tuple&gt;) <span class="hljs-comment"># Replaces '?'s in query with values.</span>
  1402. db.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>
  1403. db.executemany(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;coll_of_above&gt;) <span class="hljs-comment"># Runs execute() many times.</span>
  1404. </code></pre></div>
  1405. <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">'db.commit()'</span></code> is omitted!</strong></p><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>db = sqlite3.connect(<span class="hljs-string">'test.db'</span>)
  1406. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'create table t (a, b, c)'</span>)
  1407. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'insert into t values (1, 2, 3)'</span>)
  1408. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'select * from t'</span>).fetchall()
  1409. [(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)]
  1410. </code></pre></div>
  1411. <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>
  1412. <span class="hljs-keyword">from</span> mysql <span class="hljs-keyword">import</span> connector
  1413. db = connector.connect(host=&lt;str&gt;, user=&lt;str&gt;, password=&lt;str&gt;, database=&lt;str&gt;)
  1414. &lt;cursor&gt; = db.cursor()
  1415. &lt;cursor&gt;.execute(<span class="hljs-string">'&lt;query&gt;'</span>) <span class="hljs-comment"># Only cursor has execute method.</span>
  1416. &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>
  1417. &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>
  1418. </code></pre></div>
  1419. <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>
  1420. &lt;int&gt; = &lt;bytes&gt;[&lt;index&gt;] <span class="hljs-comment"># Returns int in range from 0 to 255.</span>
  1421. &lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;] <span class="hljs-comment"># Returns bytes even if it has only one element.</span>
  1422. &lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;) <span class="hljs-comment"># Joins elements using bytes object as separator.</span>
  1423. </code></pre></div>
  1424. <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>
  1425. &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>
  1426. &lt;bytes&gt; = &lt;int&gt;.to_bytes(n_bytes, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1427. &lt;bytes&gt; = bytes.fromhex(<span class="hljs-string">'&lt;hex&gt;'</span>)
  1428. </code></pre></div>
  1429. <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>
  1430. &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>
  1431. &lt;int&gt; = int.from_bytes(&lt;bytes&gt;, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1432. <span class="hljs-string">'&lt;hex&gt;'</span> = &lt;bytes&gt;.hex()
  1433. </code></pre></div>
  1434. <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>
  1435. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1436. <span class="hljs-keyword">return</span> file.read()
  1437. </code></pre></div>
  1438. <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>
  1439. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1440. file.write(bytes_obj)
  1441. </code></pre></div>
  1442. <div><h2 id="struct"><a href="#struct" name="struct">#</a>Struct</h2><ul>
  1443. <li><strong>Module that performs conversions between a sequence of numbers and a bytes object.</strong></li>
  1444. <li><strong>Machine’s native type sizes and byte order are used by default.</strong></li>
  1445. </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
  1446. &lt;bytes&gt; = pack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;num_1&gt; [, &lt;num_2&gt;, ...])
  1447. &lt;tuple&gt; = unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1448. &lt;tuples&gt; = iter_unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1449. </code></pre></div>
  1450. <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>)
  1451. <span class="hljs-string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>
  1452. <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>)
  1453. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  1454. </code></pre></div>
  1455. <div><h3 id="format-2">Format</h3></div><div><h4 id="forstandardsizesstartformatstringwith">For standard sizes start format string with:</h4><ul>
  1456. <li><strong><code class="python hljs"><span class="hljs-string">'='</span></code> - native byte order</strong></li>
  1457. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;'</span></code> - little-endian</strong></li>
  1458. <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>
  1459. </ul></div><div><h4 id="integertypesusecapitalletterforunsignedtypestandardsizesareinbrackets">Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:</h4><ul>
  1460. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - pad byte</strong></li>
  1461. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - char (1)</strong></li>
  1462. <li><strong><code class="python hljs"><span class="hljs-string">'h'</span></code> - short (2)</strong></li>
  1463. <li><strong><code class="python hljs"><span class="hljs-string">'i'</span></code> - int (4)</strong></li>
  1464. <li><strong><code class="python hljs"><span class="hljs-string">'l'</span></code> - long (4)</strong></li>
  1465. <li><strong><code class="python hljs"><span class="hljs-string">'q'</span></code> - long long (8)</strong></li>
  1466. </ul></div><div><h4 id="floatingpointtypes">Floating point types:</h4><ul>
  1467. <li><strong><code class="python hljs"><span class="hljs-string">'f'</span></code> - float (4)</strong></li>
  1468. <li><strong><code class="python hljs"><span class="hljs-string">'d'</span></code> - double (8)</strong></li>
  1469. </ul></div>
  1470. <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
  1471. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;collection&gt;) <span class="hljs-comment"># Array from coll. of numbers.</span>
  1472. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span>, &lt;bytes&gt;) <span class="hljs-comment"># Array from bytes object.</span>
  1473. &lt;bytes&gt; = bytes(&lt;array&gt;) <span class="hljs-comment"># Or: &lt;array&gt;.tobytes()</span>
  1474. </code></pre></div>
  1475. <div><h2 id="memoryview"><a href="#memoryview" name="memoryview">#</a>Memory View</h2><ul>
  1476. <li><strong>A sequence object that points to the memory of another object.</strong></li>
  1477. <li><strong>Each element can reference a single or multiple consecutive bytes, depending on format.</strong></li>
  1478. <li><strong>Order and number of elements can be changed with slicing.</strong></li>
  1479. </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>
  1480. &lt;real&gt; = &lt;mview&gt;[&lt;index&gt;] <span class="hljs-comment"># Returns an int or a float.</span>
  1481. &lt;mview&gt; = &lt;mview&gt;[&lt;slice&gt;] <span class="hljs-comment"># Mview with rearranged elements.</span>
  1482. &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>
  1483. &lt;mview&gt;.release() <span class="hljs-comment"># Releases the object's memory buffer.</span>
  1484. </code></pre></div>
  1485. <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"># Appends mview to the binary file.</span>
  1486. &lt;bytes&gt; = bytes(&lt;mview&gt;) <span class="hljs-comment"># Creates a new bytes object.</span>
  1487. &lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_mviews&gt;) <span class="hljs-comment"># Joins mviews using bytes object as sep.</span>
  1488. &lt;list&gt; = list(&lt;mview&gt;) <span class="hljs-comment"># Returns list of ints or floats.</span>
  1489. &lt;str&gt; = str(&lt;mview&gt;, <span class="hljs-string">'utf-8'</span>)
  1490. &lt;int&gt; = int.from_bytes(&lt;mview&gt;, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1491. <span class="hljs-string">'&lt;hex&gt;'</span> = &lt;mview&gt;.hex()
  1492. </code></pre></div>
  1493. <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
  1494. &lt;deque&gt; = deque(&lt;collection&gt;, maxlen=<span class="hljs-keyword">None</span>)
  1495. </code></pre></div>
  1496. <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>
  1497. &lt;el&gt; = &lt;deque&gt;.popleft() <span class="hljs-comment"># Raises IndexError if empty.</span>
  1498. &lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Collection gets reversed.</span>
  1499. &lt;deque&gt;.rotate(n=<span class="hljs-number">1</span>) <span class="hljs-comment"># Rotates elements to the right.</span>
  1500. </code></pre>
  1501. <div><h2 id="threading"><a href="#threading" name="threading">#</a>Threading</h2><ul>
  1502. <li><strong>CPython interpreter can only run a single thread at a time.</strong></li>
  1503. <li><strong>That is why using multiple threads won't result in a faster execution, unless there is an I/O operation in the thread.</strong></li>
  1504. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> threading <span class="hljs-keyword">import</span> Thread, RLock
  1505. </code></pre></div>
  1506. <div><h3 id="thread">Thread</h3><pre><code class="python language-python hljs">thread = Thread(target=&lt;function&gt;, args=(&lt;first_arg&gt;, ))
  1507. thread.start()
  1508. ...
  1509. &lt;bool&gt; = thread.is_alive() <span class="hljs-comment"># Checks if thread has finished executing.</span>
  1510. thread.join() <span class="hljs-comment"># Waits for thread to finish.</span>
  1511. </code></pre></div>
  1512. <ul>
  1513. <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>
  1514. <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>
  1515. </ul>
  1516. <div><h3 id="lock">Lock</h3><pre><code class="python language-python hljs">lock = RLock()
  1517. lock.acquire() <span class="hljs-comment"># Waits for lock to be available.</span>
  1518. ...
  1519. lock.release()
  1520. </code></pre></div>
  1521. <div><h4 id="or-1">Or:</h4><pre><code class="python language-python hljs">lock = RLock()
  1522. <span class="hljs-keyword">with</span> lock:
  1523. ...
  1524. </code></pre></div>
  1525. <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
  1526. <span class="hljs-keyword">with</span> ThreadPoolExecutor(max_workers=<span class="hljs-keyword">None</span>) <span class="hljs-keyword">as</span> executor:
  1527. &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>
  1528. &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>
  1529. &lt;Future&gt; = executor.submit(&lt;function&gt; [, &lt;arg_1&gt;, ...])
  1530. </code></pre></div>
  1531. <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>
  1532. &lt;obj&gt; = &lt;Future&gt;.result() <span class="hljs-comment"># Waits for thread to finish and returns result.</span>
  1533. </code></pre></div>
  1534. <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
  1535. &lt;Queue&gt; = Queue(maxsize=<span class="hljs-number">0</span>)
  1536. </code></pre></div>
  1537. <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>
  1538. &lt;Queue&gt;.put_nowait(&lt;el&gt;) <span class="hljs-comment"># Raises queue.Full exception if full.</span>
  1539. &lt;el&gt; = &lt;Queue&gt;.get() <span class="hljs-comment"># Blocks until queue stops being empty.</span>
  1540. &lt;el&gt; = &lt;Queue&gt;.get_nowait() <span class="hljs-comment"># Raises _queue.Empty exception if empty.</span>
  1541. </code></pre>
  1542. <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
  1543. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge
  1544. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> and_, or_, not_
  1545. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller
  1546. </code></pre></div>
  1547. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  1548. sorted_by_second = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>))
  1549. sorted_by_both = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>))
  1550. product_of_elems = functools.reduce(op.mul, &lt;collection&gt;)
  1551. 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_})
  1552. last_el = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;)
  1553. </code></pre>
  1554. <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 variables in current scope.</span>
  1555. &lt;dict&gt; = locals() <span class="hljs-comment"># Dict of local variables. Also vars().</span>
  1556. &lt;dict&gt; = globals() <span class="hljs-comment"># Dict of global variables.</span>
  1557. </code></pre></div></div>
  1558. <div><h3 id="attributes-1">Attributes</h3><pre><code class="python language-python hljs">&lt;dict&gt; = vars(&lt;object&gt;)
  1559. &lt;bool&gt; = hasattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1560. value = getattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1561. setattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>, value)
  1562. </code></pre></div>
  1563. <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
  1564. &lt;sig&gt; = signature(&lt;function&gt;)
  1565. no_of_params = len(&lt;sig&gt;.parameters)
  1566. param_names = list(&lt;sig&gt;.parameters.keys())
  1567. </code></pre></div>
  1568. <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>
  1569. <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>})
  1570. <span class="hljs-meta">&gt;&gt;&gt; </span>z = Z()
  1571. </code></pre>
  1572. <div><h3 id="metaclass">Meta Class</h3><p><strong>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>
  1573. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1574. <span class="hljs-keyword">return</span> type(name, parents, attrs)
  1575. </code></pre></div>
  1576. <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>
  1577. <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>
  1578. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1579. <span class="hljs-keyword">return</span> type.__new__(cls, name, parents, attrs)
  1580. </code></pre></div>
  1581. <ul>
  1582. <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>
  1583. <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>
  1584. <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>
  1585. <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>
  1586. </ul>
  1587. <div><h3 id="metaclassattribute">Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has a '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>
  1588. b = <span class="hljs-number">12345</span>
  1589. </code></pre></div>
  1590. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>MyClass.a, MyClass.b
  1591. (<span class="hljs-string">'abcde'</span>, <span class="hljs-number">12345</span>)
  1592. </code></pre>
  1593. <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>
  1594. type(MyMetaClass) == type <span class="hljs-comment"># MyMetaClass is an instance of type.</span>
  1595. </code></pre></div>
  1596. <pre><code class="text language-text">+-------------+-------------+
  1597. | Classes | Metaclasses |
  1598. +-------------+-------------|
  1599. | MyClass --&gt; MyMetaClass |
  1600. | | v |
  1601. | object -----&gt; type &lt;+ |
  1602. | | ^ +---+ |
  1603. | str ---------+ |
  1604. +-------------+-------------+
  1605. </code></pre>
  1606. <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>
  1607. MyMetaClass.__base__ == type <span class="hljs-comment"># MyMetaClass is a subclass of type.</span>
  1608. </code></pre></div>
  1609. <pre><code class="text language-text">+-------------+-------------+
  1610. | Classes | Metaclasses |
  1611. +-------------+-------------|
  1612. | MyClass | MyMetaClass |
  1613. | v | v |
  1614. | object &lt;----- type |
  1615. | ^ | |
  1616. | str | |
  1617. +-------------+-------------+
  1618. </code></pre>
  1619. <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
  1620. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'1 + 2'</span>)
  1621. <span class="hljs-number">3</span>
  1622. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'[1, 2, 3]'</span>)
  1623. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  1624. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'abs(1)'</span>)
  1625. ValueError: malformed node or string
  1626. </code></pre></div>
  1627. <div><h2 id="coroutine"><a href="#coroutine" name="coroutine">#</a>Coroutine</h2><ul>
  1628. <li><strong>Any function that contains a <code class="python hljs"><span class="hljs-string">'(yield)'</span></code> expression returns a coroutine.</strong></li>
  1629. <li><strong>Coroutines are similar to iterators, but data needs to be pulled out of an iterator by calling <code class="python hljs"><span class="hljs-string">'next(&lt;iter&gt;)'</span></code>, while we push data into the coroutine by calling <code class="python hljs"><span class="hljs-string">'&lt;coroutine&gt;.send(&lt;el&gt;)'</span></code>.</strong></li>
  1630. <li><strong>Coroutines provide more powerful data routing possibilities than iterators.</strong></li>
  1631. </ul><div><h3 id="helperdecorator">Helper Decorator</h3><ul>
  1632. <li><strong>All coroutines must first be "primed" by calling <code class="python hljs"><span class="hljs-string">'next(&lt;coroutine&gt;)'</span></code>.</strong></li>
  1633. <li><strong>Remembering to call next() is easy to forget.</strong></li>
  1634. <li><strong>Solved by wrapping coroutine functions with the following decorator:</strong></li>
  1635. </ul><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">coroutine</span><span class="hljs-params">(func)</span>:</span>
  1636. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  1637. cr = func(*args, **kwargs)
  1638. next(cr)
  1639. <span class="hljs-keyword">return</span> cr
  1640. <span class="hljs-keyword">return</span> out
  1641. </code></pre></div></div>
  1642. <div><h3 id="pipelineexample">Pipeline Example</h3><pre><code class="python language-python hljs"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">reader</span><span class="hljs-params">(target)</span>:</span>
  1643. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  1644. target.send(i)
  1645. target.close()
  1646. <span class="hljs-meta">@coroutine</span>
  1647. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">adder</span><span class="hljs-params">(target)</span>:</span>
  1648. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1649. value = (<span class="hljs-keyword">yield</span>)
  1650. target.send(value + <span class="hljs-number">100</span>)
  1651. <span class="hljs-meta">@coroutine</span>
  1652. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">printer</span><span class="hljs-params">()</span>:</span>
  1653. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1654. value = (<span class="hljs-keyword">yield</span>)
  1655. print(value, end=<span class="hljs-string">' '</span>)
  1656. </code></pre></div>
  1657. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>reader(adder(printer()))
  1658. <span class="hljs-number">100</span> <span class="hljs-number">101</span> <span class="hljs-number">102</span> <span class="hljs-number">103</span> <span class="hljs-number">104</span> <span class="hljs-number">105</span> <span class="hljs-number">106</span> <span class="hljs-number">107</span> <span class="hljs-number">108</span> <span class="hljs-number">109</span>
  1659. </code></pre>
  1660. <p><br></p>
  1661. <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>
  1662. <span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm
  1663. <span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep
  1664. <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>]):
  1665. sleep(<span class="hljs-number">0.2</span>)
  1666. </code></pre></div></div>
  1667. <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>
  1668. <span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot
  1669. pyplot.plot(&lt;y_data&gt; [, label=&lt;str&gt;])
  1670. pyplot.plot(&lt;x_data&gt;, &lt;y_data&gt;)
  1671. pyplot.legend() <span class="hljs-comment"># Adds a legend.</span>
  1672. pyplot.savefig(&lt;filename&gt;) <span class="hljs-comment"># Saves the figure.</span>
  1673. pyplot.show() <span class="hljs-comment"># Displays the figure.</span>
  1674. pyplot.clf() <span class="hljs-comment"># Clears the figure.</span>
  1675. </code></pre></div>
  1676. <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>
  1677. <span class="hljs-keyword">import</span> csv, tabulate
  1678. <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:
  1679. rows = csv.reader(file)
  1680. header = [a.title() <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> next(rows)]
  1681. table = tabulate.tabulate(rows, header)
  1682. print(table)
  1683. </code></pre></div></div>
  1684. <div><h2 id="curses"><a href="#curses" name="curses">#</a>Curses</h2><div><h4 id="clearstheterminalprintsamessageandwaitsforanesckeypress">Clears the terminal, prints a message and waits for an 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
  1685. <span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> KEY_UP, KEY_RIGHT, KEY_DOWN, KEY_LEFT
  1686. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1687. wrapper(draw)
  1688. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen)</span>:</span>
  1689. curs_set(<span class="hljs-number">0</span>) <span class="hljs-comment"># Makes cursor invisible.</span>
  1690. screen.nodelay(<span class="hljs-keyword">True</span>) <span class="hljs-comment"># Makes getch() non-blocking.</span>
  1691. screen.clear()
  1692. screen.addstr(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Press ESC to quit.'</span>)
  1693. <span class="hljs-keyword">while</span> screen.getch() != ascii.ESC:
  1694. <span class="hljs-keyword">pass</span>
  1695. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_border</span><span class="hljs-params">(screen)</span>:</span>
  1696. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1697. P = namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'x y'</span>)
  1698. height, width = screen.getmaxyx()
  1699. <span class="hljs-keyword">return</span> P(width - <span class="hljs-number">1</span>, height - <span class="hljs-number">1</span>)
  1700. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1701. main()
  1702. </code></pre></div></div>
  1703. <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>
  1704. <span class="hljs-keyword">from</span> loguru <span class="hljs-keyword">import</span> logger
  1705. </code></pre></div>
  1706. <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>
  1707. 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>
  1708. logger.&lt;level&gt;(<span class="hljs-string">'A logging message.'</span>)
  1709. </code></pre>
  1710. <ul>
  1711. <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>
  1712. </ul>
  1713. <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>:
  1714. ...
  1715. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1716. logger.exception(<span class="hljs-string">'An error happened.'</span>)
  1717. </code></pre></div>
  1718. <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;
  1719. </code></pre></div>
  1720. <ul>
  1721. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max file size in bytes.</strong></li>
  1722. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1723. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;time&gt;'</span></code> - Time of day.</strong></li>
  1724. <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>
  1725. </ul>
  1726. <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;
  1727. </code></pre></div>
  1728. <ul>
  1729. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max number of files.</strong></li>
  1730. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1731. <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>
  1732. </ul>
  1733. <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>
  1734. <span class="hljs-keyword">import</span> requests
  1735. <span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
  1736. url = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span>
  1737. html = requests.get(url).text
  1738. doc = BeautifulSoup(html, <span class="hljs-string">'html.parser'</span>)
  1739. table = doc.find(<span class="hljs-string">'table'</span>, class_=<span class="hljs-string">'infobox vevent'</span>)
  1740. rows = table.find_all(<span class="hljs-string">'tr'</span>)
  1741. link = rows[<span class="hljs-number">11</span>].find(<span class="hljs-string">'a'</span>)[<span class="hljs-string">'href'</span>]
  1742. ver = rows[<span class="hljs-number">6</span>].find(<span class="hljs-string">'div'</span>).text.split()[<span class="hljs-number">0</span>]
  1743. url_i = rows[<span class="hljs-number">0</span>].find(<span class="hljs-string">'img'</span>)[<span class="hljs-string">'src'</span>]
  1744. image = requests.get(<span class="hljs-string">f'https:<span class="hljs-subst">{url_i}</span>'</span>).content
  1745. <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:
  1746. file.write(image)
  1747. print(link, ver)
  1748. </code></pre></div></div>
  1749. <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>
  1750. <span class="hljs-keyword">from</span> bottle <span class="hljs-keyword">import</span> run, route, static_file, template, post, request, response
  1751. <span class="hljs-keyword">import</span> json
  1752. </code></pre></div>
  1753. <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>
  1754. 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>
  1755. </code></pre></div>
  1756. <div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/img/&lt;image&gt;')</span>
  1757. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_image</span><span class="hljs-params">(image)</span>:</span>
  1758. <span class="hljs-keyword">return</span> static_file(image, <span class="hljs-string">'img_dir/'</span>, mimetype=<span class="hljs-string">'image/png'</span>)
  1759. </code></pre></div>
  1760. <div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/&lt;sport&gt;')</span>
  1761. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_page</span><span class="hljs-params">(sport)</span>:</span>
  1762. <span class="hljs-keyword">return</span> template(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
  1763. </code></pre></div>
  1764. <div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@post('/odds/&lt;sport&gt;')</span>
  1765. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">odds_handler</span><span class="hljs-params">(sport)</span>:</span>
  1766. team = request.forms.get(<span class="hljs-string">'team'</span>)
  1767. home_odds, away_odds = <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>
  1768. response.headers[<span class="hljs-string">'Content-Type'</span>] = <span class="hljs-string">'application/json'</span>
  1769. response.headers[<span class="hljs-string">'Cache-Control'</span>] = <span class="hljs-string">'no-cache'</span>
  1770. <span class="hljs-keyword">return</span> json.dumps([team, home_odds, away_odds])
  1771. </code></pre></div>
  1772. <div><h4 id="test">Test:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests</span>
  1773. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests
  1774. <span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:8080/odds/football'</span>
  1775. <span class="hljs-meta">&gt;&gt;&gt; </span>data = {<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>}
  1776. <span class="hljs-meta">&gt;&gt;&gt; </span>response = requests.post(url, data=data)
  1777. <span class="hljs-meta">&gt;&gt;&gt; </span>response.json()
  1778. [<span class="hljs-string">'arsenal f.c.'</span>, <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>]
  1779. </code></pre></div>
  1780. <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
  1781. start_time = time() <span class="hljs-comment"># Seconds since the Epoch.</span>
  1782. ...
  1783. duration = time() - start_time
  1784. </code></pre></div></div>
  1785. <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
  1786. start_time = perf_counter() <span class="hljs-comment"># Seconds since restart.</span>
  1787. ...
  1788. duration = perf_counter() - start_time
  1789. </code></pre></div>
  1790. <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
  1791. <span class="hljs-meta">&gt;&gt;&gt; </span>timeit(<span class="hljs-string">'"-".join(str(a) for a in range(100))'</span>,
  1792. <span class="hljs-meta">... </span> number=<span class="hljs-number">10000</span>, globals=globals(), setup=<span class="hljs-string">'pass'</span>)
  1793. <span class="hljs-number">0.34986</span>
  1794. </code></pre></div>
  1795. <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>
  1796. <span class="hljs-meta">@profile</span>
  1797. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1798. a = [*range(<span class="hljs-number">10000</span>)]
  1799. b = {*range(<span class="hljs-number">10000</span>)}
  1800. main()
  1801. </code></pre></div>
  1802. <pre><code class="text language-text">$ kernprof -lv test.py
  1803. Line # Hits Time Per Hit % Time Line Contents
  1804. =======================================================
  1805. 1 @profile
  1806. 2 def main():
  1807. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1808. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1809. </code></pre>
  1810. <pre><code class="text language-text">$ python3 -m memory_profiler test.py
  1811. Line # Mem usage Increment Line Contents
  1812. =======================================================
  1813. 1 35.387 MiB 35.387 MiB @profile
  1814. 2 def main():
  1815. 3 35.734 MiB 0.348 MiB a = [*range(10000)]
  1816. 4 36.160 MiB 0.426 MiB b = {*range(10000)}
  1817. </code></pre>
  1818. <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>
  1819. <span class="hljs-keyword">from</span> pycallgraph <span class="hljs-keyword">import</span> output, PyCallGraph
  1820. <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
  1821. time_str = datetime.now().strftime(<span class="hljs-string">'%Y%m%d%H%M%S'</span>)
  1822. filename = <span class="hljs-string">f'profile-<span class="hljs-subst">{time_str}</span>.png'</span>
  1823. drawer = output.GraphvizOutput(output_file=filename)
  1824. <span class="hljs-keyword">with</span> PyCallGraph(drawer):
  1825. &lt;code_to_be_profiled&gt;
  1826. </code></pre></div></div>
  1827. <div><h2 id="numpy"><a href="#numpy" name="numpy">#</a>NumPy</h2><p><strong>Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.</strong></p><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install numpy</span>
  1828. <span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
  1829. </code></pre></div>
  1830. <pre><code class="python language-python hljs">&lt;array&gt; = np.array(&lt;list&gt;)
  1831. &lt;array&gt; = np.arange(from_inclusive, to_exclusive, ±step_size)
  1832. &lt;array&gt; = np.ones(&lt;shape&gt;)
  1833. &lt;array&gt; = np.random.randint(from_inclusive, to_exclusive, &lt;shape&gt;)
  1834. </code></pre>
  1835. <pre><code class="python language-python hljs">&lt;array&gt;.shape = &lt;shape&gt;
  1836. &lt;view&gt; = &lt;array&gt;.reshape(&lt;shape&gt;)
  1837. &lt;view&gt; = np.broadcast_to(&lt;array&gt;, &lt;shape&gt;)
  1838. </code></pre>
  1839. <pre><code class="python language-python hljs">&lt;array&gt; = &lt;array&gt;.sum(axis)
  1840. indexes = &lt;array&gt;.argmin(axis)
  1841. </code></pre>
  1842. <ul>
  1843. <li><strong>Shape is a tuple of dimension sizes.</strong></li>
  1844. <li><strong>Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.</strong></li>
  1845. </ul>
  1846. <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>
  1847. &lt;1d_view&gt; = &lt;2d_array&gt;[0] <span class="hljs-comment"># First row.</span>
  1848. &lt;1d_view&gt; = &lt;2d_array&gt;[:, 0] <span class="hljs-comment"># First column. Also [..., 0].</span>
  1849. &lt;3d_view&gt; = &lt;2d_array&gt;[None, :, :] <span class="hljs-comment"># Expanded by dimension of size 1.</span>
  1850. </code></pre></div>
  1851. <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;]
  1852. &lt;2d_array&gt; = &lt;2d_array&gt;[&lt;2d_row_indexes&gt;, &lt;2d_column_indexes&gt;]
  1853. </code></pre>
  1854. <pre><code class="bash language-bash hljs">&lt;2d_bools&gt; = &lt;2d_array&gt; &gt; 0
  1855. &lt;1d_array&gt; = &lt;2d_array&gt;[&lt;2d_bools&gt;]
  1856. </code></pre>
  1857. <ul>
  1858. <li><strong>If row and column indexes differ in shape, they are combined with broadcasting.</strong></li>
  1859. </ul>
  1860. <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>
  1861. 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>
  1862. </code></pre></div>
  1863. <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>
  1864. 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>
  1865. </code></pre></div>
  1866. <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>
  1867. 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>
  1868. </code></pre></div>
  1869. <div><h4 id="3ifneithernonmatchingdimensionhassize1riseanerror">3. If neither non-matching dimension has size 1, rise 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>])
  1870. [ <span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>]
  1871. <span class="hljs-meta">&gt;&gt;&gt; </span>wrapped_points = points.reshape(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>)
  1872. [[ <span class="hljs-number">0.1</span>],
  1873. [ <span class="hljs-number">0.6</span>],
  1874. [ <span class="hljs-number">0.8</span>]]
  1875. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = wrapped_points - points
  1876. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">-0.5</span>, <span class="hljs-number">-0.7</span>],
  1877. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">-0.2</span>],
  1878. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1879. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = np.abs(distances)
  1880. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1881. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">0.2</span>],
  1882. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1883. <span class="hljs-meta">&gt;&gt;&gt; </span>i = np.arange(<span class="hljs-number">3</span>)
  1884. [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
  1885. <span class="hljs-meta">&gt;&gt;&gt; </span>distances[i, i] = np.inf
  1886. [[ inf, <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1887. [ <span class="hljs-number">0.5</span>, inf, <span class="hljs-number">0.2</span>],
  1888. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, inf]]
  1889. <span class="hljs-meta">&gt;&gt;&gt; </span>distances.argmin(<span class="hljs-number">1</span>)
  1890. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]
  1891. </code></pre></div></div></div>
  1892. <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>
  1893. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image
  1894. </code></pre></div>
  1895. <pre><code class="python language-python hljs">&lt;Image&gt; = Image.new(<span class="hljs-string">'&lt;mode&gt;'</span>, (width, height))
  1896. &lt;Image&gt; = Image.open(<span class="hljs-string">'&lt;path&gt;'</span>)
  1897. &lt;Image&gt; = &lt;Image&gt;.convert(<span class="hljs-string">'&lt;mode&gt;'</span>)
  1898. &lt;Image&gt;.save(<span class="hljs-string">'&lt;path&gt;'</span>)
  1899. &lt;Image&gt;.show()
  1900. </code></pre>
  1901. <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>
  1902. &lt;Image&gt;.putpixel((x, y), &lt;tuple/int&gt;) <span class="hljs-comment"># Writes a pixel to image.</span>
  1903. &lt;ImagingCore&gt; = &lt;Image&gt;.getdata() <span class="hljs-comment"># Returns a sequence of pixels.</span>
  1904. &lt;Image&gt;.putdata(&lt;list/ImagingCore&gt;) <span class="hljs-comment"># Writes a sequence of pixels.</span>
  1905. &lt;Image&gt;.paste(&lt;Image&gt;, (x, y)) <span class="hljs-comment"># Writes an image to image.</span>
  1906. </code></pre>
  1907. <pre><code class="bash language-bash hljs">&lt;2d_array&gt; = np.array(&lt;Image&gt;) <span class="hljs-comment"># NumPy array from greyscale image.</span>
  1908. &lt;3d_array&gt; = np.array(&lt;Image&gt;) <span class="hljs-comment"># NumPy array from color image.</span>
  1909. &lt;Image&gt; = Image.fromarray(&lt;array&gt;) <span class="hljs-comment"># Image from NumPy array.</span>
  1910. </code></pre>
  1911. <div><h3 id="modes-1">Modes</h3><ul>
  1912. <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>
  1913. <li><strong><code class="python hljs"><span class="hljs-string">'L'</span></code> - 8-bit pixels, greyscale.</strong></li>
  1914. <li><strong><code class="python hljs"><span class="hljs-string">'RGB'</span></code> - 3x8-bit pixels, true color.</strong></li>
  1915. <li><strong><code class="python hljs"><span class="hljs-string">'RGBA'</span></code> - 4x8-bit pixels, true color with transparency mask.</strong></li>
  1916. <li><strong><code class="python hljs"><span class="hljs-string">'HSV'</span></code> - 3x8-bit pixels, Hue, Saturation, Value color space.</strong></li>
  1917. </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>
  1918. size = WIDTH * HEIGHT
  1919. hues = [<span class="hljs-number">255</span> * i/size <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(size)]
  1920. img = Image.new(<span class="hljs-string">'HSV'</span>, (WIDTH, HEIGHT))
  1921. 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])
  1922. img.convert(<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1923. </code></pre></div></div></div>
  1924. <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
  1925. 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>)))
  1926. img = Image.open(<span class="hljs-string">'test.png'</span>).convert(<span class="hljs-string">'HSV'</span>)
  1927. img.putdata([(add_noise(h), s, v) <span class="hljs-keyword">for</span> h, s, v <span class="hljs-keyword">in</span> img.getdata()])
  1928. img.convert(<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1929. </code></pre></div>
  1930. <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
  1931. </code></pre></div>
  1932. <pre><code class="python language-python hljs">&lt;ImageDraw&gt; = ImageDraw.Draw(&lt;Image&gt;)
  1933. &lt;ImageDraw&gt;.point((x, y), fill=<span class="hljs-keyword">None</span>)
  1934. &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>)
  1935. &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>)
  1936. &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>)
  1937. &lt;ImageDraw&gt;.polygon((x1, y1, x2, y2 [, ...]), fill=<span class="hljs-keyword">None</span>, outline=<span class="hljs-keyword">None</span>)
  1938. &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>)
  1939. </code></pre>
  1940. <ul>
  1941. <li><strong>Use <code class="python hljs"><span class="hljs-string">'fill=&lt;color&gt;'</span></code> to set the primary color.</strong></li>
  1942. <li><strong>Use <code class="python hljs"><span class="hljs-string">'outline=&lt;color&gt;'</span></code> to set the secondary color.</strong></li>
  1943. <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>
  1944. </ul>
  1945. <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>
  1946. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image, ImageDraw
  1947. <span class="hljs-keyword">import</span> imageio
  1948. WIDTH, R = <span class="hljs-number">126</span>, <span class="hljs-number">10</span>
  1949. frames = []
  1950. <span class="hljs-keyword">for</span> velocity <span class="hljs-keyword">in</span> range(<span class="hljs-number">15</span>):
  1951. y = sum(range(velocity+<span class="hljs-number">1</span>))
  1952. frame = Image.new(<span class="hljs-string">'L'</span>, (WIDTH, WIDTH))
  1953. draw = ImageDraw.Draw(frame)
  1954. draw.ellipse((WIDTH/<span class="hljs-number">2</span>-R, y, WIDTH/<span class="hljs-number">2</span>+R, y+<span class="hljs-number">2</span>*R), fill=<span class="hljs-string">'white'</span>)
  1955. frames.append(frame)
  1956. frames += reversed(frames[<span class="hljs-number">1</span>:<span class="hljs-number">-1</span>])
  1957. imageio.mimsave(<span class="hljs-string">'test.gif'</span>, frames, duration=<span class="hljs-number">0.03</span>)
  1958. </code></pre></div></div>
  1959. <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
  1960. </code></pre></div>
  1961. <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>)
  1962. framerate = &lt;Wave_read&gt;.getframerate() <span class="hljs-comment"># Number of frames per second.</span>
  1963. nchannels = &lt;Wave_read&gt;.getnchannels() <span class="hljs-comment"># Number of samples per frame.</span>
  1964. sampwidth = &lt;Wave_read&gt;.getsampwidth() <span class="hljs-comment"># Sample size in bytes.</span>
  1965. nframes = &lt;Wave_read&gt;.getnframes() <span class="hljs-comment"># Number of frames.</span>
  1966. &lt;params&gt; = &lt;Wave_read&gt;.getparams() <span class="hljs-comment"># Immutable collection of above.</span>
  1967. &lt;bytes&gt; = &lt;Wave_read&gt;.readframes(nframes) <span class="hljs-comment"># Returns next 'nframes' frames.</span>
  1968. </code></pre>
  1969. <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>)
  1970. &lt;Wave_write&gt;.setframerate(&lt;int&gt;) <span class="hljs-comment"># 44100 for CD, 48000 for video.</span>
  1971. &lt;Wave_write&gt;.setnchannels(&lt;int&gt;) <span class="hljs-comment"># 1 for mono, 2 for stereo.</span>
  1972. &lt;Wave_write&gt;.setsampwidth(&lt;int&gt;) <span class="hljs-comment"># 2 for CD quality sound.</span>
  1973. &lt;Wave_write&gt;.setparams(&lt;params&gt;) <span class="hljs-comment"># Sets all parameters.</span>
  1974. &lt;Wave_write&gt;.writeframes(&lt;bytes&gt;) <span class="hljs-comment"># Appends frames to file.</span>
  1975. </code></pre>
  1976. <ul>
  1977. <li><strong>Bytes object contains a sequence of frames, each consisting of one or more samples.</strong></li>
  1978. <li><strong>In stereo signal first sample of a frame belongs to the left channel.</strong></li>
  1979. <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>
  1980. <li><strong>If sample width is one, then the integer should be encoded unsigned.</strong></li>
  1981. <li><strong>For all other sizes the integer should be encoded signed with little-endian byte order.</strong></li>
  1982. </ul>
  1983. <div><h3 id="samplevalues">Sample Values</h3><pre><code class="text language-text">+-----------+-------------+------+-------------+
  1984. | sampwidth | min | zero | max |
  1985. +-----------+-------------+------+-------------+
  1986. | 1 | 0 | 128 | 255 |
  1987. | 2 | -32768 | 0 | 32767 |
  1988. | 3 | -8388608 | 0 | 8388607 |
  1989. | 4 | -2147483648 | 0 | 2147483647 |
  1990. +-----------+-------------+------+-------------+
  1991. </code></pre></div>
  1992. <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>
  1993. <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>
  1994. an_int = int.from_bytes(a_bytes, <span class="hljs-string">'little'</span>, signed=width!=<span class="hljs-number">1</span>)
  1995. <span class="hljs-keyword">return</span> an_int - <span class="hljs-number">128</span> * (width == <span class="hljs-number">1</span>)
  1996. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1997. width = file.getsampwidth()
  1998. frames = file.readframes(file.getnframes())
  1999. 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))
  2000. <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]
  2001. </code></pre></div>
  2002. <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>
  2003. <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>
  2004. 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))
  2005. a_float += sampwidth == <span class="hljs-number">1</span>
  2006. a_float *= pow(<span class="hljs-number">2</span>, sampwidth * <span class="hljs-number">8</span> - <span class="hljs-number">1</span>)
  2007. <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>)
  2008. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  2009. file.setnchannels(nchannels)
  2010. file.setsampwidth(sampwidth)
  2011. file.setframerate(framerate)
  2012. 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))
  2013. </code></pre></div>
  2014. <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
  2015. 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>))
  2016. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, samples_f)
  2017. </code></pre></div></div>
  2018. <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
  2019. 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>
  2020. 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>))
  2021. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, samples_f)
  2022. </code></pre></div>
  2023. <div><h4 id="playsawavfile">Plays a WAV file:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install simpleaudio</span>
  2024. <span class="hljs-keyword">import</span> wave, simpleaudio
  2025. <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:
  2026. p = file.getparams()
  2027. frames = file.readframes(p.nframes)
  2028. simpleaudio.play_buffer(frames, p.nchannels, p.sampwidth, p.framerate)
  2029. </code></pre></div>
  2030. <div><h3 id="texttospeech">Text to Speech</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pyttsx3</span>
  2031. <span class="hljs-keyword">import</span> pyttsx3
  2032. engine = pyttsx3.init()
  2033. engine.say(<span class="hljs-string">'Sally sells seashells by the seashore.'</span>)
  2034. engine.runAndWait()
  2035. </code></pre></div>
  2036. <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>
  2037. <span class="hljs-keyword">import</span> simpleaudio, math, struct
  2038. <span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain, repeat
  2039. F = <span class="hljs-number">44100</span>
  2040. P1 = <span class="hljs-string">'71♪,69,,71♪,66,,62♪,66,,59♪,,,'</span>
  2041. P2 = <span class="hljs-string">'71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'</span>
  2042. get_pause = <span class="hljs-keyword">lambda</span> seconds: repeat(<span class="hljs-number">0</span>, int(seconds * F))
  2043. sin_f = <span class="hljs-keyword">lambda</span> i, hz: math.sin(i * <span class="hljs-number">2</span> * math.pi * hz / F)
  2044. 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)))
  2045. 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>)
  2046. 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>)
  2047. 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>)
  2048. 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>))
  2049. 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)
  2050. simpleaudio.play_buffer(samples_b, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, F)
  2051. </code></pre></div></div>
  2052. <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>
  2053. <span class="hljs-comment">#</span>
  2054. <span class="hljs-comment"># Usage: .py</span>
  2055. <span class="hljs-comment">#</span>
  2056. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  2057. <span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  2058. <span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  2059. <span class="hljs-keyword">from</span> sys <span class="hljs-keyword">import</span> argv
  2060. <span class="hljs-keyword">import</span> re
  2061. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  2062. <span class="hljs-keyword">pass</span>
  2063. <span class="hljs-comment">###</span>
  2064. <span class="hljs-comment">## UTIL</span>
  2065. <span class="hljs-comment">#</span>
  2066. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
  2067. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  2068. <span class="hljs-keyword">return</span> file.readlines()
  2069. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  2070. main()
  2071. </code></pre></div>
  2072. <footer>
  2073. <aside>December 15, 2019</aside>
  2074. <a href="../" rel="author">Jure Šorn</a>
  2075. </footer>
  2076. <br>
  2077. <br>
  2078. <br>
  2079. <script src="web/jquery-3.4.0.min.js"></script>
  2080. <script src="web/script_2.js"></script>
  2081. </body>
  2082. </html>