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.

2271 lines
185 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
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
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
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
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
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
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
  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>March 14, 2018</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://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="#commandexecution">Command_Execution</a>],
  184. <strong><span class="hljs-string"><span class="hljs-string">'5. Data'</span></span></strong>: [<a href="#csv">CSV</a>, <a href="#json">JSON</a>, <a href="#pickle">Pickle</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="#introspection">Introspection</a>, <a href="#metaprograming">Metaprograming</a>, <a href="#operator">Operator</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="#profile">Profile</a>,
  187. <a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#audio">Audio</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">index = &lt;list&gt;.index(&lt;el&gt;) <span class="hljs-comment"># Returns index of first occurrence or raises ValueError.</span>
  212. &lt;list&gt;.insert(index, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
  213. &lt;el&gt; = &lt;list&gt;.pop([index]) <span class="hljs-comment"># Removes and returns item at index or from the end.</span>
  214. &lt;list&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Removes first occurrence of item or raises ValueError.</span>
  215. &lt;list&gt;.clear() <span class="hljs-comment"># Removes all items. Also works on dict and set.</span>
  216. </code></pre>
  217. <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>
  218. &lt;view&gt; = &lt;dict&gt;.values() <span class="hljs-comment"># Coll. of values that reflects changes.</span>
  219. &lt;view&gt; = &lt;dict&gt;.items() <span class="hljs-comment"># Coll. of key-value tuples.</span>
  220. </code></pre></div>
  221. <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 does not exist.</span>
  222. value = &lt;dict&gt;.setdefault(key, default=<span class="hljs-keyword">None</span>) <span class="hljs-comment"># Same, but also adds default to dict.</span>
  223. &lt;dict&gt; = collections.defaultdict(&lt;type&gt;) <span class="hljs-comment"># Creates a dict with default value of type.</span>
  224. &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>
  225. </code></pre>
  226. <pre><code class="python language-python hljs">&lt;dict&gt;.update(&lt;dict&gt;)
  227. &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">value = &lt;dict&gt;.pop(key) <span class="hljs-comment"># Removes item from dictionary.</span>
  232. {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"># Filters dictionary by keys.</span>
  233. </code></pre>
  234. <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
  235. <span class="hljs-meta">&gt;&gt;&gt; </span>colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'yellow'</span>, <span class="hljs-string">'blue'</span>, <span class="hljs-string">'red'</span>, <span class="hljs-string">'blue'</span>]
  236. <span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter(colors)
  237. 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>})
  238. <span class="hljs-meta">&gt;&gt;&gt; </span>counter.most_common()[<span class="hljs-number">0</span>]
  239. (<span class="hljs-string">'blue'</span>, <span class="hljs-number">3</span>)
  240. </code></pre></div>
  241. <div><h2 id="set"><a href="#set" name="set">#</a>Set</h2><pre><code class="python language-python hljs">&lt;set&gt; = set()
  242. </code></pre></div>
  243. <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>
  244. &lt;set&gt;.update(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;set&gt; |= &lt;set&gt;</span>
  245. </code></pre>
  246. <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>
  247. &lt;set&gt; = &lt;set&gt;.intersection(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &amp; &lt;set&gt;</span>
  248. &lt;set&gt; = &lt;set&gt;.difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; - &lt;set&gt;</span>
  249. &lt;set&gt; = &lt;set&gt;.symmetric_difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; ^ &lt;set&gt;</span>
  250. &lt;bool&gt; = &lt;set&gt;.issubset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &lt;= &lt;set&gt;</span>
  251. &lt;bool&gt; = &lt;set&gt;.issuperset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &gt;= &lt;set&gt;</span>
  252. </code></pre>
  253. <pre><code class="python language-python hljs">&lt;set&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Raises KeyError.</span>
  254. &lt;set&gt;.discard(&lt;el&gt;) <span class="hljs-comment"># Doesn't raise an error.</span>
  255. </code></pre>
  256. <div><h3 id="frozenset">Frozen Set</h3><ul>
  257. <li><strong>Is immutable and hashable.</strong></li>
  258. <li><strong>That means it can be used as a key in a dictionary or as an element in a set.</strong></li>
  259. </ul><pre><code class="python language-python hljs">&lt;frozenset&gt; = frozenset(&lt;collection&gt;)
  260. </code></pre></div>
  261. <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; = ()
  262. &lt;tuple&gt; = (&lt;el&gt;, )
  263. &lt;tuple&gt; = (&lt;el_1&gt;, &lt;el_2&gt;, ...)
  264. </code></pre></div>
  265. <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
  266. <span class="hljs-meta">&gt;&gt;&gt; </span>Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  267. <span class="hljs-meta">&gt;&gt;&gt; </span>p = Point(<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  268. Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  269. <span class="hljs-meta">&gt;&gt;&gt; </span>p[<span class="hljs-number">0</span>]
  270. <span class="hljs-number">1</span>
  271. <span class="hljs-meta">&gt;&gt;&gt; </span>p.x
  272. <span class="hljs-number">1</span>
  273. <span class="hljs-meta">&gt;&gt;&gt; </span>getattr(p, <span class="hljs-string">'y'</span>)
  274. <span class="hljs-number">2</span>
  275. <span class="hljs-meta">&gt;&gt;&gt; </span>p._fields <span class="hljs-comment"># Or: Point._fields</span>
  276. (<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>)
  277. </code></pre></div>
  278. <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)
  279. &lt;range&gt; = range(from_inclusive, to_exclusive)
  280. &lt;range&gt; = range(from_inclusive, to_exclusive, ±step_size)
  281. </code></pre></div>
  282. <pre><code class="python language-python hljs">from_inclusive = &lt;range&gt;.start
  283. to_exclusive = &lt;range&gt;.stop
  284. </code></pre>
  285. <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]):
  286. ...
  287. </code></pre></div>
  288. <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"># Calling `iter(&lt;iter&gt;)` returns unmodified iterator.</span>
  289. &lt;iter&gt; = iter(&lt;function&gt;, to_exclusive) <span class="hljs-comment"># Sequence of return values until 'to_exclusive'.</span>
  290. &lt;el&gt; = next(&lt;iter&gt; [, default]) <span class="hljs-comment"># Raises StopIteration or returns 'default' on end.</span>
  291. </code></pre></div>
  292. <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
  293. </code></pre></div>
  294. <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>
  295. &lt;iter&gt; = repeat(&lt;el&gt; [, times]) <span class="hljs-comment"># Returns element endlessly or 'times' times.</span>
  296. &lt;iter&gt; = cycle(&lt;collection&gt;) <span class="hljs-comment"># Repeats the sequence indefinitely.</span>
  297. </code></pre>
  298. <pre><code class="python language-python hljs">&lt;iter&gt; = chain(&lt;coll.&gt;, &lt;coll.&gt; [, ...]) <span class="hljs-comment"># Empties collections in order.</span>
  299. &lt;iter&gt; = chain.from_iterable(&lt;collection&gt;) <span class="hljs-comment"># Empties collections inside a collection in order.</span>
  300. </code></pre>
  301. <pre><code class="python language-python hljs">&lt;iter&gt; = islice(&lt;collection&gt;, to_exclusive)
  302. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive)
  303. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive, +step_size)
  304. </code></pre>
  305. <div><h2 id="generator"><a href="#generator" name="generator">#</a>Generator</h2><ul>
  306. <li><strong>Convenient way to implement the iterator protocol.</strong></li>
  307. <li><strong>Any function that contains a yield statement returns a generator object.</strong></li>
  308. <li><strong>Generators and iterators are interchangeable.</strong></li>
  309. </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>
  310. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  311. <span class="hljs-keyword">yield</span> start
  312. start += step
  313. </code></pre></div>
  314. <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>)
  315. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  316. (<span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>)
  317. </code></pre>
  318. <div><h2 id="type"><a href="#type" name="type">#</a>Type</h2><ul>
  319. <li><strong>Everything is an object.</strong></li>
  320. <li><strong>Every object has a type.</strong></li>
  321. <li><strong>Type and class are synonymous.</strong></li>
  322. </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>
  323. &lt;bool&gt; = isinstance(&lt;el&gt;, &lt;type&gt;) <span class="hljs-comment"># Or: issubclass(type(&lt;el&gt;), &lt;type&gt;)</span>
  324. </code></pre></div>
  325. <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
  326. (&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;)
  327. </span></code></pre>
  328. <div><h4 id="sometypesdonothavebuiltinnamessotheymustbeimported">Some types do not have builtin 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
  329. </code></pre></div>
  330. <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
  331. <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)
  332. <span class="hljs-keyword">True</span>
  333. </code></pre></div>
  334. <pre><code class="text language-text">+------------------+----------+------------+----------+
  335. | | Sequence | Collection | Iterable |
  336. +------------------+----------+------------+----------+
  337. | list, range, str | yes | yes | yes |
  338. | dict, set | | yes | yes |
  339. | iter | | | yes |
  340. +------------------+----------+------------+----------+
  341. </code></pre>
  342. <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
  343. <span class="hljs-meta">&gt;&gt;&gt; </span>isinstance(<span class="hljs-number">123</span>, Number)
  344. <span class="hljs-keyword">True</span>
  345. </code></pre>
  346. <pre><code class="text language-text">+--------------------+----------+----------+------+---------+--------+
  347. | | Integral | Rational | Real | Complex | Number |
  348. +--------------------+----------+----------+------+---------+--------+
  349. | int | yes | yes | yes | yes | yes |
  350. | fractions.Fraction | | yes | yes | yes | yes |
  351. | float | | | yes | yes | yes |
  352. | complex | | | | yes | yes |
  353. +--------------------+----------+----------+------+---------+--------+
  354. </code></pre>
  355. <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>
  356. &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>
  357. </code></pre></div>
  358. <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>
  359. &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>
  360. &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>
  361. &lt;str&gt; = &lt;str&gt;.join(&lt;coll_of_strings&gt;) <span class="hljs-comment"># Joins elements using string as separator.</span>
  362. </code></pre>
  363. <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>
  364. &lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  365. &lt;bool&gt; = &lt;str&gt;.endswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  366. &lt;int&gt; = &lt;str&gt;.find(&lt;sub_str&gt;) <span class="hljs-comment"># Returns start index of first match or -1.</span>
  367. &lt;int&gt; = &lt;str&gt;.index(&lt;sub_str&gt;) <span class="hljs-comment"># Same but raises ValueError.</span>
  368. </code></pre>
  369. <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>
  370. &lt;bool&gt; = &lt;str&gt;.isnumeric() <span class="hljs-comment"># True if str contains only numeric characters.</span>
  371. &lt;list&gt; = textwrap.wrap(&lt;str&gt;, width) <span class="hljs-comment"># Nicely breaks string into lines.</span>
  372. </code></pre>
  373. <ul>
  374. <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>
  375. <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>
  376. </ul>
  377. <div><h3 id="char">Char</h3><pre><code class="python language-python hljs">&lt;str&gt; = chr(&lt;int&gt;) <span class="hljs-comment"># Converts int to unicode char.</span>
  378. &lt;int&gt; = ord(&lt;str&gt;) <span class="hljs-comment"># Converts unicode char to int.</span>
  379. </code></pre></div>
  380. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>ord(<span class="hljs-string">'0'</span>), ord(<span class="hljs-string">'9'</span>)
  381. (<span class="hljs-number">48</span>, <span class="hljs-number">57</span>)
  382. <span class="hljs-meta">&gt;&gt;&gt; </span>ord(<span class="hljs-string">'A'</span>), ord(<span class="hljs-string">'Z'</span>)
  383. (<span class="hljs-number">65</span>, <span class="hljs-number">90</span>)
  384. <span class="hljs-meta">&gt;&gt;&gt; </span>ord(<span class="hljs-string">'a'</span>), ord(<span class="hljs-string">'z'</span>)
  385. (<span class="hljs-number">97</span>, <span class="hljs-number">122</span>)
  386. </code></pre>
  387. <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
  388. &lt;str&gt; = re.sub(&lt;regex&gt;, new, text, count=<span class="hljs-number">0</span>) <span class="hljs-comment"># Substitutes all occurrences.</span>
  389. &lt;list&gt; = re.findall(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences.</span>
  390. &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>
  391. &lt;Match&gt; = re.search(&lt;regex&gt;, text) <span class="hljs-comment"># Searches for first occurrence of pattern.</span>
  392. &lt;Match&gt; = re.match(&lt;regex&gt;, text) <span class="hljs-comment"># Searches only at the beginning of the text.</span>
  393. &lt;iter&gt; = re.finditer(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as match objects.</span>
  394. </code></pre></div>
  395. <ul>
  396. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.IGNORECASE'</span></code> can be used with all functions.</strong></li>
  397. <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>
  398. <li><strong>Argument <code class="python hljs"><span class="hljs-string">'flags=re.DOTALL'</span></code> makes dot also accept newline.</strong></li>
  399. <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>
  400. <li><strong>Use <code class="python hljs"><span class="hljs-string">'?'</span></code> to make an operator non-greedy.</strong></li>
  401. </ul>
  402. <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>
  403. &lt;str&gt; = &lt;Match&gt;.group(<span class="hljs-number">1</span>) <span class="hljs-comment"># Part in first bracket.</span>
  404. &lt;tuple&gt; = &lt;Match&gt;.groups() <span class="hljs-comment"># All bracketed parts.</span>
  405. &lt;int&gt; = &lt;Match&gt;.start() <span class="hljs-comment"># Start index of a match.</span>
  406. &lt;int&gt; = &lt;Match&gt;.end() <span class="hljs-comment"># Exclusive end index of a match.</span>
  407. </code></pre></div>
  408. <div><h3 id="specialsequences">Special Sequences</h3><ul>
  409. <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>
  410. <li><strong>Use capital letters for negation.</strong></li>
  411. </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>
  412. <span class="hljs-string">'\s'</span> == <span class="hljs-string">'[ \t\n\r\f\v]'</span> <span class="hljs-comment"># Whitespace</span>
  413. <span class="hljs-string">'\w'</span> == <span class="hljs-string">'[a-zA-Z0-9_]'</span> <span class="hljs-comment"># Alphanumeric</span>
  414. </code></pre></div>
  415. <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>
  416. &lt;str&gt; = <span class="hljs-string">'{}, {}'</span>.format(&lt;el_1&gt;, &lt;el_2&gt;)
  417. </code></pre></div>
  418. <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
  419. <span class="hljs-meta">&gt;&gt;&gt; </span>Person = namedtuple(<span class="hljs-string">'Person'</span>, <span class="hljs-string">'name height'</span>)
  420. <span class="hljs-meta">&gt;&gt;&gt; </span>person = Person(<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)
  421. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">f'<span class="hljs-subst">{person.height}</span>'</span>
  422. <span class="hljs-string">'187'</span>
  423. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">'{p.height}'</span>.format(p=person)
  424. <span class="hljs-string">'187'</span>
  425. </code></pre></div>
  426. <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>
  427. {&lt;el&gt;:^<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt; '</span>
  428. {&lt;el&gt;:&gt;<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt;'</span>
  429. </code></pre></div>
  430. <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>
  431. {&lt;el&gt;:&gt;<span class="hljs-number">0</span>} <span class="hljs-comment"># '&lt;el&gt;'</span>
  432. </code></pre>
  433. <div><h3 id="strings">Strings</h3><p><strong><code class="python hljs"><span class="hljs-string">'!r'</span></code> calls object's repr() method, instead of str(), 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>
  434. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">.3</span>} <span class="hljs-comment"># 'abc'</span>
  435. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># 'abc '</span>
  436. </code></pre></div>
  437. <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>
  438. { <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>_} <span class="hljs-comment"># ' 123_456'</span>
  439. { <span class="hljs-number">123456</span>:+<span class="hljs-number">10</span>} <span class="hljs-comment"># ' +123456'</span>
  440. {<span class="hljs-number">-123456</span>:=<span class="hljs-number">10</span>} <span class="hljs-comment"># '- 123456'</span>
  441. { <span class="hljs-number">123456</span>: } <span class="hljs-comment"># ' 123456'</span>
  442. {<span class="hljs-number">-123456</span>: } <span class="hljs-comment"># '-123456'</span>
  443. </code></pre></div>
  444. <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>
  445. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>f} <span class="hljs-comment"># ' 1.235'</span>
  446. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>e} <span class="hljs-comment"># ' 1.235e+00'</span>
  447. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>%} <span class="hljs-comment"># ' 123.456%'</span>
  448. </code></pre></div>
  449. <div><h4 id="comparisonoffloatpresentationtypes">Comparison of float presentation types:</h4><pre><code class="text language-text">+----------------+----------------+---------------+----------------+-----------------+
  450. | | {&lt;float&gt;} | {&lt;float&gt;:f} | {&lt;float&gt;:e} | {&lt;float&gt;:%} |
  451. +----------------+----------------+---------------+----------------+-----------------+
  452. | 0.000056789 | '5.6789e-05' | '0.000057' | '5.678900e-05' | '0.005679%' |
  453. | 0.00056789 | '0.00056789' | '0.000568' | '5.678900e-04' | '0.056789%' |
  454. | 0.0056789 | '0.0056789' | '0.005679' | '5.678900e-03' | '0.567890%' |
  455. | 0.056789 | '0.056789' | '0.056789' | '5.678900e-02' | '5.678900%' |
  456. | 0.56789 | '0.56789' | '0.567890' | '5.678900e-01' | '56.789000%' |
  457. | 5.6789 | '5.6789' | '5.678900' | '5.678900e+00' | '567.890000%' |
  458. | 56.789 | '56.789' | '56.789000' | '5.678900e+01' | '5678.900000%' |
  459. | 567.89 | '567.89' | '567.890000' | '5.678900e+02' | '56789.000000%' |
  460. +----------------+----------------+---------------+----------------+-----------------+
  461. </code></pre></div>
  462. <pre><code class="text language-text">+----------------+----------------+---------------+----------------+-----------------+
  463. | | {&lt;float&gt;:.2} | {&lt;float&gt;:.2f} | {&lt;float&gt;:.2e} | {&lt;float&gt;:.2%} |
  464. +----------------+----------------+---------------+----------------+-----------------+
  465. | 0.000056789 | '5.7e-05' | '0.00' | '5.68e-05' | '0.01%' |
  466. | 0.00056789 | '0.00057' | '0.00' | '5.68e-04' | '0.06%' |
  467. | 0.0056789 | '0.0057' | '0.01' | '5.68e-03' | '0.57%' |
  468. | 0.056789 | '0.057' | '0.06' | '5.68e-02' | '5.68%' |
  469. | 0.56789 | '0.57' | '0.57' | '5.68e-01' | '56.79%' |
  470. | 5.6789 | '5.7' | '5.68' | '5.68e+00' | '567.89%' |
  471. | 56.789 | '5.7e+01' | '56.79' | '5.68e+01' | '5678.90%' |
  472. | 567.89 | '5.7e+02' | '567.89' | '5.68e+02' | '56789.00%' |
  473. +----------------+----------------+---------------+----------------+-----------------+
  474. </code></pre>
  475. <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>
  476. {<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'</span>
  477. {<span class="hljs-number">90</span>:b} <span class="hljs-comment"># '1011010'</span>
  478. </code></pre></div>
  479. <div><h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2><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>
  480. &lt;float&gt; = float(&lt;int/str/bool&gt;)
  481. &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>
  482. &lt;Fraction&gt; = fractions.Fraction(numerator=<span class="hljs-number">0</span>, denominator=<span class="hljs-number">1</span>)
  483. </code></pre></div>
  484. <ul>
  485. <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>
  486. </ul>
  487. <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>
  488. &lt;real&gt; = abs(&lt;num&gt;)
  489. &lt;int&gt; = round(&lt;real&gt;)
  490. &lt;real&gt; = round(&lt;real&gt;, ±ndigits) <span class="hljs-comment"># `round(126, -1) == 130`</span>
  491. </code></pre></div>
  492. <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
  493. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians
  494. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2
  495. </code></pre></div>
  496. <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
  497. </code></pre></div>
  498. <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
  499. &lt;float&gt; = random()
  500. &lt;int&gt; = randint(from_inclusive, to_inclusive)
  501. &lt;el&gt; = choice(&lt;list&gt;)
  502. shuffle(&lt;list&gt;)
  503. </code></pre></div>
  504. <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>
  505. &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>
  506. &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>
  507. <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>
  508. </code></pre></div>
  509. <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>
  510. &lt;int&gt; = &lt;int&gt; | &lt;int&gt; <span class="hljs-comment"># Or</span>
  511. &lt;int&gt; = &lt;int&gt; ^ &lt;int&gt; <span class="hljs-comment"># Xor (0 if both bits equal)</span>
  512. &lt;int&gt; = &lt;int&gt; &lt;&lt; n_bits <span class="hljs-comment"># Shift left</span>
  513. &lt;int&gt; = &lt;int&gt; &gt;&gt; n_bits <span class="hljs-comment"># Shift right</span>
  514. &lt;int&gt; = ~&lt;int&gt; <span class="hljs-comment"># Compliment (flips bits)</span>
  515. </code></pre></div>
  516. <div><h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2><ul>
  517. <li><strong>Every function returns an iterator.</strong></li>
  518. <li><strong>If you want to print the iterator, you need to pass it to the list() function!</strong></li>
  519. </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
  520. </code></pre></div>
  521. <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>)
  522. [(<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>),
  523. (<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>)]
  524. </code></pre>
  525. <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>)
  526. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'2'</span>),
  527. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'2'</span>)]
  528. </code></pre>
  529. <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>)
  530. [(<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>)]
  531. </code></pre>
  532. <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>)
  533. [(<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>),
  534. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  535. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)]
  536. </code></pre>
  537. <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>)
  538. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  539. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  540. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)]
  541. </code></pre>
  542. <div><h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2><ul>
  543. <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>
  544. <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>
  545. <li><strong>If object is naive it is presumed to be in system's timezone.</strong></li>
  546. </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
  547. <span class="hljs-keyword">from</span> dateutil.tz <span class="hljs-keyword">import</span> UTC, tzlocal, gettz
  548. </code></pre></div>
  549. <div><h3 id="constructors">Constructors</h3><pre><code class="python language-python apache hljs">&lt;D&gt; = date(year, month, day)
  550. &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>)
  551. &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>, ...)
  552. &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>,
  553. minutes=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>, weeks=<span class="hljs-number">0</span>)
  554. </code></pre></div>
  555. <ul>
  556. <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>
  557. <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>
  558. </ul>
  559. <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>
  560. &lt;DTn&gt; = DT.utcnow() <span class="hljs-comment"># Naive datetime from current UTC time.</span>
  561. &lt;DTa&gt; = DT.now(&lt;tzinfo&gt;) <span class="hljs-comment"># Aware datetime from current tz time.</span>
  562. </code></pre></div>
  563. <ul>
  564. <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>
  565. </ul>
  566. <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>
  567. &lt;tzinfo&gt; = tzlocal() <span class="hljs-comment"># Local timezone. Also gettz().</span>
  568. &lt;tzinfo&gt; = gettz(<span class="hljs-string">'&lt;Cont.&gt;/&lt;City&gt;'</span>) <span class="hljs-comment"># Timezone from 'Continent/City_Name' str.</span>
  569. </code></pre></div>
  570. <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>
  571. &lt;Ta/DTa&gt; = &lt;T/DT&gt;.replace(tzinfo=&lt;tzinfo&gt;) <span class="hljs-comment"># Unconverted object with new timezone.</span>
  572. </code></pre>
  573. <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.</span>
  574. &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>
  575. &lt;D/DTn&gt; = D/DT.fromordinal(&lt;int&gt;) <span class="hljs-comment"># D/DTn from days since Christ, at midnight.</span>
  576. &lt;DTn&gt; = DT.fromtimestamp(&lt;real&gt;) <span class="hljs-comment"># Local time DTn from seconds since Epoch.</span>
  577. &lt;DTa&gt; = DT.fromtimestamp(&lt;real&gt;, &lt;tz.&gt;) <span class="hljs-comment"># Aware datetime from seconds since Epoch.</span>
  578. </code></pre></div>
  579. <ul>
  580. <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 <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>
  581. <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>
  582. </ul>
  583. <div><h3 id="decode">Decode</h3><pre><code class="python language-python hljs">&lt;str&gt; = &lt;D/T/DT&gt;.isoformat() <span class="hljs-comment"># ISO string representation.</span>
  584. &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>
  585. &lt;int&gt; = &lt;D/DT&gt;.toordinal() <span class="hljs-comment"># Days since Christ, ignoring time and tz.</span>
  586. &lt;float&gt; = &lt;DTn&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTn in local time.</span>
  587. &lt;float&gt; = &lt;DTa&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch from DTa.</span>
  588. </code></pre></div>
  589. <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
  590. <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>)
  591. <span class="hljs-meta">&gt;&gt;&gt; </span>dt.strftime(<span class="hljs-string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)
  592. <span class="hljs-string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span>
  593. </code></pre></div>
  594. <ul>
  595. <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>
  596. <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>
  597. </ul>
  598. <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;
  599. &lt;TD&gt; = &lt;TD&gt; ± &lt;TD&gt;
  600. &lt;TD&gt; = &lt;TD&gt; */ &lt;real&gt;
  601. &lt;float&gt; = &lt;TD&gt; / &lt;TD&gt;
  602. </code></pre></div>
  603. <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>
  604. &lt;function&gt;(&lt;keyword_args&gt;) <span class="hljs-comment"># f(x=0, y=0)</span>
  605. &lt;function&gt;(&lt;positional_args&gt;, &lt;keyword_args&gt;) <span class="hljs-comment"># f(0, y=0)</span>
  606. </code></pre></div></div>
  607. <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>
  608. <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>
  609. <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>
  610. </code></pre></div>
  611. <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>)
  612. 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>}
  613. func(*args, **kwargs)
  614. </code></pre></div></div>
  615. <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>)
  616. </code></pre></div>
  617. <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>
  618. <span class="hljs-keyword">return</span> sum(a)
  619. </code></pre></div>
  620. <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>)
  621. <span class="hljs-number">6</span>
  622. </code></pre>
  623. <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>
  624. <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>
  625. <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>
  626. <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>
  627. </code></pre></div>
  628. <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>
  629. <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>
  630. <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>
  631. <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>
  632. </code></pre>
  633. <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>
  634. <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>
  635. <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>
  636. </code></pre>
  637. <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>
  638. <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>
  639. <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>
  640. <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>
  641. </code></pre>
  642. <div><h3 id="otheruses">Other Uses</h3><pre><code class="python language-python hljs">&lt;list&gt; = [*&lt;collection&gt; [, ...]]
  643. &lt;set&gt; = {*&lt;collection&gt; [, ...]}
  644. &lt;tuple&gt; = (*&lt;collection&gt;, [...])
  645. &lt;dict&gt; = {**&lt;dict&gt; [, ...]}
  646. </code></pre></div>
  647. <pre><code class="python language-python hljs">head, *body, tail = &lt;collection&gt;
  648. </code></pre>
  649. <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;
  650. &lt;function&gt; = <span class="hljs-keyword">lambda</span> &lt;argument_1&gt;, &lt;argument_2&gt;: &lt;return_value&gt;
  651. </code></pre></div></div>
  652. <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>
  653. &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>
  654. &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>
  655. &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>
  656. </code></pre></div>
  657. <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>)]
  658. </code></pre>
  659. <div><h4 id="isthesameas-1">Is the same as:</h4><pre><code class="python language-python hljs">out = []
  660. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  661. <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  662. out.append(i+j)
  663. </code></pre></div>
  664. <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
  665. &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>
  666. &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>
  667. &lt;int&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>
  668. </code></pre></div>
  669. <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>
  670. &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>
  671. </code></pre></div>
  672. <div><h3 id="ifelse">If - Else</h3><pre><code class="python language-python hljs">&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;
  673. </code></pre></div>
  674. <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">0</span>, <span class="hljs-number">3</span>)]
  675. [<span class="hljs-string">'zero'</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'zero'</span>, <span class="hljs-number">3</span>]
  676. </code></pre>
  677. <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
  678. Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  679. point = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
  680. </code></pre></div>
  681. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  682. Direction = Enum(<span class="hljs-string">'Direction'</span>, <span class="hljs-string">'n e s w'</span>)
  683. direction = Direction.n
  684. </code></pre>
  685. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  686. Creature = make_dataclass(<span class="hljs-string">'Creature'</span>, [<span class="hljs-string">'location'</span>, <span class="hljs-string">'direction'</span>])
  687. creature = Creature(Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), Direction.n)
  688. </code></pre>
  689. <div><h2 id="closure"><a href="#closure" name="closure">#</a>Closure</h2><p><strong>We have a closure in Python when:</strong></p><ul>
  690. <li><strong>A nested function references a value of its enclosing function and then</strong></li>
  691. <li><strong>the enclosing function returns the nested function.</strong></li>
  692. </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>
  693. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(b)</span>:</span>
  694. <span class="hljs-keyword">return</span> a * b
  695. <span class="hljs-keyword">return</span> out
  696. </code></pre></div>
  697. <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>)
  698. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  699. <span class="hljs-number">30</span>
  700. </code></pre>
  701. <ul>
  702. <li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
  703. <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>
  704. </ul>
  705. <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
  706. &lt;function&gt; = partial(&lt;function&gt; [, &lt;arg_1&gt;, &lt;arg_2&gt;, ...])
  707. </code></pre></div>
  708. <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
  709. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3 = partial(op.mul, <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>Partial is also useful in cases when a function needs to be passed as an argument, because it enables us to set its arguments beforehand.</strong></li>
  715. <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>
  716. </ul>
  717. <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>
  718. i = <span class="hljs-number">0</span>
  719. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">()</span>:</span>
  720. <span class="hljs-keyword">nonlocal</span> i
  721. i += <span class="hljs-number">1</span>
  722. <span class="hljs-keyword">return</span> i
  723. <span class="hljs-keyword">return</span> out
  724. </code></pre></div>
  725. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = get_counter()
  726. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  727. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  728. </code></pre>
  729. <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>
  730. <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>
  731. ...
  732. </code></pre></div>
  733. <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
  734. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(func)</span>:</span>
  735. <span class="hljs-meta"> @wraps(func)</span>
  736. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  737. print(func.__name__)
  738. <span class="hljs-keyword">return</span> func(*args, **kwargs)
  739. <span class="hljs-keyword">return</span> out
  740. <span class="hljs-meta">@debug</span>
  741. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  742. <span class="hljs-keyword">return</span> x + y
  743. </code></pre></div>
  744. <ul>
  745. <li><strong>Wraps is a helper decorator that copies metadata of function add() to function out().</strong></li>
  746. <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>
  747. </ul>
  748. <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
  749. <span class="hljs-meta">@lru_cache(maxsize=None)</span>
  750. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>
  751. <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>)
  752. </code></pre></div>
  753. <ul>
  754. <li><strong>Recursion depth is limited 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>
  755. </ul>
  756. <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
  757. <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>
  758. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>
  759. <span class="hljs-meta"> @wraps(func)</span>
  760. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  761. result = func(*args, **kwargs)
  762. print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>)
  763. <span class="hljs-keyword">return</span> result
  764. <span class="hljs-keyword">return</span> out
  765. <span class="hljs-keyword">return</span> decorator
  766. <span class="hljs-meta">@debug(print_result=True)</span>
  767. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  768. <span class="hljs-keyword">return</span> x + y
  769. </code></pre></div>
  770. <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>
  771. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  772. self.a = a
  773. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span><span class="hljs-params">(self)</span>:</span>
  774. class_name = self.__class__.__name__
  775. <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>
  776. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
  777. <span class="hljs-keyword">return</span> str(self.a)
  778. <span class="hljs-meta"> @classmethod</span>
  779. <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>
  780. <span class="hljs-keyword">return</span> cls.__name__
  781. </code></pre></div>
  782. <ul>
  783. <li><strong>Return value of repr() should be unambiguous and of str() readable.</strong></li>
  784. <li><strong>If only repr() is defined, it will be also used for str().</strong></li>
  785. </ul>
  786. <div><h4 id="strusecases">Str() use cases:</h4><pre><code class="python language-python hljs">print(&lt;el&gt;)
  787. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;}</span>'</span>)
  788. <span class="hljs-keyword">raise</span> Exception(&lt;el&gt;)
  789. logging.debug(&lt;el&gt;)
  790. csv.writer(&lt;file&gt;).writerow([&lt;el&gt;])
  791. </code></pre></div>
  792. <div><h4 id="reprusecases">Repr() use cases:</h4><pre><code class="python language-python hljs">print([&lt;el&gt;])
  793. print(<span class="hljs-string">f'<span class="hljs-subst">{&lt;el&gt;!r}</span>'</span>)
  794. <span class="hljs-meta">&gt;&gt;&gt; </span>&lt;el&gt;
  795. loguru.logger.exception()
  796. Z = dataclasses.make_dataclass(<span class="hljs-string">'Z'</span>, [<span class="hljs-string">'a'</span>]); print(Z(&lt;el&gt;))
  797. </code></pre></div>
  798. <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>
  799. <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>
  800. self.a = a
  801. </code></pre></div>
  802. <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>
  803. <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>
  804. self.name = name
  805. self.age = age
  806. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Person)</span>:</span>
  807. <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>
  808. super().__init__(name, age)
  809. self.staff_num = staff_num
  810. </code></pre></div>
  811. <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>
  812. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>:</span> <span class="hljs-keyword">pass</span>
  813. <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>
  814. </code></pre></div>
  815. <p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong></p>
  816. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>C.mro()
  817. [&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;]
  818. </span></code></pre>
  819. <div><h3 id="property">Property</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyClass</span>:</span>
  820. <span class="hljs-meta"> @property</span>
  821. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  822. <span class="hljs-keyword">return</span> self._a
  823. <span class="hljs-meta"> @a.setter</span>
  824. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self, value)</span>:</span>
  825. self._a = value
  826. </code></pre></div>
  827. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>el = MyClass()
  828. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a = <span class="hljs-number">123</span>
  829. <span class="hljs-meta">&gt;&gt;&gt; </span>el.a
  830. <span class="hljs-number">123</span>
  831. </code></pre>
  832. <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
  833. <span class="hljs-meta">@dataclass(order=False, frozen=False)</span>
  834. <span class="hljs-class"><span class="hljs-keyword">class</span> &lt;<span class="hljs-title">class_name</span>&gt;:</span>
  835. &lt;attr_name_1&gt;: &lt;type&gt;
  836. &lt;attr_name_2&gt;: &lt;type&gt; = &lt;default_value&gt;
  837. &lt;attr_name_3&gt;: list/dict/set = field(default_factory=list/dict/set)
  838. </code></pre></div>
  839. <ul>
  840. <li><strong>An object can be made sortable with <code class="python hljs"><span class="hljs-string">'order=True'</span></code> or immutable with <code class="python hljs"><span class="hljs-string">'frozen=True'</span></code>.</strong></li>
  841. <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>
  842. <li><strong>Default_factory can be any callable.</strong></li>
  843. </ul>
  844. <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>
  845. __slots__ = [<span class="hljs-string">'a'</span>]
  846. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  847. self.a = <span class="hljs-number">1</span>
  848. </code></pre></div>
  849. <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
  850. &lt;object&gt; = copy(&lt;object&gt;)
  851. &lt;object&gt; = deepcopy(&lt;object&gt;)
  852. </code></pre></div>
  853. <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>
  854. <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>
  855. <li><strong>That means all objects compare not equal by default.</strong></li>
  856. <li><strong>Only left side object has eq() method called, unless it returns 'NotImplemented', in which case the right object is consulted.</strong></li>
  857. </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>
  858. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  859. self.a = a
  860. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  861. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  862. <span class="hljs-keyword">return</span> self.a == other.a
  863. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  864. </code></pre></div></div>
  865. <div><h3 id="hashable">Hashable</h3><ul>
  866. <li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
  867. <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>
  868. <li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
  869. </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>
  870. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  871. self._a = copy.deepcopy(a)
  872. <span class="hljs-meta"> @property</span>
  873. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  874. <span class="hljs-keyword">return</span> self._a
  875. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  876. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  877. <span class="hljs-keyword">return</span> self.a == other.a
  878. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  879. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__hash__</span><span class="hljs-params">(self)</span>:</span>
  880. <span class="hljs-keyword">return</span> hash(self.a)
  881. </code></pre></div>
  882. <div><h3 id="sortable">Sortable</h3><ul>
  883. <li><strong>With 'total_ordering' decorator you only need to provide eq() and one of lt(), gt(), le() or ge() special methods.</strong></li>
  884. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> total_ordering
  885. <span class="hljs-meta">@total_ordering</span>
  886. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySortable</span>:</span>
  887. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  888. self.a = a
  889. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  890. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  891. <span class="hljs-keyword">return</span> self.a == other.a
  892. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  893. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__lt__</span><span class="hljs-params">(self, other)</span>:</span>
  894. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  895. <span class="hljs-keyword">return</span> self.a &lt; other.a
  896. <span class="hljs-keyword">return</span> <span class="hljs-built_in">NotImplemented</span>
  897. </code></pre></div>
  898. <div><h3 id="iterator-1">Iterator</h3><ul>
  899. <li><strong>Next() should return next item or raise 'StopIteration'.</strong></li>
  900. <li><strong>Iter() should return 'self'.</strong></li>
  901. </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>
  902. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  903. self.i = <span class="hljs-number">0</span>
  904. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__next__</span><span class="hljs-params">(self)</span>:</span>
  905. self.i += <span class="hljs-number">1</span>
  906. <span class="hljs-keyword">return</span> self.i
  907. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  908. <span class="hljs-keyword">return</span> self
  909. </code></pre></div>
  910. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  911. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  912. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  913. </code></pre>
  914. <div><h3 id="callable">Callable</h3><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
  915. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  916. self.i = <span class="hljs-number">0</span>
  917. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self)</span>:</span>
  918. self.i += <span class="hljs-number">1</span>
  919. <span class="hljs-keyword">return</span> self.i
  920. </code></pre></div>
  921. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  922. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  923. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  924. </code></pre>
  925. <div><h3 id="contextmanager">Context Manager</h3><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>
  926. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, filename)</span>:</span>
  927. self.filename = filename
  928. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span><span class="hljs-params">(self)</span>:</span>
  929. self.file = open(self.filename)
  930. <span class="hljs-keyword">return</span> self.file
  931. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, *args)</span>:</span>
  932. self.file.close()
  933. </code></pre></div>
  934. <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:
  935. <span class="hljs-meta">... </span> file.write(<span class="hljs-string">'Hello World!'</span>)
  936. <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:
  937. <span class="hljs-meta">... </span> print(file.read())
  938. Hello World!
  939. </code></pre>
  940. <div><h4 id="listofexistingcontextmanagers">List of existing context managers:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">with</span> open(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-keyword">as</span> file: ...
  941. <span class="hljs-keyword">with</span> wave.open(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-keyword">as</span> wave_file: ...
  942. <span class="hljs-keyword">with</span> memoryview(&lt;bytes/bytearray/array&gt;) <span class="hljs-keyword">as</span> view: ...
  943. db = sqlite3.connect(<span class="hljs-string">'&lt;path&gt;'</span>); <span class="hljs-keyword">with</span> db: db.execute(<span class="hljs-string">'&lt;insert_query&gt;'</span>)
  944. lock = threading.RLock(); <span class="hljs-keyword">with</span> lock: ...
  945. </code></pre></div>
  946. <div><h2 id="iterableducktypes"><a href="#iterableducktypes" name="iterableducktypes">#</a>Iterable Duck Types</h2><div><h3 id="iterable">Iterable</h3><ul>
  947. <li><strong>Only required method is iter(). It should return an iterator of object's items.</strong></li>
  948. <li><strong>Contains() automatically works on any object that has iter() defined.</strong></li>
  949. </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>
  950. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  951. self.a = a
  952. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  953. <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> self.a:
  954. <span class="hljs-keyword">yield</span> el
  955. </code></pre></div></div>
  956. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>a = MyIterable([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>])
  957. <span class="hljs-meta">&gt;&gt;&gt; </span>iter(a)
  958. &lt;generator object MyIterable.__iter__ at <span class="hljs-number">0x1026c18b8</span>&gt;
  959. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-number">1</span> <span class="hljs-keyword">in</span> a
  960. <span class="hljs-keyword">True</span>
  961. </code></pre>
  962. <div><h3 id="collection">Collection</h3><ul>
  963. <li><strong>Only required methods are iter() and len().</strong></li>
  964. <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>
  965. <li><strong>I chose not to use the name 'iterable' because it sounds scarier and more vague than 'collection'.</strong></li>
  966. </ul><pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCollection</span>:</span>
  967. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  968. self.a = a
  969. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  970. <span class="hljs-keyword">return</span> iter(self.a)
  971. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  972. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  973. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  974. <span class="hljs-keyword">return</span> len(self.a)
  975. </code></pre></div>
  976. <div><h3 id="sequence">Sequence</h3><ul>
  977. <li><strong>Only required methods are len() and getitem().</strong></li>
  978. <li><strong>Getitem() should return an item at index or raise 'IndexError'.</strong></li>
  979. <li><strong>Iter() and contains() automatically work on any object that has getitem() defined.</strong></li>
  980. <li><strong>Reversed() automatically works on any object that has getitem() and len() defined.</strong></li>
  981. </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>
  982. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  983. self.a = a
  984. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  985. <span class="hljs-keyword">return</span> iter(self.a)
  986. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  987. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  988. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  989. <span class="hljs-keyword">return</span> len(self.a)
  990. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  991. <span class="hljs-keyword">return</span> self.a[i]
  992. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__reversed__</span><span class="hljs-params">(self)</span>:</span>
  993. <span class="hljs-keyword">return</span> reversed(self.a)
  994. </code></pre></div>
  995. <div><h3 id="collectionsabcsequence">Collections.abc.Sequence</h3><ul>
  996. <li><strong>It's a richer interface than the basic sequence.</strong></li>
  997. <li><strong>Extending it generates iter(), contains(), reversed(), index(), and count().</strong></li>
  998. <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>
  999. </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>
  1000. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  1001. self.a = a
  1002. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  1003. <span class="hljs-keyword">return</span> len(self.a)
  1004. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  1005. <span class="hljs-keyword">return</span> self.a[i]
  1006. </code></pre></div>
  1007. <div><h4 id="tableofrequiredandavailablespecialmethods">Table of required and available special methods:</h4><pre><code class="text language-text">+------------+----------+------------+----------+--------------+
  1008. | | Iterable | Collection | Sequence | abc.Sequence |
  1009. +------------+----------+------------+----------+--------------+
  1010. | iter() | REQ | REQ | yes | yes |
  1011. | contains() | yes | yes | yes | yes |
  1012. | len() | | REQ | REQ | REQ |
  1013. | getitem() | | | REQ | REQ |
  1014. | reversed() | | | yes | yes |
  1015. | index() | | | | yes |
  1016. | count() | | | | yes |
  1017. +------------+----------+------------+----------+--------------+
  1018. </code></pre></div>
  1019. <ul>
  1020. <li><strong>Other useful ABCs that automatically generate missing methods are: MutableSequence, Set, MutableSet, Mapping and MutableMapping.</strong></li>
  1021. </ul>
  1022. <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
  1023. <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>
  1024. &lt;member_name_1&gt; = &lt;value_1&gt;
  1025. &lt;member_name_2&gt; = &lt;value_2_a&gt;, &lt;value_2_b&gt;
  1026. &lt;member_name_3&gt; = auto()
  1027. <span class="hljs-meta"> @classmethod</span>
  1028. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_member_names</span><span class="hljs-params">(cls)</span>:</span>
  1029. <span class="hljs-keyword">return</span> [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> cls.__members__.values()]
  1030. </code></pre></div>
  1031. <ul>
  1032. <li><strong>If there are no numeric values before auto(), it returns 1.</strong></li>
  1033. <li><strong>Otherwise it returns an increment of last numeric value.</strong></li>
  1034. </ul>
  1035. <pre><code class="python language-python hljs">&lt;member&gt; = &lt;enum&gt;.&lt;member_name&gt;
  1036. &lt;member&gt; = &lt;enum&gt;[<span class="hljs-string">'&lt;member_name&gt;'</span>]
  1037. &lt;member&gt; = &lt;enum&gt;(&lt;value&gt;)
  1038. name = &lt;member&gt;.name
  1039. value = &lt;member&gt;.value
  1040. </code></pre>
  1041. <pre><code class="python language-python hljs">list_of_members = list(&lt;enum&gt;)
  1042. member_names = [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1043. member_values = [a.value <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  1044. random_member = random.choice(list(&lt;enum&gt;))
  1045. </code></pre>
  1046. <div><h3 id="inline-1">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>])
  1047. Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, <span class="hljs-string">'fork knife spoon'</span>)
  1048. 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>})
  1049. </code></pre></div>
  1050. <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
  1051. 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),
  1052. <span class="hljs-string">'OR'</span> : partial(<span class="hljs-keyword">lambda</span> l, r: l <span class="hljs-keyword">or</span> r)})
  1053. </code></pre></div>
  1054. <ul>
  1055. <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>
  1056. </ul>
  1057. <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>:
  1058. &lt;code&gt;
  1059. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1060. &lt;code&gt;
  1061. </code></pre></div></div>
  1062. <div><h3 id="complexexample">Complex Example</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">try</span>:
  1063. &lt;code_1&gt;
  1064. <span class="hljs-keyword">except</span> &lt;exception_a&gt;:
  1065. &lt;code_2_a&gt;
  1066. <span class="hljs-keyword">except</span> &lt;exception_b&gt;:
  1067. &lt;code_2_b&gt;
  1068. <span class="hljs-keyword">else</span>:
  1069. &lt;code_2_c&gt;
  1070. <span class="hljs-keyword">finally</span>:
  1071. &lt;code_3&gt;
  1072. </code></pre></div>
  1073. <div><h3 id="catchingexceptions">Catching Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">except</span> &lt;exception&gt;:
  1074. <span class="hljs-keyword">except</span> &lt;exception&gt; <span class="hljs-keyword">as</span> &lt;name&gt;:
  1075. <span class="hljs-keyword">except</span> (&lt;exception_1&gt;, &lt;exception_2&gt;, ...):
  1076. <span class="hljs-keyword">except</span> (&lt;exception_1&gt;, &lt;exception_2&gt;, ...) <span class="hljs-keyword">as</span> &lt;name&gt;:
  1077. </code></pre></div>
  1078. <ul>
  1079. <li><strong>Also catches subclasses of the exception.</strong></li>
  1080. </ul>
  1081. <div><h3 id="raisingexceptions">Raising Exceptions</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> &lt;exception&gt;
  1082. <span class="hljs-keyword">raise</span> &lt;exception&gt;()
  1083. <span class="hljs-keyword">raise</span> &lt;exception&gt;(&lt;el&gt;)
  1084. <span class="hljs-keyword">raise</span> &lt;exception&gt;(&lt;el_1&gt;, &lt;el_2&gt;, ...)
  1085. </code></pre></div>
  1086. <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>)
  1087. <span class="hljs-keyword">raise</span> TypeError(<span class="hljs-string">'Argument is of wrong type!'</span>)
  1088. <span class="hljs-keyword">raise</span> RuntimeError(<span class="hljs-string">'None of above!'</span>)
  1089. </code></pre></div>
  1090. <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;:
  1091. &lt;code&gt;
  1092. <span class="hljs-keyword">raise</span>
  1093. </code></pre></div>
  1094. <div><h3 id="commonbuiltinexceptions">Common Built-in Exceptions</h3><pre><code class="text language-text">BaseException
  1095. +-- SystemExit # Raised by the sys.exit() function.
  1096. +-- KeyboardInterrupt # Raised when the user hits the interrupt key.
  1097. +-- Exception # User-defined exceptions should be derived from this class.
  1098. +-- StopIteration # Raised by next() when run on an empty iterator.
  1099. +-- ArithmeticError # Base class for arithmetic errors.
  1100. | +-- ZeroDivisionError # Raised when dividing by zero.
  1101. +-- AttributeError # Raised when an attribute is missing.
  1102. +-- EOFError # Raised by input() when it hits end-of-file condition.
  1103. +-- LookupError # Raised when a look-up on sequence or dict fails.
  1104. | +-- IndexError # Raised when a sequence index is out of range.
  1105. | +-- KeyError # Raised when a dictionary key is not found.
  1106. +-- NameError # Raised when a variable name is not found.
  1107. +-- OSError # Failures such as “file not found” or “disk full”.
  1108. | +-- FileNotFoundError # When a file or directory is requested but doesn't exist.
  1109. +-- RuntimeError # Raised by errors that don't fall in other categories.
  1110. | +-- RecursionError # Raised when the the maximum recursion depth is exceeded.
  1111. +-- TypeError # Raised when an argument is of wrong type.
  1112. +-- ValueError # When an argument is of right type but inappropriate value.
  1113. +-- UnicodeError # Raised when encoding/decoding strings from/to bytes fails.
  1114. </code></pre></div>
  1115. <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>
  1116. <span class="hljs-keyword">pass</span>
  1117. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyInputError</span><span class="hljs-params">(MyError)</span>:</span>
  1118. <span class="hljs-keyword">pass</span>
  1119. </code></pre></div>
  1120. <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>)
  1121. </code></pre></div>
  1122. <ul>
  1123. <li><strong>Use <code class="python hljs"><span class="hljs-string">'file=sys.stderr'</span></code> for errors.</strong></li>
  1124. <li><strong>Use <code class="python hljs"><span class="hljs-string">'flush=True'</span></code> to forcibly flush the stream.</strong></li>
  1125. </ul>
  1126. <div><h3 id="prettyprint">Pretty Print</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> pprint <span class="hljs-keyword">import</span> pprint
  1127. <span class="hljs-meta">&gt;&gt;&gt; </span>pprint(dir())
  1128. [<span class="hljs-string">'__annotations__'</span>,
  1129. <span class="hljs-string">'__builtins__'</span>,
  1130. <span class="hljs-string">'__doc__'</span>, ...]
  1131. </code></pre></div>
  1132. <div><h2 id="input"><a href="#input" name="input">#</a>Input</h2><ul>
  1133. <li><strong>Reads a line from user input or pipe if present.</strong></li>
  1134. <li><strong>Trailing newline gets stripped.</strong></li>
  1135. <li><strong>Prompt string is printed to the standard output before reading input.</strong></li>
  1136. </ul><pre><code class="python language-python hljs">&lt;str&gt; = input(prompt=<span class="hljs-keyword">None</span>)
  1137. </code></pre></div>
  1138. <div><h4 id="printslinesuntileof">Prints lines until EOF:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1139. <span class="hljs-keyword">try</span>:
  1140. print(input())
  1141. <span class="hljs-keyword">except</span> EOFError:
  1142. <span class="hljs-keyword">break</span>
  1143. </code></pre></div>
  1144. <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
  1145. script_name = sys.argv[<span class="hljs-number">0</span>]
  1146. arguments = sys.argv[<span class="hljs-number">1</span>:]
  1147. </code></pre></div>
  1148. <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
  1149. p = ArgumentParser(description=&lt;str&gt;)
  1150. 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>
  1151. 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>
  1152. 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"># Argument</span>
  1153. 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"># Arguments</span>
  1154. args = p.parse_args()
  1155. value = args.&lt;name&gt;
  1156. </code></pre></div>
  1157. <ul>
  1158. <li><strong>Use <code class="python hljs"><span class="hljs-string">'help=&lt;str&gt;'</span></code> for argument description.</strong></li>
  1159. <li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files.</strong></li>
  1160. </ul>
  1161. <div><h2 id="open"><a href="#open" name="open">#</a>Open</h2><p><strong>Opens a 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>)
  1162. </code></pre></div>
  1163. <ul>
  1164. <li><strong><code class="python hljs"><span class="hljs-string">'encoding=None'</span></code> means 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>
  1165. <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>
  1166. <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>
  1167. </ul>
  1168. <div><h3 id="modes">Modes</h3><ul>
  1169. <li><strong><code class="python hljs"><span class="hljs-string">'r'</span></code> - Read (default).</strong></li>
  1170. <li><strong><code class="python hljs"><span class="hljs-string">'w'</span></code> - Write (truncate).</strong></li>
  1171. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - Write or fail if the file already exists.</strong></li>
  1172. <li><strong><code class="python hljs"><span class="hljs-string">'a'</span></code> - Append.</strong></li>
  1173. <li><strong><code class="python hljs"><span class="hljs-string">'w+'</span></code> - Read and write (truncate).</strong></li>
  1174. <li><strong><code class="python hljs"><span class="hljs-string">'r+'</span></code> - Read and write from the start.</strong></li>
  1175. <li><strong><code class="python hljs"><span class="hljs-string">'a+'</span></code> - Read and write from the end.</strong></li>
  1176. <li><strong><code class="python hljs"><span class="hljs-string">'t'</span></code> - Text mode (default).</strong></li>
  1177. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - Binary mode.</strong></li>
  1178. </ul><div><h3 id="exceptions-1">Exceptions</h3><ul>
  1179. <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>
  1180. <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>
  1181. <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>
  1182. <li><strong><code class="python hljs"><span class="hljs-string">'OSError'</span></code> is the parent class of all listed exceptions.</strong></li>
  1183. </ul><div><h3 id="file">File</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>
  1184. &lt;file&gt;.seek(offset) <span class="hljs-comment"># Moves 'offset' chars/bytes from the start.</span>
  1185. &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>
  1186. &lt;bin_file&gt;.seek(±offset, &lt;anchor&gt;) <span class="hljs-comment"># Anchor: 0 start, 1 current pos., 2 end.</span>
  1187. </code></pre></div></div></div>
  1188. <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>
  1189. &lt;str/bytes&gt; = &lt;file&gt;.readline() <span class="hljs-comment"># Returns a line or empty string on EOF.</span>
  1190. &lt;list&gt; = &lt;file&gt;.readlines() <span class="hljs-comment"># Returns a list of remaining lines.</span>
  1191. &lt;str/bytes&gt; = next(&lt;file&gt;) <span class="hljs-comment"># Returns a line using buffer. Do not mix.</span>
  1192. </code></pre>
  1193. <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>
  1194. &lt;file&gt;.writelines(&lt;coll.&gt;) <span class="hljs-comment"># Writes a coll. of strings or bytes objects.</span>
  1195. &lt;file&gt;.flush() <span class="hljs-comment"># Flushes write buffer.</span>
  1196. </code></pre>
  1197. <ul>
  1198. <li><strong>Methods do not add or strip trailing newlines, even writelines().</strong></li>
  1199. </ul>
  1200. <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>
  1201. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1202. <span class="hljs-keyword">return</span> file.readlines()
  1203. </code></pre></div>
  1204. <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>
  1205. <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:
  1206. file.write(text)
  1207. </code></pre></div>
  1208. <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> path, listdir
  1209. <span class="hljs-keyword">from</span> glob <span class="hljs-keyword">import</span> glob
  1210. </code></pre></div>
  1211. <pre><code class="python language-python hljs">&lt;bool&gt; = path.exists(<span class="hljs-string">'&lt;path&gt;'</span>)
  1212. &lt;bool&gt; = path.isfile(<span class="hljs-string">'&lt;path&gt;'</span>)
  1213. &lt;bool&gt; = path.isdir(<span class="hljs-string">'&lt;path&gt;'</span>)
  1214. </code></pre>
  1215. <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>
  1216. &lt;list&gt; = glob(<span class="hljs-string">'&lt;pattern&gt;'</span>) <span class="hljs-comment"># Filenames matching the wildcard pattern.</span>
  1217. </code></pre>
  1218. <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
  1219. </code></pre></div>
  1220. <pre><code class="python language-python hljs">cwd = Path()
  1221. &lt;Path&gt; = Path(<span class="hljs-string">'&lt;path&gt;'</span> [, <span class="hljs-string">'&lt;path&gt;'</span>, &lt;Path&gt;, ...])
  1222. &lt;Path&gt; = &lt;Path&gt; / <span class="hljs-string">'&lt;dir&gt;'</span> / <span class="hljs-string">'&lt;file&gt;'</span>
  1223. </code></pre>
  1224. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;Path&gt;.exists()
  1225. &lt;bool&gt; = &lt;Path&gt;.is_file()
  1226. &lt;bool&gt; = &lt;Path&gt;.is_dir()
  1227. </code></pre>
  1228. <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>
  1229. &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>
  1230. </code></pre>
  1231. <pre><code class="python language-python hljs">&lt;str&gt; = str(&lt;Path&gt;) <span class="hljs-comment"># Path as a string.</span>
  1232. &lt;str&gt; = &lt;Path&gt;.name <span class="hljs-comment"># Final component.</span>
  1233. &lt;str&gt; = &lt;Path&gt;.stem <span class="hljs-comment"># Final component without extension.</span>
  1234. &lt;str&gt; = &lt;Path&gt;.suffix <span class="hljs-comment"># Final component's extension.</span>
  1235. &lt;tup.&gt; = &lt;Path&gt;.parts <span class="hljs-comment"># All components as strings.</span>
  1236. </code></pre>
  1237. <pre><code class="python language-python hljs">&lt;Path&gt; = &lt;Path&gt;.resolve() <span class="hljs-comment"># Returns absolute path without symlinks.</span>
  1238. &lt;Path&gt; = &lt;Path&gt;.parent <span class="hljs-comment"># Returns path without final component.</span>
  1239. &lt;file&gt; = open(&lt;Path&gt;) <span class="hljs-comment"># Opens a file and returns file object.</span>
  1240. </code></pre>
  1241. <div><h2 id="commandexecution"><a href="#commandexecution" name="commandexecution">#</a>Command Execution</h2><div><h3 id="filesanddirectories">Files and Directories</h3><ul>
  1242. <li><strong>Paths can be either strings, Paths, or DirEntry objects.</strong></li>
  1243. <li><strong>All exceptions are either OSError or its subclasses.</strong></li>
  1244. </ul><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os, shutil
  1245. &lt;str&gt; = os.getcwd() <span class="hljs-comment"># Returns the current working directory.</span>
  1246. os.chdir(&lt;path&gt;) <span class="hljs-comment"># Changes current working directory.</span>
  1247. </code></pre></div></div>
  1248. <pre><code class="python language-python hljs">shutil.copy(from, to) <span class="hljs-comment"># Copies the file.</span>
  1249. os.rename(from, to) <span class="hljs-comment"># Renames the file or directory.</span>
  1250. os.replace(from, to) <span class="hljs-comment"># Same, but overwrites 'to' if it exists.</span>
  1251. </code></pre>
  1252. <pre><code class="python language-python hljs">os.remove(&lt;path&gt;) <span class="hljs-comment"># Deletes the file.</span>
  1253. os.rmdir(&lt;path&gt;) <span class="hljs-comment"># Deletes empty directory.</span>
  1254. shutil.rmtree(&lt;path&gt;) <span class="hljs-comment"># Deletes the entire directory tree.</span>
  1255. </code></pre>
  1256. <pre><code class="python language-python hljs">os.mkdir(&lt;path&gt;, mode=<span class="hljs-number">0o777</span>) <span class="hljs-comment"># Creates a directory.</span>
  1257. &lt;iter&gt; = os.scandir(path=<span class="hljs-string">'.'</span>) <span class="hljs-comment"># Returns os.DirEntry objects located at path.</span>
  1258. </code></pre>
  1259. <div><h4 id="direntry">DirEntry:</h4><pre><code class="python language-python hljs">&lt;bool&gt; = &lt;DirEntry&gt;.is_file()
  1260. &lt;bool&gt; = &lt;DirEntry&gt;.is_dir()
  1261. </code></pre></div>
  1262. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;DirEntry&gt;.path <span class="hljs-comment"># Path as a string.</span>
  1263. &lt;str&gt; = &lt;DirEntry&gt;.name <span class="hljs-comment"># Final component.</span>
  1264. </code></pre>
  1265. <pre><code class="python language-python hljs">&lt;Path&gt; = Path(&lt;DirEntry&gt;) <span class="hljs-comment"># Path object.</span>
  1266. &lt;file&gt; = open(&lt;DirEntry&gt;) <span class="hljs-comment"># File object.</span>
  1267. </code></pre>
  1268. <div><h3 id="shellcommands">Shell Commands</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os
  1269. &lt;str&gt; = os.popen(<span class="hljs-string">'&lt;shell_command&gt;'</span>).read()
  1270. </code></pre></div>
  1271. <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
  1272. <span class="hljs-meta">&gt;&gt;&gt; </span>a = subprocess.run(shlex.split(<span class="hljs-string">'ls -a'</span>), stdout=subprocess.PIPE)
  1273. <span class="hljs-meta">&gt;&gt;&gt; </span>a.stdout
  1274. <span class="hljs-string">b'.\n..\nfile1.txt\nfile2.txt\n'</span>
  1275. <span class="hljs-meta">&gt;&gt;&gt; </span>a.returncode
  1276. <span class="hljs-number">0</span>
  1277. </code></pre></div>
  1278. <div><h2 id="csv"><a href="#csv" name="csv">#</a>CSV</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> csv <span class="hljs-keyword">import</span> reader, writer
  1279. </code></pre></div>
  1280. <div><h3 id="read">Read</h3><pre><code class="python language-python hljs">&lt;reader&gt; = reader(&lt;file&gt;, dialect=<span class="hljs-string">'excel'</span>, delimiter=<span class="hljs-string">','</span>)
  1281. &lt;list&gt; = next(&lt;reader&gt;) <span class="hljs-comment"># Returns next row as list of strings.</span>
  1282. </code></pre></div>
  1283. <ul>
  1284. <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>
  1285. </ul>
  1286. <div><h3 id="write">Write</h3><pre><code class="python language-python hljs">&lt;writer&gt; = writer(&lt;file&gt;, dialect=<span class="hljs-string">'excel'</span>, delimiter=<span class="hljs-string">','</span>)
  1287. &lt;writer&gt;.writerow(&lt;collection&gt;) <span class="hljs-comment"># Encodes objects using `str(&lt;el&gt;)`.</span>
  1288. &lt;writer&gt;.writerows(&lt;coll_of_coll&gt;)
  1289. </code></pre></div>
  1290. <ul>
  1291. <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>
  1292. </ul>
  1293. <div><h3 id="parameters">Parameters</h3><ul>
  1294. <li><strong><code class="python hljs"><span class="hljs-string">'dialect'</span></code> - Master parameter that sets the default values.</strong></li>
  1295. <li><strong><code class="python hljs"><span class="hljs-string">'delimiter'</span></code> - A one-character string used to separate fields.</strong></li>
  1296. <li><strong><code class="python hljs"><span class="hljs-string">'quotechar'</span></code> - Character for quoting fields that contain special characters.</strong></li>
  1297. <li><strong><code class="python hljs"><span class="hljs-string">'doublequote'</span></code> - Whether quotechars inside fields get doubled or escaped.</strong></li>
  1298. <li><strong><code class="python hljs"><span class="hljs-string">'skipinitialspace'</span></code> - Whether whitespace after delimiter gets stripped.</strong></li>
  1299. <li><strong><code class="python hljs"><span class="hljs-string">'lineterminator'</span></code> - How does writer terminate lines.</strong></li>
  1300. <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>
  1301. <li><strong><code class="python hljs"><span class="hljs-string">'escapechar'</span></code> - Character for escaping 'quotechar' if 'doublequote' is false.</strong></li>
  1302. </ul><div><h3 id="dialects">Dialects</h3><pre><code class="text language-text">+------------------+-----------+-----------+--------------+
  1303. | | excel | excel_tab | unix_dialect |
  1304. +------------------+-----------+-----------+--------------+
  1305. | delimiter | ',' | '\t' | ',' |
  1306. | quotechar | '"' | '"' | '"' |
  1307. | doublequote | True | True | True |
  1308. | skipinitialspace | False | False | False |
  1309. | lineterminator | '\r\n' | '\r\n' | '\n' |
  1310. | quoting | 0 | 0 | 1 |
  1311. | escapechar | None | None | None |
  1312. +------------------+-----------+-----------+--------------+
  1313. </code></pre></div></div>
  1314. <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>
  1315. <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:
  1316. <span class="hljs-keyword">return</span> csv.reader(file)
  1317. </code></pre></div>
  1318. <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>
  1319. <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:
  1320. writer = csv.writer(file)
  1321. writer.writerows(rows)
  1322. </code></pre></div>
  1323. <div><h2 id="json"><a href="#json" name="json">#</a>JSON</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> json
  1324. &lt;str&gt; = json.dumps(&lt;object&gt;, ensure_ascii=<span class="hljs-keyword">True</span>, indent=<span class="hljs-keyword">None</span>)
  1325. &lt;object&gt; = json.loads(&lt;str&gt;)
  1326. </code></pre></div>
  1327. <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>
  1328. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1329. <span class="hljs-keyword">return</span> json.load(file)
  1330. </code></pre></div>
  1331. <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>
  1332. <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:
  1333. json.dump(an_object, file, ensure_ascii=<span class="hljs-keyword">False</span>, indent=<span class="hljs-number">2</span>)
  1334. </code></pre></div>
  1335. <div><h2 id="pickle"><a href="#pickle" name="pickle">#</a>Pickle</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> pickle
  1336. &lt;bytes&gt; = pickle.dumps(&lt;object&gt;)
  1337. &lt;object&gt; = pickle.loads(&lt;bytes&gt;)
  1338. </code></pre></div>
  1339. <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>
  1340. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1341. <span class="hljs-keyword">return</span> pickle.load(file)
  1342. </code></pre></div>
  1343. <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>
  1344. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1345. pickle.dump(an_object, file)
  1346. </code></pre></div>
  1347. <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><pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sqlite3
  1348. db = sqlite3.connect(<span class="hljs-string">'&lt;path&gt;'</span>) <span class="hljs-comment"># Also ':memory:'.</span>
  1349. ...
  1350. db.close()
  1351. </code></pre></div>
  1352. <ul>
  1353. <li><strong>New database will be created if path doesn't exist.</strong></li>
  1354. </ul>
  1355. <div><h3 id="read-1">Read</h3><pre><code class="python language-python hljs">cursor = db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1356. <span class="hljs-keyword">if</span> cursor:
  1357. &lt;tuple&gt; = cursor.fetchone() <span class="hljs-comment"># First row. Also next(cursor).</span>
  1358. &lt;list&gt; = cursor.fetchall() <span class="hljs-comment"># Remaining rows.</span>
  1359. </code></pre></div>
  1360. <ul>
  1361. <li><strong>Returned values can be of type str, int, float, bytes or None.</strong></li>
  1362. </ul>
  1363. <div><h3 id="write-1">Write</h3><pre><code class="python language-python hljs">db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1364. db.commit()
  1365. </code></pre></div>
  1366. <div><h4 id="or">Or:</h4><pre><code class="python language-python hljs"><span class="hljs-keyword">with</span> db:
  1367. db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1368. </code></pre></div>
  1369. <div><h3 id="placeholders">Placeholders</h3><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>
  1370. 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>
  1371. db.executemany(<span class="hljs-string">'&lt;query&gt;'</span>, &lt;coll_of_above&gt;) <span class="hljs-comment"># Runs execute() many times.</span>
  1372. </code></pre></div>
  1373. <ul>
  1374. <li><strong>Passed values can be of type str, int, float, bytes, None, bool, datetime.date or datetime.datetme.</strong></li>
  1375. <li><strong>Bools will be stored and returned as ints and dates as ISO formatted strings.</strong></li>
  1376. </ul>
  1377. <div><h3 id="example">Example</h3><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>)
  1378. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'create table t (a, b, c)'</span>)
  1379. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'insert into t values (1, 2, 3)'</span>)
  1380. <span class="hljs-meta">&gt;&gt;&gt; </span>db.execute(<span class="hljs-string">'select * from t'</span>).fetchall()
  1381. [(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)]
  1382. </code></pre></div>
  1383. <ul>
  1384. <li><strong>In this example values are not actually saved because <code class="python hljs"><span class="hljs-string">'db.commit()'</span></code> was omitted.</strong> </li>
  1385. </ul>
  1386. <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>
  1387. <span class="hljs-keyword">from</span> mysql <span class="hljs-keyword">import</span> connector
  1388. db = connector.connect(host=&lt;str&gt;, user=&lt;str&gt;, password=&lt;str&gt;, database=&lt;str&gt;)
  1389. cursor = db.cursor()
  1390. cursor.execute(<span class="hljs-string">'&lt;query&gt;'</span>) <span class="hljs-comment"># Only cursor has execute method.</span>
  1391. cursor.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>
  1392. cursor.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>
  1393. </code></pre></div>
  1394. <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>
  1395. &lt;int&gt; = &lt;bytes&gt;[&lt;index&gt;] <span class="hljs-comment"># Returns int in range from 0 to 255.</span>
  1396. &lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;] <span class="hljs-comment"># Returns bytes even if it has only one element.</span>
  1397. &lt;bytes&gt; = &lt;bytes&gt;.join(&lt;coll_of_bytes&gt;) <span class="hljs-comment"># Joins elements using bytes object as separator.</span>
  1398. </code></pre></div>
  1399. <div><h3 id="encode-1">Encode</h3><pre><code class="python language-python hljs">&lt;bytes&gt; = &lt;str&gt;.encode(<span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Or: bytes(&lt;str&gt;, 'utf-8')</span>
  1400. &lt;bytes&gt; = bytes(&lt;coll_of_ints&gt;) <span class="hljs-comment"># Ints must be in range from 0 to 255.</span>
  1401. &lt;bytes&gt; = &lt;int&gt;.to_bytes(&lt;length&gt;, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1402. &lt;bytes&gt; = bytes.fromhex(<span class="hljs-string">'&lt;hex&gt;'</span>)
  1403. </code></pre></div>
  1404. <div><h3 id="decode-1">Decode</h3><pre><code class="python language-python hljs">&lt;str&gt; = &lt;bytes&gt;.decode(<span class="hljs-string">'utf-8'</span>) <span class="hljs-comment"># Or: str(&lt;bytes&gt;, 'utf-8')</span>
  1405. &lt;list&gt; = list(&lt;bytes&gt;) <span class="hljs-comment"># Returns ints in range from 0 to 255.</span>
  1406. &lt;int&gt; = int.from_bytes(&lt;bytes&gt;, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1407. <span class="hljs-string">'&lt;hex&gt;'</span> = &lt;bytes&gt;.hex()
  1408. </code></pre></div>
  1409. <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>
  1410. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1411. <span class="hljs-keyword">return</span> file.read()
  1412. </code></pre></div>
  1413. <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>
  1414. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1415. file.write(bytes_obj)
  1416. </code></pre></div>
  1417. <div><h2 id="struct"><a href="#struct" name="struct">#</a>Struct</h2><ul>
  1418. <li><strong>Module that performs conversions between a sequence of numbers and a C struct, represented as a Python bytes object.</strong></li>
  1419. <li><strong>Machine’s native type sizes and byte order are used by default.</strong></li>
  1420. </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, calcsize
  1421. &lt;bytes&gt; = pack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;num_1&gt; [, &lt;num_2&gt;, ...])
  1422. &lt;tuple&gt; = unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1423. &lt;tuples&gt; = iter_unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1424. </code></pre></div>
  1425. <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>)
  1426. <span class="hljs-string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>
  1427. <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>)
  1428. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  1429. </code></pre></div>
  1430. <div><h3 id="format-2">Format</h3><div><h4 id="forstandardsizesstartformatstringwith">For standard sizes start format string with:</h4><ul>
  1431. <li><strong><code class="python hljs"><span class="hljs-string">'='</span></code> - native byte order</strong></li>
  1432. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;'</span></code> - little-endian</strong></li>
  1433. <li><strong><code class="python hljs"><span class="hljs-string">'&gt;'</span></code> - big-endian</strong></li>
  1434. </ul><div><h4 id="integertypesusecapitalletterforunsignedtypestandardsizesareinbrackets">Integer types. Use capital letter for unsigned type. Standard sizes are in brackets:</h4><ul>
  1435. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - pad byte</strong></li>
  1436. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - char (1)</strong></li>
  1437. <li><strong><code class="python hljs"><span class="hljs-string">'h'</span></code> - short (2)</strong></li>
  1438. <li><strong><code class="python hljs"><span class="hljs-string">'i'</span></code> - int (4)</strong></li>
  1439. <li><strong><code class="python hljs"><span class="hljs-string">'l'</span></code> - long (4)</strong></li>
  1440. <li><strong><code class="python hljs"><span class="hljs-string">'q'</span></code> - long long (8)</strong></li>
  1441. </ul><div><h4 id="floatingpointtypes">Floating point types:</h4><ul>
  1442. <li><strong><code class="python hljs"><span class="hljs-string">'f'</span></code> - float (4)</strong></li>
  1443. <li><strong><code class="python hljs"><span class="hljs-string">'d'</span></code> - double (8)</strong></li>
  1444. </ul></div></div></div></div>
  1445. <div><h2 id="array"><a href="#array" name="array">#</a>Array</h2><p><strong>List that can only hold numbers of 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
  1446. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span> [, &lt;collection&gt;])
  1447. </code></pre></div>
  1448. <div><h2 id="memoryview"><a href="#memoryview" name="memoryview">#</a>Memory View</h2><p><strong>Used for accessing the internal data of an object that supports the buffer protocol.</strong></p><pre><code class="python language-python hljs">&lt;memoryview&gt; = memoryview(&lt;bytes&gt; / &lt;bytearray&gt; / &lt;array&gt;)
  1449. &lt;memoryview&gt;.release()
  1450. </code></pre></div>
  1451. <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
  1452. &lt;deque&gt; = deque(&lt;collection&gt;, maxlen=<span class="hljs-keyword">None</span>)
  1453. </code></pre></div>
  1454. <pre><code class="python language-python hljs">&lt;deque&gt;.appendleft(&lt;el&gt;)
  1455. &lt;el&gt; = &lt;deque&gt;.popleft()
  1456. &lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Collection gets reversed.</span>
  1457. &lt;deque&gt;.rotate(n=<span class="hljs-number">1</span>) <span class="hljs-comment"># Rotates elements to the right.</span>
  1458. </code></pre>
  1459. <div><h3 id="example-2">Example</h3><pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>a = deque([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>], maxlen=<span class="hljs-number">3</span>)
  1460. <span class="hljs-meta">&gt;&gt;&gt; </span>a.append(<span class="hljs-number">4</span>)
  1461. [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
  1462. <span class="hljs-meta">&gt;&gt;&gt; </span>a.appendleft(<span class="hljs-number">5</span>)
  1463. [<span class="hljs-number">5</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  1464. <span class="hljs-meta">&gt;&gt;&gt; </span>a.insert(<span class="hljs-number">1</span>, <span class="hljs-number">6</span>)
  1465. IndexError: deque already at its maximum size
  1466. </code></pre></div>
  1467. <div><h2 id="threading"><a href="#threading" name="threading">#</a>Threading</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> threading <span class="hljs-keyword">import</span> Thread, RLock
  1468. </code></pre></div>
  1469. <div><h3 id="thread">Thread</h3><pre><code class="python language-python hljs">thread = Thread(target=&lt;function&gt;, args=(&lt;first_arg&gt;, ))
  1470. thread.start()
  1471. ...
  1472. thread.join()
  1473. </code></pre></div>
  1474. <div><h3 id="lock">Lock</h3><pre><code class="python language-python hljs">lock = RLock()
  1475. lock.acquire()
  1476. ...
  1477. lock.release()
  1478. </code></pre></div>
  1479. <div><h4 id="or-1">Or:</h4><pre><code class="python language-python hljs">lock = RLock()
  1480. <span class="hljs-keyword">with</span> lock:
  1481. ...
  1482. </code></pre></div>
  1483. <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>
  1484. &lt;dict&gt; = locals() <span class="hljs-comment"># Dict of local variables. Also vars().</span>
  1485. &lt;dict&gt; = globals() <span class="hljs-comment"># Dict of global variables.</span>
  1486. </code></pre></div></div>
  1487. <div><h3 id="attributes-1">Attributes</h3><pre><code class="python language-python hljs">&lt;dict&gt; = vars(&lt;object&gt;)
  1488. &lt;bool&gt; = hasattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1489. value = getattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1490. setattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>, value)
  1491. </code></pre></div>
  1492. <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
  1493. &lt;sig&gt; = signature(&lt;function&gt;)
  1494. no_of_params = len(&lt;sig&gt;.parameters)
  1495. param_names = list(&lt;sig&gt;.parameters.keys())
  1496. </code></pre></div>
  1497. <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">&lt;<span class="hljs-class"><span class="hljs-keyword">class</span>&gt; = <span class="hljs-title">type</span><span class="hljs-params">(&lt;class_name&gt;, &lt;parents_tuple&gt;, &lt;attributes_dict&gt;)</span>
  1498. </span></code></pre></div></div>
  1499. <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>})
  1500. <span class="hljs-meta">&gt;&gt;&gt; </span>z = Z()
  1501. </code></pre>
  1502. <div><h3 id="metaclass">Meta Class</h3><p><strong>Class that creates class.</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>
  1503. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1504. <span class="hljs-keyword">return</span> type(name, parents, attrs)
  1505. </code></pre></div>
  1506. <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>
  1507. <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>
  1508. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1509. <span class="hljs-keyword">return</span> type.__new__(cls, name, parents, attrs)
  1510. </code></pre></div>
  1511. <ul>
  1512. <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>
  1513. <li><strong>It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (</strong><code class="python hljs"><span class="hljs-string">'MyMetaClass'</span></code> <strong>in our case).</strong></li>
  1514. <li><strong>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>), in which case init() is not called.</strong></li>
  1515. </ul>
  1516. <div><h3 id="metaclassattribute">Metaclass Attribute</h3><p><strong>Right before a class is created it checks if it has metaclass 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>
  1517. b = <span class="hljs-number">12345</span>
  1518. </code></pre></div>
  1519. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>MyClass.a, MyClass.b
  1520. (<span class="hljs-string">'abcde'</span>, <span class="hljs-number">12345</span>)
  1521. </code></pre>
  1522. <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>
  1523. type(MyMetaClass) == type <span class="hljs-comment"># MyMetaClass is an instance of type.</span>
  1524. </code></pre></div>
  1525. <pre><code class="text language-text">+---------+-------------+
  1526. | Classes | Metaclasses |
  1527. +---------+-------------|
  1528. | MyClass &gt; MyMetaClass |
  1529. | | v |
  1530. | object ---&gt; type &lt;+ |
  1531. | | ^ +---+ |
  1532. | str -------+ |
  1533. +---------+-------------+
  1534. </code></pre>
  1535. <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>
  1536. MyMetaClass.__base__ == type <span class="hljs-comment"># MyMetaClass is a subclass of type.</span>
  1537. </code></pre></div>
  1538. <pre><code class="text language-text">+---------+-------------+
  1539. | Classes | Metaclasses |
  1540. +---------+-------------|
  1541. | MyClass | MyMetaClass |
  1542. | v | v |
  1543. | object &lt;--- type |
  1544. | ^ | |
  1545. | str | |
  1546. +---------+-------------+
  1547. </code></pre>
  1548. <div><h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2><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
  1549. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge
  1550. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> and_, or_, not_
  1551. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller
  1552. </code></pre></div>
  1553. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  1554. sorted_by_second = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>))
  1555. sorted_by_both = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>))
  1556. product_of_elems = functools.reduce(op.mul, &lt;collection&gt;)
  1557. 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_})
  1558. last_el = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;)
  1559. </code></pre>
  1560. <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
  1561. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'1 + 2'</span>)
  1562. <span class="hljs-number">3</span>
  1563. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'[1, 2, 3]'</span>)
  1564. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  1565. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'abs(1)'</span>)
  1566. ValueError: malformed node or string
  1567. </code></pre></div>
  1568. <div><h2 id="coroutine"><a href="#coroutine" name="coroutine">#</a>Coroutine</h2><ul>
  1569. <li><strong>Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().</strong></li>
  1570. <li><strong>Coroutines provide more powerful data routing possibilities than iterators.</strong></li>
  1571. <li><strong>If you build a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.</strong></li>
  1572. </ul><div><h3 id="helperdecorator">Helper Decorator</h3><ul>
  1573. <li><strong>All coroutines must be "primed" by first calling next().</strong></li>
  1574. <li><strong>Remembering to call next() is easy to forget.</strong></li>
  1575. <li><strong>Solved by wrapping coroutines with a decorator:</strong></li>
  1576. </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>
  1577. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  1578. cr = func(*args, **kwargs)
  1579. next(cr)
  1580. <span class="hljs-keyword">return</span> cr
  1581. <span class="hljs-keyword">return</span> out
  1582. </code></pre></div></div>
  1583. <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>
  1584. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  1585. target.send(i)
  1586. target.close()
  1587. <span class="hljs-meta">@coroutine</span>
  1588. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">adder</span><span class="hljs-params">(target)</span>:</span>
  1589. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1590. value = (<span class="hljs-keyword">yield</span>)
  1591. target.send(value + <span class="hljs-number">100</span>)
  1592. <span class="hljs-meta">@coroutine</span>
  1593. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">printer</span><span class="hljs-params">()</span>:</span>
  1594. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1595. value = (<span class="hljs-keyword">yield</span>)
  1596. print(value)
  1597. reader(adder(printer())) <span class="hljs-comment"># 100, 101, ..., 109</span>
  1598. </code></pre></div>
  1599. <p><br><br></p>
  1600. <div class="pagebreak"></div><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>
  1601. <span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm
  1602. <span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep
  1603. <span class="hljs-keyword">for</span> i <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>]):
  1604. sleep(<span class="hljs-number">0.2</span>)
  1605. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> tqdm(range(<span class="hljs-number">100</span>)):
  1606. sleep(<span class="hljs-number">0.02</span>)
  1607. </code></pre></div></div>
  1608. <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>
  1609. <span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot
  1610. pyplot.plot(&lt;data_1&gt; [, &lt;data_2&gt;, ...]) <span class="hljs-comment"># Or: hist(&lt;data&gt;).</span>
  1611. pyplot.savefig(&lt;filename&gt;)
  1612. pyplot.show()
  1613. pyplot.clf() <span class="hljs-comment"># Clears figure.</span>
  1614. </code></pre></div>
  1615. <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>
  1616. <span class="hljs-keyword">from</span> tabulate <span class="hljs-keyword">import</span> tabulate
  1617. <span class="hljs-keyword">import</span> csv
  1618. <span class="hljs-keyword">with</span> open(&lt;filename&gt;, encoding=<span class="hljs-string">'utf-8'</span>, newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> file:
  1619. lines = csv.reader(file)
  1620. headers = [header.title() <span class="hljs-keyword">for</span> header <span class="hljs-keyword">in</span> next(lines)]
  1621. table = tabulate(lines, headers)
  1622. print(table)
  1623. </code></pre></div></div>
  1624. <div><h2 id="curses"><a href="#curses" name="curses">#</a>Curses</h2><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> wrapper, ascii
  1625. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1626. wrapper(draw)
  1627. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen)</span>:</span>
  1628. screen.clear()
  1629. screen.addstr(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Press ESC to quit.'</span>)
  1630. <span class="hljs-keyword">while</span> screen.getch() != ascii.ESC:
  1631. <span class="hljs-keyword">pass</span>
  1632. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_border</span><span class="hljs-params">(screen)</span>:</span>
  1633. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1634. P = namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'y x'</span>)
  1635. height, width = screen.getmaxyx()
  1636. <span class="hljs-keyword">return</span> P(height<span class="hljs-number">-1</span>, width<span class="hljs-number">-1</span>)
  1637. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1638. main()
  1639. </code></pre></div>
  1640. <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>
  1641. <span class="hljs-keyword">from</span> loguru <span class="hljs-keyword">import</span> logger
  1642. </code></pre></div>
  1643. <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>
  1644. 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>
  1645. logger.&lt;level&gt;(<span class="hljs-string">'A logging message.'</span>)
  1646. </code></pre>
  1647. <ul>
  1648. <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>
  1649. </ul>
  1650. <div><h3 id="exceptions-2">Exceptions</h3><p><strong>Error 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>:
  1651. ...
  1652. <span class="hljs-keyword">except</span> &lt;exception&gt;:
  1653. logger.exception(<span class="hljs-string">'An error happened.'</span>)
  1654. </code></pre></div>
  1655. <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;
  1656. </code></pre></div>
  1657. <ul>
  1658. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max file size in bytes.</strong></li>
  1659. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1660. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;time&gt;'</span></code> - Time of day.</strong></li>
  1661. <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>
  1662. </ul>
  1663. <div><h3 id="retention">Retention</h3><p><strong>Sets a condition which old log files are deleted.</strong></p><pre><code class="python language-python hljs">retention=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;str&gt;
  1664. </code></pre></div>
  1665. <ul>
  1666. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max number of files.</strong></li>
  1667. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1668. <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>
  1669. </ul>
  1670. <div><h2 id="scraping"><a href="#scraping" name="scraping">#</a>Scraping</h2><div><h4 id="scrapesandprintspythonsurlandversionnumberfromwikipedia">Scrapes and prints Python's URL and version number from Wikipedia:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests beautifulsoup4</span>
  1671. <span class="hljs-keyword">import</span> requests
  1672. <span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
  1673. url = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span>
  1674. html = requests.get(url).text
  1675. doc = BeautifulSoup(html, <span class="hljs-string">'html.parser'</span>)
  1676. table = doc.find(<span class="hljs-string">'table'</span>, class_=<span class="hljs-string">'infobox vevent'</span>)
  1677. rows = table.find_all(<span class="hljs-string">'tr'</span>)
  1678. link = rows[<span class="hljs-number">11</span>].find(<span class="hljs-string">'a'</span>)[<span class="hljs-string">'href'</span>]
  1679. ver = rows[<span class="hljs-number">6</span>].find(<span class="hljs-string">'div'</span>).text.split()[<span class="hljs-number">0</span>]
  1680. print(link, ver)
  1681. </code></pre></div></div>
  1682. <div><h4 id="downloadspythonslogo">Downloads Python's logo:</h4><pre><code class="python language-python hljs">url_img = rows[<span class="hljs-number">0</span>].find(<span class="hljs-string">'img'</span>)[<span class="hljs-string">'src'</span>]
  1683. image = requests.get(<span class="hljs-string">f'https:<span class="hljs-subst">{url_img}</span>'</span>).content
  1684. <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:
  1685. file.write(image)
  1686. </code></pre></div>
  1687. <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>
  1688. <span class="hljs-keyword">from</span> bottle <span class="hljs-keyword">import</span> run, route, post, template, request, response
  1689. <span class="hljs-keyword">import</span> json
  1690. </code></pre></div>
  1691. <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>)
  1692. run(host=<span class="hljs-string">'0.0.0.0'</span>, port=<span class="hljs-number">80</span>, server=<span class="hljs-string">'cherrypy'</span>)
  1693. </code></pre></div>
  1694. <div><h3 id="staticrequest">Static Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/img/&lt;image&gt;')</span>
  1695. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_image</span><span class="hljs-params">(image)</span>:</span>
  1696. <span class="hljs-keyword">return</span> static_file(image, <span class="hljs-string">'images/'</span>, mimetype=<span class="hljs-string">'image/png'</span>)
  1697. </code></pre></div>
  1698. <div><h3 id="dynamicrequest">Dynamic Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@route('/&lt;sport&gt;')</span>
  1699. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_page</span><span class="hljs-params">(sport)</span>:</span>
  1700. <span class="hljs-keyword">return</span> template(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
  1701. </code></pre></div>
  1702. <div><h3 id="restrequest">REST Request</h3><pre><code class="python language-python hljs"><span class="hljs-meta">@post('/odds/&lt;sport&gt;')</span>
  1703. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">odds_handler</span><span class="hljs-params">(sport)</span>:</span>
  1704. team = request.forms.get(<span class="hljs-string">'team'</span>)
  1705. home_odds, away_odds = <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>
  1706. response.headers[<span class="hljs-string">'Content-Type'</span>] = <span class="hljs-string">'application/json'</span>
  1707. response.headers[<span class="hljs-string">'Cache-Control'</span>] = <span class="hljs-string">'no-cache'</span>
  1708. <span class="hljs-keyword">return</span> json.dumps([team, home_odds, away_odds])
  1709. </code></pre></div>
  1710. <div><h4 id="test">Test:</h4><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests</span>
  1711. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests
  1712. <span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:8080/odds/football'</span>
  1713. <span class="hljs-meta">&gt;&gt;&gt; </span>data = {<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>}
  1714. <span class="hljs-meta">&gt;&gt;&gt; </span>response = requests.post(url, data=data)
  1715. <span class="hljs-meta">&gt;&gt;&gt; </span>response.json()
  1716. [<span class="hljs-string">'arsenal f.c.'</span>, <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>]
  1717. </code></pre></div>
  1718. <div><h2 id="profile"><a href="#profile" name="profile">#</a>Profile</h2><div><h3 id="basic">Basic</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> time
  1719. start_time = time() <span class="hljs-comment"># Seconds since Epoch.</span>
  1720. ...
  1721. duration = time() - start_time
  1722. </code></pre></div></div>
  1723. <div><h3 id="highperformance">High Performance</h3><pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> perf_counter <span class="hljs-keyword">as</span> pc
  1724. start_time = pc() <span class="hljs-comment"># Seconds since restart.</span>
  1725. ...
  1726. duration = pc() - start_time
  1727. </code></pre></div>
  1728. <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
  1729. <span class="hljs-meta">&gt;&gt;&gt; </span>timeit(<span class="hljs-string">'"-".join(str(a) for a in range(100))'</span>,
  1730. <span class="hljs-meta">... </span> number=<span class="hljs-number">10000</span>, globals=globals(), setup=<span class="hljs-string">'pass'</span>)
  1731. <span class="hljs-number">0.34986</span>
  1732. </code></pre></div>
  1733. <div><h3 id="lineprofiler">Line Profiler</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install line_profiler</span>
  1734. <span class="hljs-meta">@profile</span>
  1735. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1736. a = [*range(<span class="hljs-number">10000</span>)]
  1737. b = {*range(<span class="hljs-number">10000</span>)}
  1738. main()
  1739. </code></pre></div>
  1740. <div><h4 id="usage">Usage:</h4><pre><code class="text language-text">$ kernprof -lv test.py
  1741. Line # Hits Time Per Hit % Time Line Contents
  1742. ==============================================================
  1743. 1 @profile
  1744. 2 def main():
  1745. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1746. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1747. </code></pre></div>
  1748. <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>
  1749. <span class="hljs-keyword">from</span> pycallgraph <span class="hljs-keyword">import</span> output, PyCallGraph
  1750. <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
  1751. time_str = datetime.now().strftime(<span class="hljs-string">'%Y%m%d%H%M%S'</span>)
  1752. filename = <span class="hljs-string">f'profile-<span class="hljs-subst">{time_str}</span>.png'</span>
  1753. drawer = output.GraphvizOutput(output_file=filename)
  1754. <span class="hljs-keyword">with</span> PyCallGraph(drawer):
  1755. &lt;code_to_be_profiled&gt;
  1756. </code></pre></div></div>
  1757. <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>
  1758. <span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
  1759. </code></pre></div>
  1760. <pre><code class="python language-python hljs">&lt;array&gt; = np.array(&lt;list&gt;)
  1761. &lt;array&gt; = np.arange(from_inclusive, to_exclusive, ±step_size)
  1762. &lt;array&gt; = np.ones(&lt;shape&gt;)
  1763. &lt;array&gt; = np.random.randint(from_inclusive, to_exclusive, &lt;shape&gt;)
  1764. </code></pre>
  1765. <pre><code class="python language-python hljs">&lt;array&gt;.shape = &lt;shape&gt;
  1766. &lt;view&gt; = &lt;array&gt;.reshape(&lt;shape&gt;)
  1767. &lt;view&gt; = np.broadcast_to(&lt;array&gt;, &lt;shape&gt;)
  1768. </code></pre>
  1769. <pre><code class="python language-python hljs">&lt;array&gt; = &lt;array&gt;.sum(axis)
  1770. indexes = &lt;array&gt;.argmin(axis)
  1771. </code></pre>
  1772. <ul>
  1773. <li><strong>Shape is a tuple of dimension sizes.</strong></li>
  1774. <li><strong>Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.</strong></li>
  1775. </ul>
  1776. <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>
  1777. &lt;1d_view&gt; = &lt;2d_array&gt;[0] <span class="hljs-comment"># First row.</span>
  1778. &lt;1d_view&gt; = &lt;2d_array&gt;[:, 0] <span class="hljs-comment"># First column. Also [..., 0].</span>
  1779. &lt;3d_view&gt; = &lt;2d_array&gt;[None, :, :] <span class="hljs-comment"># Expanded by dimension of size 1.</span>
  1780. </code></pre></div>
  1781. <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;]
  1782. &lt;2d_array&gt; = &lt;2d_array&gt;[&lt;2d_row_indexes&gt;, &lt;2d_column_indexes&gt;]
  1783. </code></pre>
  1784. <pre><code class="bash language-bash hljs">&lt;2d_bools&gt; = &lt;2d_array&gt; &gt; 0
  1785. &lt;1d_array&gt; = &lt;2d_array&gt;[&lt;2d_bools&gt;]
  1786. </code></pre>
  1787. <ul>
  1788. <li><strong>If row and column indexes differ in shape, they are combined with broadcasting.</strong></li>
  1789. </ul>
  1790. <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>
  1791. 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>
  1792. </code></pre></div>
  1793. <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>
  1794. 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>
  1795. </code></pre></div>
  1796. <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>
  1797. 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>
  1798. </code></pre></div>
  1799. <div><h4 id="3ifneithernonmatchingdimensionhassize1riseanerror">3. If neither non-matching dimension has size 1, rise an error.</h4><div><h3 id="example-3">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>])
  1800. [ <span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>]
  1801. <span class="hljs-meta">&gt;&gt;&gt; </span>wrapped_points = points.reshape(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>)
  1802. [[ <span class="hljs-number">0.1</span>],
  1803. [ <span class="hljs-number">0.6</span>],
  1804. [ <span class="hljs-number">0.8</span>]]
  1805. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = wrapped_points - points
  1806. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">-0.5</span>, <span class="hljs-number">-0.7</span>],
  1807. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">-0.2</span>],
  1808. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1809. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = np.abs(distances)
  1810. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1811. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">0.2</span>],
  1812. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1813. <span class="hljs-meta">&gt;&gt;&gt; </span>i = np.arange(<span class="hljs-number">3</span>)
  1814. [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
  1815. <span class="hljs-meta">&gt;&gt;&gt; </span>distances[i, i] = np.inf
  1816. [[ inf, <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1817. [ <span class="hljs-number">0.5</span>, inf, <span class="hljs-number">0.2</span>],
  1818. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, inf]]
  1819. <span class="hljs-meta">&gt;&gt;&gt; </span>distances.argmin(<span class="hljs-number">1</span>)
  1820. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]
  1821. </code></pre></div></div></div>
  1822. <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>
  1823. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image
  1824. </code></pre></div>
  1825. <div><h4 id="createsapngimageofarainbowgradient">Creates a PNG image of a rainbow gradient:</h4><pre><code class="python language-python hljs">width = <span class="hljs-number">100</span>
  1826. height = <span class="hljs-number">100</span>
  1827. size = width * height
  1828. pixels = [<span class="hljs-number">255</span> * i/size <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(size)]
  1829. img = Image.new(<span class="hljs-string">'HSV'</span>, (width, height))
  1830. img.putdata([(int(a), <span class="hljs-number">255</span>, <span class="hljs-number">255</span>) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> pixels])
  1831. img.convert(mode=<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1832. </code></pre></div>
  1833. <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
  1834. 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>)))
  1835. img = Image.open(<span class="hljs-string">'test.png'</span>).convert(mode=<span class="hljs-string">'HSV'</span>)
  1836. img.putdata([(add_noise(h), s, v) <span class="hljs-keyword">for</span> h, s, v <span class="hljs-keyword">in</span> img.getdata()])
  1837. img.convert(mode=<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1838. </code></pre></div>
  1839. <div><h3 id="modes-1">Modes</h3><ul>
  1840. <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>
  1841. <li><strong><code class="python hljs"><span class="hljs-string">'L'</span></code> - 8-bit pixels, greyscale.</strong></li>
  1842. <li><strong><code class="python hljs"><span class="hljs-string">'RGB'</span></code> - 3x8-bit pixels, true color.</strong></li>
  1843. <li><strong><code class="python hljs"><span class="hljs-string">'RGBA'</span></code> - 4x8-bit pixels, true color with transparency mask.</strong></li>
  1844. <li><strong><code class="python hljs"><span class="hljs-string">'HSV'</span></code> - 3x8-bit pixels, Hue, Saturation, Value color space.</strong></li>
  1845. </ul></div>
  1846. <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
  1847. <span class="hljs-keyword">from</span> struct <span class="hljs-keyword">import</span> pack, iter_unpack
  1848. </code></pre></div>
  1849. <div><h3 id="readframesfromwavfile">Read Frames 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>
  1850. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> wf:
  1851. frames = wf.readframes(wf.getnframes())
  1852. <span class="hljs-keyword">return</span> [a[<span class="hljs-number">0</span>] <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> iter_unpack(<span class="hljs-string">'&lt;h'</span>, frames)]
  1853. </code></pre></div>
  1854. <div><h3 id="writeframestowavfile">Write Frames 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, frames_int, mono=True)</span>:</span>
  1855. frames_short = (pack(<span class="hljs-string">'&lt;h'</span>, a) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> frames_int)
  1856. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> wf:
  1857. wf.setnchannels(<span class="hljs-number">1</span> <span class="hljs-keyword">if</span> mono <span class="hljs-keyword">else</span> <span class="hljs-number">2</span>)
  1858. wf.setsampwidth(<span class="hljs-number">2</span>)
  1859. wf.setframerate(<span class="hljs-number">44100</span>)
  1860. wf.writeframes(<span class="hljs-string">b''</span>.join(frames_short))
  1861. </code></pre></div>
  1862. <div><h3 id="examples">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
  1863. frames_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>))
  1864. frames_i = (int(a * <span class="hljs-number">30000</span>) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> frames_f)
  1865. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, frames_i)
  1866. </code></pre></div></div>
  1867. <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> randint
  1868. add_noise = <span class="hljs-keyword">lambda</span> value: max(<span class="hljs-number">-32768</span>, min(<span class="hljs-number">32767</span>, value + randint(<span class="hljs-number">-500</span>, <span class="hljs-number">500</span>)))
  1869. frames_i = (add_noise(a) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> read_wav_file(<span class="hljs-string">'test.wav'</span>))
  1870. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, frames_i)
  1871. </code></pre></div>
  1872. <div><h3 id="synthesizer">Synthesizer</h3><pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install simpleaudio</span>
  1873. <span class="hljs-keyword">import</span> simpleaudio, math, struct
  1874. <span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain, repeat
  1875. F = <span class="hljs-number">44100</span>
  1876. P1 = <span class="hljs-string">'71♪,69,,71♪,66,,62♪,66,,59♪,,,'</span>
  1877. P2 = <span class="hljs-string">'71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'</span>
  1878. get_pause = <span class="hljs-keyword">lambda</span> seconds: repeat(<span class="hljs-number">0</span>, int(seconds * F))
  1879. sin_f = <span class="hljs-keyword">lambda</span> i, hz: math.sin(i * <span class="hljs-number">2</span> * math.pi * hz / F)
  1880. 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)))
  1881. 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>)
  1882. 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>)
  1883. get_frames = <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>)
  1884. frames_f = chain.from_iterable(get_frames(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>))
  1885. frames_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> frames_f)
  1886. simpleaudio.play_buffer(frames_b, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, F)
  1887. </code></pre></div>
  1888. <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>
  1889. <span class="hljs-comment">#</span>
  1890. <span class="hljs-comment"># Usage: .py</span>
  1891. <span class="hljs-comment">#</span>
  1892. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1893. <span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> make_dataclass
  1894. <span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  1895. <span class="hljs-keyword">import</span> re
  1896. <span class="hljs-keyword">import</span> sys
  1897. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1898. <span class="hljs-keyword">pass</span>
  1899. <span class="hljs-comment">###</span>
  1900. <span class="hljs-comment">## UTIL</span>
  1901. <span class="hljs-comment">#</span>
  1902. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
  1903. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1904. <span class="hljs-keyword">return</span> file.readlines()
  1905. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1906. main()
  1907. </code></pre></div>
  1908. <footer>
  1909. <aside>March 14, 2018</aside>
  1910. <a href="../" rel="author">Jure Šorn</a>
  1911. </footer>
  1912. <br>
  1913. <br>
  1914. <br>
  1915. <script src="web/jquery-3.4.0.min.js"></script>
  1916. <script src="web/script_2.js"></script>
  1917. </body>
  1918. </html>