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.

1756 lines
143 KiB

6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 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. <link rel="icon" href="web/favicon.png">
  8. <link rel="stylesheet" href="web/default.min.css">
  9. <meta name="twitter:card" content="summary">
  10. <meta name="twitter:title" content="Comprehensive Python Cheatsheet">
  11. <meta name="twitter:description" content="Exhaustive, simple, beautiful and concise. A truly pythonic cheat sheet about Python programming language.">
  12. <meta name="twitter:image" content="https://gto76.github.io/python-cheatsheet/web/image_twitter_card_2.jpeg">
  13. </head>
  14. <style>
  15. @import url(web/style.css);
  16. .join,
  17. .link,
  18. .node rect {
  19. fill: none;
  20. stroke: #636363;
  21. stroke-width: 1.5px;
  22. }
  23. .link {
  24. stroke: #969696;
  25. }
  26. .node rect {
  27. fill: white;
  28. }
  29. .link path,
  30. .node rect,
  31. .node text,
  32. .join {
  33. -webkit-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  34. -moz-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  35. -ms-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  36. -o-transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  37. transition: stroke-opacity 500ms linear, fill-opacity 500ms linear;
  38. }
  39. .node .element rect {
  40. fill: #bdbdbd;
  41. stroke: none;
  42. }
  43. .node .null rect {
  44. fill: none;
  45. stroke: none;
  46. }
  47. .node .null text {
  48. fill: #636363;
  49. }
  50. .node .selection rect {
  51. stroke: #e6550d;
  52. }
  53. .node .data rect {
  54. stroke: #3182bd;
  55. }
  56. .node .datum rect {
  57. fill: #d9d9d9;
  58. stroke: none;
  59. }
  60. .node .code text {
  61. font-family: monospace;
  62. }
  63. .node .key rect {
  64. fill: #a1d99b;
  65. stroke: none;
  66. }
  67. .link .to-key,
  68. .join {
  69. stroke: #a1d99b;
  70. }
  71. .join {
  72. stroke-dasharray: 2,2;
  73. }
  74. .link .to-null {
  75. stroke-dasharray: .5,3.5;
  76. stroke-linecap: round;
  77. }
  78. .link .from-data {
  79. stroke: #3182bd;
  80. }
  81. .play circle {
  82. fill: #fff;
  83. stroke: #000;
  84. stroke-width: 3px;
  85. }
  86. .play:hover path {
  87. fill: #f00;
  88. }
  89. .play.mousedown circle {
  90. fill: #f00;
  91. }
  92. .play.mousedown path {
  93. fill: #fff;
  94. }
  95. .play rect {
  96. fill: none;
  97. pointer-events: all;
  98. cursor: pointer;
  99. }
  100. code span {
  101. -webkit-transition: background 250ms linear;
  102. -moz-transition: background 250ms linear;
  103. -ms-transition: background 250ms linear;
  104. -o-transition: background 250ms linear;
  105. transition: background 250ms linear;
  106. }
  107. pre.prettyprint, code.prettyprint {
  108. background-color: #222;
  109. border-radius: 8px;
  110. font-size: 15px;
  111. }
  112. pre.prettyprint {
  113. width: 90%;
  114. margin: 0.5em;
  115. padding: 1em;
  116. white-space: pre-wrap;
  117. }
  118. </style>
  119. <body>
  120. <header>
  121. <aside>March 14, 2018</aside>
  122. <a href="../" rel="author">Jure Šorn</a>
  123. </header>
  124. <h1 id="comprehensivepythoncheatsheet">Comprehensive Python Cheatsheet</h1>
  125. <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>.
  126. </sup></p>
  127. <p class="banner"><img src="web/image_888.jpeg" alt="Monty Python"></p>
  128. <br><h2 id="toc"><a href="#toc" name="toc">#</a>Contents</h2>
  129. <pre><code class="hljs bash"><strong>ToC</strong> = {
  130. <strong><span class="hljs-string"><span class="hljs-string">'1. Collections'</span></span></strong>: [<a href="#list">List</a>, <a href="#dictionary">Dict</a>, <a href="#set">Set</a>, <a href="#range">Range</a>, <a href="#enumerate">Enumerate</a>, <a href="#namedtuple">Namedtuple</a>, <a href="#iterator">Iterator</a>, <a href="#generator">Generator</a>],
  131. <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">Regex</a>, <a href="#format">Format</a>, <a href="#numbers">Numbers</a>, <a href="#combinatorics">Combinatorics</a>, <a href="#datetime">Datetime</a>ᴺᴱᵂ],
  132. <strong><span class="hljs-string"><span class="hljs-string">'3. Syntax'</span></span></strong>: [<a href="#arguments">Arguments</a>, <a href="#splatoperator">Splat</a>, <a href="#inline">Inline</a>, <a href="#closure">Closure</a>, <a href="#decorator">Decorator</a>, <a href="#class">Class</a>, <a href="#enum">Enum</a>, <a href="#exceptions">Exceptions</a>],
  133. <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>],
  134. <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>],
  135. <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>],
  136. <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>,
  137. <a href="#numpy">NumPy</a>, <a href="#image">Image</a>, <a href="#audio">Audio</a>]
  138. }
  139. </code></pre>
  140. <h2 id="main"><a href="#main" name="main">#</a>Main</h2>
  141. <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>
  142. main()
  143. </code></pre>
  144. <h2 id="list"><a href="#list" name="list">#</a>List</h2>
  145. <pre><code class="python language-python hljs">&lt;list&gt; = &lt;list&gt;[from_inclusive : to_exclusive : ±step_size]
  146. </code></pre>
  147. <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>
  148. &lt;list&gt;.extend(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;list&gt; += &lt;collection&gt;</span>
  149. </code></pre>
  150. <pre><code class="python language-python hljs">&lt;list&gt;.sort()
  151. &lt;list&gt;.reverse()
  152. &lt;list&gt; = sorted(&lt;collection&gt;)
  153. &lt;iter&gt; = reversed(&lt;list&gt;)
  154. </code></pre>
  155. <pre><code class="python language-python hljs">sum_of_elements = sum(&lt;collection&gt;)
  156. elementwise_sum = [sum(pair) <span class="hljs-keyword">for</span> pair <span class="hljs-keyword">in</span> zip(list_a, list_b)]
  157. sorted_by_second = sorted(&lt;collection&gt;, key=<span class="hljs-keyword">lambda</span> el: el[<span class="hljs-number">1</span>])
  158. 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>]))
  159. flatter_list = list(itertools.chain.from_iterable(&lt;list&gt;))
  160. product_of_elems = functools.reduce(<span class="hljs-keyword">lambda</span> out, x: out * x, &lt;collection&gt;)
  161. list_of_chars = list(&lt;str&gt;)
  162. </code></pre>
  163. <pre><code class="python language-python hljs">index = &lt;list&gt;.index(&lt;el&gt;) <span class="hljs-comment"># Returns first index of item.</span>
  164. &lt;list&gt;.insert(index, &lt;el&gt;) <span class="hljs-comment"># Inserts item at index and moves the rest to the right.</span>
  165. &lt;el&gt; = &lt;list&gt;.pop([index]) <span class="hljs-comment"># Removes and returns item at index or from the end.</span>
  166. &lt;list&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Removes first occurrence of item or raises ValueError.</span>
  167. &lt;list&gt;.clear() <span class="hljs-comment"># Removes all items.</span>
  168. </code></pre>
  169. <h2 id="dictionary"><a href="#dictionary" name="dictionary">#</a>Dictionary</h2>
  170. <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>
  171. &lt;view&gt; = &lt;dict&gt;.values() <span class="hljs-comment"># Coll. of values that reflects changes.</span>
  172. &lt;view&gt; = &lt;dict&gt;.items() <span class="hljs-comment"># Coll. of key-value tuples.</span>
  173. </code></pre>
  174. <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>
  175. 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>
  176. &lt;dict&gt; = collections.defaultdict(&lt;type&gt;) <span class="hljs-comment"># Creates a dict with default value of type.</span>
  177. &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>
  178. </code></pre>
  179. <pre><code class="python language-python hljs">&lt;dict&gt;.update(&lt;dict&gt;) <span class="hljs-comment"># Or: dict_a = {**dict_a, **dict_b}.</span>
  180. &lt;dict&gt; = dict(&lt;collection&gt;) <span class="hljs-comment"># Creates a dict from coll. of key-value pairs.</span>
  181. &lt;dict&gt; = dict(zip(keys, values)) <span class="hljs-comment"># Creates a dict from two collections.</span>
  182. &lt;dict&gt; = dict.fromkeys(keys [, value]) <span class="hljs-comment"># Creates a dict from collection of keys.</span>
  183. </code></pre>
  184. <pre><code class="python language-python hljs">value = &lt;dict&gt;.pop(key) <span class="hljs-comment"># Removes item from dictionary.</span>
  185. {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>
  186. </code></pre>
  187. <h3 id="counter">Counter</h3>
  188. <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
  189. <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>]
  190. <span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter(colors)
  191. 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>})
  192. <span class="hljs-meta">&gt;&gt;&gt; </span>counter.most_common()[<span class="hljs-number">0</span>]
  193. (<span class="hljs-string">'blue'</span>, <span class="hljs-number">3</span>)
  194. </code></pre>
  195. <h2 id="set"><a href="#set" name="set">#</a>Set</h2>
  196. <pre><code class="python language-python hljs">&lt;set&gt; = set()
  197. </code></pre>
  198. <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>
  199. &lt;set&gt;.update(&lt;collection&gt;) <span class="hljs-comment"># Or: &lt;set&gt; |= &lt;set&gt;</span>
  200. </code></pre>
  201. <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>
  202. &lt;set&gt; = &lt;set&gt;.intersection(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &amp; &lt;set&gt;</span>
  203. &lt;set&gt; = &lt;set&gt;.difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; - &lt;set&gt;</span>
  204. &lt;set&gt; = &lt;set&gt;.symmetric_difference(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; ^ &lt;set&gt;</span>
  205. &lt;bool&gt; = &lt;set&gt;.issubset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &lt;= &lt;set&gt;</span>
  206. &lt;bool&gt; = &lt;set&gt;.issuperset(&lt;coll.&gt;) <span class="hljs-comment"># Or: &lt;set&gt; &gt;= &lt;set&gt;</span>
  207. </code></pre>
  208. <pre><code class="python language-python hljs">&lt;set&gt;.remove(&lt;el&gt;) <span class="hljs-comment"># Raises KeyError.</span>
  209. &lt;set&gt;.discard(&lt;el&gt;) <span class="hljs-comment"># Doesn't raise an error.</span>
  210. </code></pre>
  211. <h3 id="frozenset">Frozenset</h3>
  212. <h4 id="ishashablemeaningitcanbeusedasakeyinadictionaryorasanelementinaset">Is hashable, meaning it can be used as a key in a dictionary or as an element in a set.</h4>
  213. <pre><code class="python language-python hljs">&lt;frozenset&gt; = frozenset(&lt;collection&gt;)
  214. </code></pre>
  215. <h2 id="range"><a href="#range" name="range">#</a>Range</h2>
  216. <pre><code class="python language-python hljs">&lt;range&gt; = range(to_exclusive)
  217. &lt;range&gt; = range(from_inclusive, to_exclusive)
  218. &lt;range&gt; = range(from_inclusive, to_exclusive, ±step_size)
  219. </code></pre>
  220. <pre><code class="python language-python hljs">from_inclusive = &lt;range&gt;.start
  221. to_exclusive = &lt;range&gt;.stop
  222. </code></pre>
  223. <h2 id="enumerate"><a href="#enumerate" name="enumerate">#</a>Enumerate</h2>
  224. <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]):
  225. ...
  226. </code></pre>
  227. <h2 id="namedtuple"><a href="#namedtuple" name="namedtuple">#</a>Named Tuple</h2>
  228. <ul>
  229. <li><strong>Tuple is an immutable and hashable list.</strong></li>
  230. <li><strong>Named tuple is its subclass with named elements.</strong></li>
  231. </ul>
  232. <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
  233. <span class="hljs-meta">&gt;&gt;&gt; </span>Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  234. <span class="hljs-meta">&gt;&gt;&gt; </span>p = Point(<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  235. Point(x=<span class="hljs-number">1</span>, y=<span class="hljs-number">2</span>)
  236. <span class="hljs-meta">&gt;&gt;&gt; </span>p[<span class="hljs-number">0</span>]
  237. <span class="hljs-number">1</span>
  238. <span class="hljs-meta">&gt;&gt;&gt; </span>p.x
  239. <span class="hljs-number">1</span>
  240. <span class="hljs-meta">&gt;&gt;&gt; </span>getattr(p, <span class="hljs-string">'y'</span>)
  241. <span class="hljs-number">2</span>
  242. <span class="hljs-meta">&gt;&gt;&gt; </span>p._fields <span class="hljs-comment"># Or: Point._fields</span>
  243. (<span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>)
  244. </code></pre>
  245. <h2 id="iterator"><a href="#iterator" name="iterator">#</a>Iterator</h2>
  246. <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
  247. </code></pre>
  248. <pre><code class="python language-python hljs">&lt;iter&gt; = iter(&lt;collection&gt;)
  249. &lt;iter&gt; = iter(&lt;function&gt;, to_exclusive) <span class="hljs-comment"># Sequence of return values until 'to_exclusive'.</span>
  250. &lt;el&gt; = next(&lt;iter&gt; [, default]) <span class="hljs-comment"># Raises StopIteration or returns 'default' on end.</span>
  251. </code></pre>
  252. <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>
  253. &lt;iter&gt; = repeat(&lt;el&gt; [, times]) <span class="hljs-comment"># Returns element endlessly or 'times' times.</span>
  254. &lt;iter&gt; = cycle(&lt;collection&gt;) <span class="hljs-comment"># Repeats the sequence indefinitely.</span>
  255. </code></pre>
  256. <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>
  257. &lt;iter&gt; = chain.from_iterable(&lt;collection&gt;) <span class="hljs-comment"># Empties collections inside a collection in order.</span>
  258. </code></pre>
  259. <pre><code class="python language-python hljs">&lt;iter&gt; = islice(&lt;collection&gt;, to_exclusive)
  260. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive)
  261. &lt;iter&gt; = islice(&lt;collection&gt;, from_inclusive, to_exclusive, step_size)
  262. </code></pre>
  263. <h2 id="generator"><a href="#generator" name="generator">#</a>Generator</h2>
  264. <p><strong>Convenient way to implement the iterator protocol.</strong></p>
  265. <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>
  266. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  267. <span class="hljs-keyword">yield</span> start
  268. start += step
  269. </code></pre>
  270. <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>)
  271. <span class="hljs-meta">&gt;&gt;&gt; </span>next(counter), next(counter), next(counter)
  272. (<span class="hljs-number">10</span>, <span class="hljs-number">12</span>, <span class="hljs-number">14</span>)
  273. </code></pre>
  274. <h2 id="type"><a href="#type" name="type">#</a>Type</h2>
  275. <ul>
  276. <li><strong>Everything is an object.</strong></li>
  277. <li><strong>Every object has a type.</strong></li>
  278. <li><strong>Type and class are synonymous.</strong></li>
  279. </ul>
  280. <pre><code class="python language-python hljs">&lt;type&gt; = type(&lt;el&gt;) <span class="hljs-comment"># Or: &lt;type&gt; = &lt;el&gt;.__class__</span>
  281. &lt;bool&gt; = isinstance(&lt;el&gt;, &lt;type&gt;) <span class="hljs-comment"># Also checks subclasses and ABCs.</span>
  282. </code></pre>
  283. <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
  284. (&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;)
  285. </span></code></pre>
  286. <h4 id="sometypesdonothavebuiltinnamessotheymustbeimported">Some types do not have builtin names, so they must be imported:</h4>
  287. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> types <span class="hljs-keyword">import</span> FunctionType, MethodType, LambdaType, GeneratorType
  288. </code></pre>
  289. <h3 id="abcs">ABC-s</h3>
  290. <p><strong>Abstract base classes introduce virtual subclasses, that don’t inherit from a class but are still recognized by isinstance().</strong></p>
  291. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> numbers <span class="hljs-keyword">import</span> Integral, Rational, Real, Complex, Number
  292. <span class="hljs-keyword">from</span> collections.abc <span class="hljs-keyword">import</span> Iterable, Collection, Sequence
  293. </code></pre>
  294. <h2 id="string"><a href="#string" name="string">#</a>String</h2>
  295. <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>
  296. &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>
  297. </code></pre>
  298. <pre><code class="python language-python hljs">&lt;list&gt; = &lt;str&gt;.split() <span class="hljs-comment"># Splits on any whitespace character.</span>
  299. &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>
  300. &lt;str&gt; = &lt;str&gt;.join(&lt;collection&gt;) <span class="hljs-comment"># Joins elements using string as separator.</span>
  301. </code></pre>
  302. <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>
  303. &lt;bool&gt; = &lt;str&gt;.startswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  304. &lt;bool&gt; = &lt;str&gt;.endswith(&lt;sub_str&gt;) <span class="hljs-comment"># Pass tuple of strings for multiple options.</span>
  305. &lt;int&gt; = &lt;str&gt;.index(&lt;sub_str&gt;) <span class="hljs-comment"># Returns start index of first match.</span>
  306. </code></pre>
  307. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;str&gt;.isnumeric() <span class="hljs-comment"># True if str contains only numeric characters.</span>
  308. &lt;list&gt; = textwrap.wrap(&lt;str&gt;, width) <span class="hljs-comment"># Nicely breaks string into lines.</span>
  309. </code></pre>
  310. <h3 id="char">Char</h3>
  311. <pre><code class="python language-python hljs">&lt;str&gt; = chr(&lt;int&gt;) <span class="hljs-comment"># Converts int to unicode char.</span>
  312. &lt;int&gt; = ord(&lt;str&gt;) <span class="hljs-comment"># Converts unicode char to int.</span>
  313. </code></pre>
  314. <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>)
  315. (<span class="hljs-number">48</span>, <span class="hljs-number">57</span>)
  316. <span class="hljs-meta">&gt;&gt;&gt; </span>ord(<span class="hljs-string">'A'</span>), ord(<span class="hljs-string">'Z'</span>)
  317. (<span class="hljs-number">65</span>, <span class="hljs-number">90</span>)
  318. <span class="hljs-meta">&gt;&gt;&gt; </span>ord(<span class="hljs-string">'a'</span>), ord(<span class="hljs-string">'z'</span>)
  319. (<span class="hljs-number">97</span>, <span class="hljs-number">122</span>)
  320. </code></pre>
  321. <h2 id="regex"><a href="#regex" name="regex">#</a>Regex</h2>
  322. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> re
  323. &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>
  324. &lt;list&gt; = re.findall(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences.</span>
  325. &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>
  326. &lt;Match&gt; = re.search(&lt;regex&gt;, text) <span class="hljs-comment"># Searches for first occurrence of pattern.</span>
  327. &lt;Match&gt; = re.match(&lt;regex&gt;, text) <span class="hljs-comment"># Searches only at the beginning of the text.</span>
  328. &lt;iter&gt; = re.finditer(&lt;regex&gt;, text) <span class="hljs-comment"># Returns all occurrences as match objects.</span>
  329. </code></pre>
  330. <ul>
  331. <li><strong>Parameter <code class="python hljs"><span class="hljs-string">'flags=re.IGNORECASE'</span></code> can be used with all functions.</strong></li>
  332. <li><strong>Parameter <code class="python hljs"><span class="hljs-string">'flags=re.DOTALL'</span></code> makes dot also accept newline.</strong></li>
  333. <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>
  334. <li><strong>Use <code class="python hljs"><span class="hljs-string">'?'</span></code> to make an operator non-greedy.</strong></li>
  335. </ul>
  336. <h3 id="matchobject">Match Object</h3>
  337. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;Match&gt;.group() <span class="hljs-comment"># Whole match.</span>
  338. &lt;str&gt; = &lt;Match&gt;.group(<span class="hljs-number">1</span>) <span class="hljs-comment"># Part in first bracket.</span>
  339. &lt;tuple&gt; = &lt;Match&gt;.groups() <span class="hljs-comment"># All bracketed parts.</span>
  340. &lt;int&gt; = &lt;Match&gt;.start() <span class="hljs-comment"># Start index of a match.</span>
  341. &lt;int&gt; = &lt;Match&gt;.end() <span class="hljs-comment"># Exclusive end index of a match.</span>
  342. </code></pre>
  343. <h3 id="specialsequences">Special Sequences</h3>
  344. <p><strong>Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.</strong></p>
  345. <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>
  346. <span class="hljs-string">'\s'</span> == <span class="hljs-string">'[ \t\n\r\f\v]'</span> <span class="hljs-comment"># Whitespace</span>
  347. <span class="hljs-string">'\w'</span> == <span class="hljs-string">'[a-zA-Z0-9_]'</span> <span class="hljs-comment"># Alphanumeric</span>
  348. </code></pre>
  349. <h2 id="format"><a href="#format" name="format">#</a>Format</h2>
  350. <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>
  351. &lt;str&gt; = <span class="hljs-string">'{}, {}'</span>.format(&lt;el_1&gt;, &lt;el_2&gt;)
  352. </code></pre>
  353. <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
  354. <span class="hljs-meta">&gt;&gt;&gt; </span>Person = namedtuple(<span class="hljs-string">'Person'</span>, <span class="hljs-string">'name height'</span>)
  355. <span class="hljs-meta">&gt;&gt;&gt; </span>person = Person(<span class="hljs-string">'Jean-Luc'</span>, <span class="hljs-number">187</span>)
  356. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">f'<span class="hljs-subst">{person.height}</span>'</span>
  357. <span class="hljs-string">'187'</span>
  358. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-string">'{p.height}'</span>.format(p=person)
  359. <span class="hljs-string">'187'</span>
  360. </code></pre>
  361. <h3 id="generaloptions">General Options</h3>
  362. <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>
  363. {&lt;el&gt;:&gt;<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt;'</span>
  364. {&lt;el&gt;:^<span class="hljs-number">10</span>} <span class="hljs-comment"># ' &lt;el&gt; '</span>
  365. {&lt;el&gt;:.&gt;<span class="hljs-number">10</span>} <span class="hljs-comment"># '......&lt;el&gt;'</span>
  366. {&lt;el&gt;:&gt;<span class="hljs-number">0</span>} <span class="hljs-comment"># '&lt;el&gt;'</span>
  367. </code></pre>
  368. <h3 id="stringoptions">String Options</h3>
  369. <p><strong><code class="python hljs"><span class="hljs-string">'!r'</span></code> calls object's repr() method, instead of format(), to get a string.</strong></p>
  370. <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>
  371. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">.3</span>} <span class="hljs-comment"># 'abc'</span>
  372. {<span class="hljs-string">'abcde'</span>:<span class="hljs-number">10.3</span>} <span class="hljs-comment"># 'abc '</span>
  373. </code></pre>
  374. <h3 id="numberoptions">Number Options</h3>
  375. <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>
  376. { <span class="hljs-number">123456</span>:<span class="hljs-number">10</span>_} <span class="hljs-comment"># ' 123_456'</span>
  377. { <span class="hljs-number">123456</span>:+<span class="hljs-number">10</span>} <span class="hljs-comment"># ' +123456'</span>
  378. {<span class="hljs-number">-123456</span>:=<span class="hljs-number">10</span>} <span class="hljs-comment"># '- 123456'</span>
  379. { <span class="hljs-number">123456</span>: } <span class="hljs-comment"># ' 123456'</span>
  380. {<span class="hljs-number">-123456</span>: } <span class="hljs-comment"># '-123456'</span>
  381. </code></pre>
  382. <h4 id="floattypes">Float types:</h4>
  383. <pre><code class="python language-python hljs">{<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>f} <span class="hljs-comment"># ' 1.235'</span>
  384. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>e} <span class="hljs-comment"># ' 1.235e+00'</span>
  385. {<span class="hljs-number">1.23456</span>:<span class="hljs-number">10.3</span>%} <span class="hljs-comment"># ' 123.456%'</span>
  386. </code></pre>
  387. <h4 id="inttypes">Int types:</h4>
  388. <pre><code class="python language-python hljs">{<span class="hljs-number">90</span>:c} <span class="hljs-comment"># 'Z'</span>
  389. {<span class="hljs-number">90</span>:X} <span class="hljs-comment"># '5A'</span>
  390. {<span class="hljs-number">90</span>:b} <span class="hljs-comment"># '1011010'</span>
  391. </code></pre>
  392. <h2 id="numbers"><a href="#numbers" name="numbers">#</a>Numbers</h2>
  393. <h3 id="basicfunctions">Basic Functions</h3>
  394. <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>
  395. &lt;real&gt; = abs(&lt;num&gt;)
  396. &lt;int&gt; = round(&lt;real&gt;)
  397. &lt;real&gt; = round(&lt;real&gt;, ±ndigits)
  398. </code></pre>
  399. <h3 id="math">Math</h3>
  400. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> e, pi
  401. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> cos, acos, sin, asin, tan, atan, degrees, radians
  402. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> log, log10, log2
  403. <span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> inf, nan, isinf, isnan
  404. </code></pre>
  405. <h3 id="statistics">Statistics</h3>
  406. <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
  407. </code></pre>
  408. <h3 id="random">Random</h3>
  409. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> random, randint, choice, shuffle
  410. &lt;float&gt; = random()
  411. &lt;int&gt; = randint(from_inclusive, to_inclusive)
  412. &lt;el&gt; = choice(&lt;list&gt;)
  413. shuffle(&lt;list&gt;)
  414. </code></pre>
  415. <h2 id="combinatorics"><a href="#combinatorics" name="combinatorics">#</a>Combinatorics</h2>
  416. <ul>
  417. <li><strong>Every function returns an iterator.</strong></li>
  418. <li><strong>If you want to print the iterator, you need to pass it to the list() function!</strong></li>
  419. </ul>
  420. <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
  421. </code></pre>
  422. <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>)
  423. [(<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>),
  424. (<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>)]
  425. </code></pre>
  426. <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>)
  427. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'2'</span>),
  428. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'1'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'2'</span>)]
  429. </code></pre>
  430. <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>)
  431. [(<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>)]
  432. </code></pre>
  433. <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>)
  434. [(<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>),
  435. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  436. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'c'</span>)]
  437. </code></pre>
  438. <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>)
  439. [(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>), (<span class="hljs-string">'a'</span>, <span class="hljs-string">'c'</span>),
  440. (<span class="hljs-string">'b'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>),
  441. (<span class="hljs-string">'c'</span>, <span class="hljs-string">'a'</span>), (<span class="hljs-string">'c'</span>, <span class="hljs-string">'b'</span>)]
  442. </code></pre>
  443. <h2 id="datetime"><a href="#datetime" name="datetime">#</a>Datetime</h2>
  444. <ul>
  445. <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>
  446. <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>
  447. <li><strong>If object is naive it is presumed to be in system's timezone.</strong></li>
  448. </ul>
  449. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> date, time, datetime, timedelta
  450. <span class="hljs-keyword">from</span> dateutil.tz <span class="hljs-keyword">import</span> UTC, tzlocal, gettz
  451. </code></pre>
  452. <h3 id="constructors">Constructors</h3>
  453. <pre><code class="python language-python apache hljs">&lt;D&gt; = date(year, month, day)
  454. &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>)
  455. &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>, ...)
  456. &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>,
  457. minutes=<span class="hljs-number">0</span>, hours=<span class="hljs-number">0</span>, weeks=<span class="hljs-number">0</span>)
  458. </code></pre>
  459. <ul>
  460. <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>
  461. <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>
  462. </ul>
  463. <h3 id="now">Now</h3>
  464. <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>
  465. &lt;DTn&gt; = DT.utcnow() <span class="hljs-comment"># Naive datetime from current UTC time.</span>
  466. &lt;DTa&gt; = DT.now(&lt;tz&gt;) <span class="hljs-comment"># Aware datetime from current tz time.</span>
  467. </code></pre>
  468. <h3 id="timezone">Timezone</h3>
  469. <pre><code class="python language-python hljs">&lt;tz&gt; = UTC <span class="hljs-comment"># UTC timezone. London without DST.</span>
  470. &lt;tz&gt; = tzlocal() <span class="hljs-comment"># Local timezone.</span>
  471. &lt;tz&gt; = gettz(<span class="hljs-string">'&lt;Cont.&gt;/&lt;City&gt;'</span>) <span class="hljs-comment"># Timezone from 'Continent/City_Name' str.</span>
  472. </code></pre>
  473. <pre><code class="python language-python apache hljs">&lt;DTa&gt; = &lt;DT&gt;.astimezone(&lt;tz&gt;) <span class="hljs-comment"># Datetime, converted to passed timezone.</span>
  474. &lt;Ta/DTa&gt; = &lt;T/DT&gt;.replace(tzinfo=&lt;tz&gt;) <span class="hljs-comment"># Unconverted object with new timezone.</span>
  475. </code></pre>
  476. <h3 id="encode">Encode</h3>
  477. <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>
  478. &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>
  479. &lt;D/DTn&gt; = D/DT.fromordinal(&lt;int&gt;) <span class="hljs-comment"># D/DTn from days since Christ.</span>
  480. &lt;DTa&gt; = DT.fromtimestamp(&lt;real&gt;, &lt;tz&gt;) <span class="hljs-comment"># DTa from seconds since Epoch in tz time.</span>
  481. </code></pre>
  482. <ul>
  483. <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>
  484. <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>
  485. </ul>
  486. <h3 id="decode">Decode</h3>
  487. <pre><code class="python language-python apache hljs">&lt;str&gt; = &lt;D/T/DT&gt;.isoformat() <span class="hljs-comment"># ISO string representation.</span>
  488. &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>
  489. &lt;int&gt; = &lt;D/DT&gt;.toordinal() <span class="hljs-comment"># Days since Christ, ignoring time and tz.</span>
  490. &lt;float&gt; = &lt;DT&gt;.timestamp() <span class="hljs-comment"># Seconds since Epoch in local time or tz.</span>
  491. </code></pre>
  492. <h3 id="format-1">Format</h3>
  493. <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
  494. <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>)
  495. <span class="hljs-meta">&gt;&gt;&gt; </span>dt.strftime(<span class="hljs-string">"%A, %dth of %B '%y, %I:%M%p %Z"</span>)
  496. <span class="hljs-string">"Thursday, 14th of May '15, 11:39PM UTC+02:00"</span>
  497. </code></pre>
  498. <h4 id="restofthecodes">Rest of the codes:</h4>
  499. <ul>
  500. <li><strong><code class="python hljs"><span class="hljs-string">'a'</span></code> - Weekday, abbreviated name.</strong></li>
  501. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - Month, abbreviated name.</strong></li>
  502. </ul>
  503. <h2 id="arguments"><a href="#arguments" name="arguments">#</a>Arguments</h2>
  504. <h3 id="insidefunctioncall">Inside Function Call</h3>
  505. <pre><code class="python language-python hljs">&lt;function&gt;(&lt;positional_args&gt;) <span class="hljs-comment"># f(0, 0)</span>
  506. &lt;function&gt;(&lt;keyword_args&gt;) <span class="hljs-comment"># f(x=0, y=0)</span>
  507. &lt;function&gt;(&lt;positional_args&gt;, &lt;keyword_args&gt;) <span class="hljs-comment"># f(0, y=0)</span>
  508. </code></pre>
  509. <h3 id="insidefunctiondefinition">Inside Function Definition</h3>
  510. <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>
  511. <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>
  512. <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>
  513. </code></pre>
  514. <h2 id="splatoperator"><a href="#splatoperator" name="splatoperator">#</a>Splat Operator</h2>
  515. <h3 id="insidefunctioncall-1">Inside Function Call</h3>
  516. <p><strong>Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.</strong></p>
  517. <pre><code class="python language-python hljs">args = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
  518. 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>}
  519. func(*args, **kwargs)
  520. </code></pre>
  521. <h4 id="isthesameas">Is the same as:</h4>
  522. <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>)
  523. </code></pre>
  524. <h3 id="insidefunctiondefinition-1">Inside Function Definition</h3>
  525. <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>
  526. <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>
  527. <span class="hljs-keyword">return</span> sum(a)
  528. </code></pre>
  529. <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>)
  530. <span class="hljs-number">6</span>
  531. </code></pre>
  532. <h4 id="legalargumentcombinations">Legal argument combinations:</h4>
  533. <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>
  534. <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>
  535. <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>
  536. <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>
  537. </code></pre>
  538. <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>
  539. <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>
  540. </code></pre>
  541. <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>
  542. <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>
  543. <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>
  544. <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>
  545. </code></pre>
  546. <h3 id="otheruses">Other Uses</h3>
  547. <pre><code class="python language-python hljs">&lt;list&gt; = [*&lt;collection&gt; [, ...]]
  548. &lt;set&gt; = {*&lt;collection&gt; [, ...]}
  549. &lt;tuple&gt; = (*&lt;collection&gt;, [...])
  550. &lt;dict&gt; = {**&lt;dict&gt; [, ...]}
  551. </code></pre>
  552. <pre><code class="python language-python hljs">head, *body, tail = &lt;collection&gt;
  553. </code></pre>
  554. <h2 id="inline"><a href="#inline" name="inline">#</a>Inline</h2>
  555. <h3 id="lambda">Lambda</h3>
  556. <pre><code class="python language-python hljs">&lt;function&gt; = <span class="hljs-keyword">lambda</span>: &lt;return_value&gt;
  557. &lt;function&gt; = <span class="hljs-keyword">lambda</span> &lt;argument_1&gt;, &lt;argument_2&gt;: &lt;return_value&gt;
  558. </code></pre>
  559. <h3 id="comprehension">Comprehension</h3>
  560. <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>
  561. &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>
  562. &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>
  563. &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>
  564. </code></pre>
  565. <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>)]
  566. </code></pre>
  567. <h4 id="isthesameas-1">Is the same as:</h4>
  568. <pre><code class="python language-python hljs">out = []
  569. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  570. <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  571. out.append(i+j)
  572. </code></pre>
  573. <h3 id="mapfilterreduce">Map, Filter, Reduce</h3>
  574. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> reduce
  575. &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>
  576. &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>
  577. &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>
  578. </code></pre>
  579. <h3 id="anyall">Any, All</h3>
  580. <pre><code class="python language-python hljs">&lt;bool&gt; = any(&lt;collection&gt;) <span class="hljs-comment"># False if empty.</span>
  581. &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>
  582. </code></pre>
  583. <h3 id="ifelse">If - Else</h3>
  584. <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;
  585. </code></pre>
  586. <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>)]
  587. [<span class="hljs-string">'zero'</span>, <span class="hljs-number">1</span>, <span class="hljs-string">'zero'</span>, <span class="hljs-number">3</span>]
  588. </code></pre>
  589. <h3 id="namedtupleenumclass">Namedtuple, Enum, Class</h3>
  590. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  591. Point = namedtuple(<span class="hljs-string">'Point'</span>, <span class="hljs-string">'x y'</span>)
  592. point = Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>)
  593. </code></pre>
  594. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  595. Direction = Enum(<span class="hljs-string">'Direction'</span>, <span class="hljs-string">'n e s w'</span>)
  596. 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>})
  597. </code></pre>
  598. <pre><code class="python language-python hljs"><span class="hljs-comment"># Warning: Objects will share the objects that are initialized in the dictionary!</span>
  599. Creature = type(<span class="hljs-string">'Creature'</span>, (), {<span class="hljs-string">'p'</span>: Point(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>), <span class="hljs-string">'d'</span>: Direction.n})
  600. creature = Creature()
  601. </code></pre>
  602. <h2 id="closure"><a href="#closure" name="closure">#</a>Closure</h2>
  603. <p><strong>We have a closure in Python when:</strong></p>
  604. <ul>
  605. <li><strong>A nested function references a value of its enclosing function and then</strong></li>
  606. <li><strong>the enclosing function returns the nested function.</strong></li>
  607. </ul>
  608. <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>
  609. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(b)</span>:</span>
  610. <span class="hljs-keyword">return</span> a * b
  611. <span class="hljs-keyword">return</span> out
  612. </code></pre>
  613. <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>)
  614. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  615. <span class="hljs-number">30</span>
  616. </code></pre>
  617. <ul>
  618. <li><strong>If multiple nested functions within enclosing function reference the same value, that value gets shared.</strong></li>
  619. <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>
  620. </ul>
  621. <h3 id="partial">Partial</h3>
  622. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial
  623. &lt;function&gt; = partial(&lt;function&gt; [, &lt;arg_1&gt;, &lt;arg_2&gt;, ...])
  624. </code></pre>
  625. <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
  626. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3 = partial(op.mul, <span class="hljs-number">3</span>)
  627. <span class="hljs-meta">&gt;&gt;&gt; </span>multiply_by_3(<span class="hljs-number">10</span>)
  628. <span class="hljs-number">30</span>
  629. </code></pre>
  630. <h3 id="nonlocal">Nonlocal</h3>
  631. <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>
  632. <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>
  633. i = <span class="hljs-number">0</span>
  634. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">()</span>:</span>
  635. <span class="hljs-keyword">nonlocal</span> i
  636. i += <span class="hljs-number">1</span>
  637. <span class="hljs-keyword">return</span> i
  638. <span class="hljs-keyword">return</span> out
  639. </code></pre>
  640. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = get_counter()
  641. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  642. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  643. </code></pre>
  644. <h2 id="decorator"><a href="#decorator" name="decorator">#</a>Decorator</h2>
  645. <p><strong>A decorator takes a function, adds some functionality and returns it.</strong></p>
  646. <pre><code class="python language-python hljs"><span class="hljs-meta">@decorator_name</span>
  647. <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>
  648. ...
  649. </code></pre>
  650. <h3 id="debuggerexample">Debugger Example</h3>
  651. <p><strong>Decorator that prints function's name every time it gets called.</strong></p>
  652. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
  653. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug</span><span class="hljs-params">(func)</span>:</span>
  654. <span class="hljs-meta"> @wraps(func)</span>
  655. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  656. print(func.__name__)
  657. <span class="hljs-keyword">return</span> func(*args, **kwargs)
  658. <span class="hljs-keyword">return</span> out
  659. <span class="hljs-meta">@debug</span>
  660. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  661. <span class="hljs-keyword">return</span> x + y
  662. </code></pre>
  663. <ul>
  664. <li><strong>Wraps is a helper decorator that copies metadata of function add() to function out().</strong></li>
  665. <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>
  666. </ul>
  667. <h3 id="lrucache">LRU Cache</h3>
  668. <p><strong>Decorator that caches function's return values. All function's arguments must be hashable.</strong></p>
  669. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> lru_cache
  670. <span class="hljs-meta">@lru_cache(maxsize=None)</span>
  671. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fib</span><span class="hljs-params">(n)</span>:</span>
  672. <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>)
  673. </code></pre>
  674. <ul>
  675. <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>
  676. </ul>
  677. <h3 id="parametrizeddecorator">Parametrized Decorator</h3>
  678. <p><strong>A decorator that accepts arguments and returns a normal decorator that accepts a function.</strong></p>
  679. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> wraps
  680. <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>
  681. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span><span class="hljs-params">(func)</span>:</span>
  682. <span class="hljs-meta"> @wraps(func)</span>
  683. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  684. result = func(*args, **kwargs)
  685. print(func.__name__, result <span class="hljs-keyword">if</span> print_result <span class="hljs-keyword">else</span> <span class="hljs-string">''</span>)
  686. <span class="hljs-keyword">return</span> result
  687. <span class="hljs-keyword">return</span> out
  688. <span class="hljs-keyword">return</span> decorator
  689. <span class="hljs-meta">@debug(print_result=True)</span>
  690. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span><span class="hljs-params">(x, y)</span>:</span>
  691. <span class="hljs-keyword">return</span> x + y
  692. </code></pre>
  693. <h2 id="class"><a href="#class" name="class">#</a>Class</h2>
  694. <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>
  695. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  696. self.a = a
  697. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__repr__</span><span class="hljs-params">(self)</span>:</span>
  698. class_name = self.__class__.__name__
  699. <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>
  700. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span><span class="hljs-params">(self)</span>:</span>
  701. <span class="hljs-keyword">return</span> str(self.a)
  702. <span class="hljs-meta"> @classmethod</span>
  703. <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>
  704. <span class="hljs-keyword">return</span> cls.__name__
  705. </code></pre>
  706. <h3 id="constructoroverloading">Constructor Overloading</h3>
  707. <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>
  708. <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>
  709. self.a = a
  710. </code></pre>
  711. <h3 id="inheritance">Inheritance</h3>
  712. <pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span>:</span>
  713. <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>
  714. self.name = name
  715. self.age = age
  716. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Employee</span><span class="hljs-params">(Person)</span>:</span>
  717. <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>
  718. super().__init__(name, age)
  719. self.staff_num = staff_num
  720. </code></pre>
  721. <h3 id="multipleinheritance">Multiple Inheritance</h3>
  722. <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>
  723. <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">B</span>:</span> <span class="hljs-keyword">pass</span>
  724. <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>
  725. </code></pre>
  726. <p><strong>MRO determines the order in which parent classes are traversed when searching for a method:</strong></p>
  727. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>C.mro()
  728. [&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;]
  729. </span></code></pre>
  730. <h3 id="copy">Copy</h3>
  731. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> copy <span class="hljs-keyword">import</span> copy, deepcopy
  732. &lt;object&gt; = copy(&lt;object&gt;)
  733. &lt;object&gt; = deepcopy(&lt;object&gt;)
  734. </code></pre>
  735. <h2 id="ducktypes"><a href="#ducktypes" name="ducktypes">#</a>Duck Types</h2>
  736. <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>
  737. <h3 id="comparable">Comparable</h3>
  738. <ul>
  739. <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>
  740. <li><strong>That means all objects compare not equal by default.</strong></li>
  741. </ul>
  742. <pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyComparable</span>:</span>
  743. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  744. self.a = a
  745. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  746. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  747. <span class="hljs-keyword">return</span> self.a == other.a
  748. <span class="hljs-keyword">return</span> <span class="hljs-keyword">False</span>
  749. </code></pre>
  750. <h3 id="hashable">Hashable</h3>
  751. <ul>
  752. <li><strong>Hashable object needs both hash() and eq() methods and its hash value should never change.</strong></li>
  753. <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>
  754. <li><strong>That is why Python automatically makes classes unhashable if you only implement eq().</strong></li>
  755. </ul>
  756. <pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyHashable</span>:</span>
  757. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  758. self.__a = copy.deepcopy(a)
  759. <span class="hljs-meta"> @property</span>
  760. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">a</span><span class="hljs-params">(self)</span>:</span>
  761. <span class="hljs-keyword">return</span> self.__a
  762. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__eq__</span><span class="hljs-params">(self, other)</span>:</span>
  763. <span class="hljs-keyword">if</span> isinstance(other, type(self)):
  764. <span class="hljs-keyword">return</span> self.a == other.a
  765. <span class="hljs-keyword">return</span> <span class="hljs-keyword">False</span>
  766. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__hash__</span><span class="hljs-params">(self)</span>:</span>
  767. <span class="hljs-keyword">return</span> hash(self.a)
  768. </code></pre>
  769. <h3 id="collection">Collection</h3>
  770. <ul>
  771. <li><strong>Methods do not depend on each other, so they can be skipped if not needed.</strong></li>
  772. <li><strong>Any object with defined getitem() is considered iterable, even if it lacks iter().</strong></li>
  773. </ul>
  774. <pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCollection</span>:</span>
  775. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, a)</span>:</span>
  776. self.a = a
  777. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__len__</span><span class="hljs-params">(self)</span>:</span>
  778. <span class="hljs-keyword">return</span> len(self.a)
  779. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__getitem__</span><span class="hljs-params">(self, i)</span>:</span>
  780. <span class="hljs-keyword">return</span> self.a[i]
  781. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__setitem__</span><span class="hljs-params">(self, i, el)</span>:</span>
  782. self.a[i] = el
  783. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__contains__</span><span class="hljs-params">(self, el)</span>:</span>
  784. <span class="hljs-keyword">return</span> el <span class="hljs-keyword">in</span> self.a
  785. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__iter__</span><span class="hljs-params">(self)</span>:</span>
  786. <span class="hljs-keyword">for</span> el <span class="hljs-keyword">in</span> self.a:
  787. <span class="hljs-keyword">yield</span> el
  788. </code></pre>
  789. <h3 id="callable">Callable</h3>
  790. <pre><code class="python language-python hljs"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Counter</span>:</span>
  791. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self)</span>:</span>
  792. self.i = <span class="hljs-number">0</span>
  793. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span><span class="hljs-params">(self)</span>:</span>
  794. self.i += <span class="hljs-number">1</span>
  795. <span class="hljs-keyword">return</span> self.i
  796. </code></pre>
  797. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>counter = Counter()
  798. <span class="hljs-meta">&gt;&gt;&gt; </span>counter(), counter(), counter()
  799. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  800. </code></pre>
  801. <h3 id="contextmanager">Context Manager</h3>
  802. <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>
  803. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span><span class="hljs-params">(self, filename)</span>:</span>
  804. self.filename = filename
  805. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__enter__</span><span class="hljs-params">(self)</span>:</span>
  806. self.file = open(self.filename)
  807. <span class="hljs-keyword">return</span> self.file
  808. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__exit__</span><span class="hljs-params">(self, *args)</span>:</span>
  809. self.file.close()
  810. </code></pre>
  811. <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:
  812. <span class="hljs-meta">... </span> file.write(<span class="hljs-string">'Hello World!'</span>)
  813. <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:
  814. <span class="hljs-meta">... </span> print(file.read())
  815. Hello World!
  816. </code></pre>
  817. <h2 id="enum"><a href="#enum" name="enum">#</a>Enum</h2>
  818. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum, auto
  819. <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>
  820. &lt;member_name_1&gt; = &lt;value_1&gt;
  821. &lt;member_name_2&gt; = &lt;value_2_a&gt;, &lt;value_2_b&gt;
  822. &lt;member_name_3&gt; = auto()
  823. <span class="hljs-meta"> @classmethod</span>
  824. <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>
  825. <span class="hljs-keyword">return</span> [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> cls.__members__.values()]
  826. </code></pre>
  827. <pre><code class="python language-python hljs">&lt;member&gt; = &lt;enum&gt;.&lt;member_name&gt;
  828. &lt;member&gt; = &lt;enum&gt;[<span class="hljs-string">'&lt;member_name&gt;'</span>]
  829. &lt;member&gt; = &lt;enum&gt;(&lt;value&gt;)
  830. name = &lt;member&gt;.name
  831. value = &lt;member&gt;.value
  832. </code></pre>
  833. <pre><code class="python language-python hljs">list_of_members = list(&lt;enum&gt;)
  834. member_names = [a.name <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  835. member_values = [a.value <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> &lt;enum&gt;]
  836. random_member = random.choice(list(&lt;enum&gt;))
  837. </code></pre>
  838. <h3 id="inline-1">Inline</h3>
  839. <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>])
  840. Cutlery = Enum(<span class="hljs-string">'Cutlery'</span>, <span class="hljs-string">'fork knife spoon'</span>)
  841. 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>})
  842. </code></pre>
  843. <h4 id="functionscannotbevaluessotheymustbewrapped">Functions can not be values, so they must be wrapped:</h4>
  844. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> functools <span class="hljs-keyword">import</span> partial
  845. 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),
  846. <span class="hljs-string">'OR'</span> : partial(<span class="hljs-keyword">lambda</span> l, r: l <span class="hljs-keyword">or</span> r)})
  847. </code></pre>
  848. <h2 id="exceptions"><a href="#exceptions" name="exceptions">#</a>Exceptions</h2>
  849. <pre><code class="python language-python hljs"><span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  850. <span class="hljs-keyword">try</span>:
  851. x = int(input(<span class="hljs-string">'Please enter a number: '</span>))
  852. <span class="hljs-keyword">except</span> ValueError:
  853. print(<span class="hljs-string">'Oops! That was no valid number. Try again...'</span>)
  854. <span class="hljs-keyword">else</span>:
  855. print(<span class="hljs-string">'Thank you.'</span>)
  856. <span class="hljs-keyword">break</span>
  857. </code></pre>
  858. <h3 id="raisingexception">Raising Exception</h3>
  859. <pre><code class="python language-python hljs"><span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">'A very specific message!'</span>)
  860. </code></pre>
  861. <h3 id="finally">Finally</h3>
  862. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">try</span>:
  863. <span class="hljs-meta">... </span> <span class="hljs-keyword">raise</span> KeyboardInterrupt
  864. <span class="hljs-meta">... </span><span class="hljs-keyword">finally</span>:
  865. <span class="hljs-meta">... </span> print(<span class="hljs-string">'Goodbye, world!'</span>)
  866. Goodbye, world!
  867. Traceback (most recent call last):
  868. File <span class="hljs-string">"&lt;stdin&gt;"</span>, line <span class="hljs-number">2</span>, <span class="hljs-keyword">in</span> &lt;module&gt;
  869. KeyboardInterrupt
  870. </code></pre>
  871. <h2 id="print"><a href="#print" name="print">#</a>Print</h2>
  872. <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>)
  873. </code></pre>
  874. <ul>
  875. <li><strong>Use <code class="python hljs"><span class="hljs-string">'file=sys.stderr'</span></code> for errors.</strong></li>
  876. </ul>
  877. <h3 id="prettyprint">Pretty Print</h3>
  878. <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
  879. <span class="hljs-meta">&gt;&gt;&gt; </span>pprint(dir())
  880. [<span class="hljs-string">'__annotations__'</span>,
  881. <span class="hljs-string">'__builtins__'</span>,
  882. <span class="hljs-string">'__doc__'</span>, ...]
  883. </code></pre>
  884. <h2 id="input"><a href="#input" name="input">#</a>Input</h2>
  885. <ul>
  886. <li><strong>Reads a line from user input or pipe if present.</strong></li>
  887. <li><strong>Trailing newline gets stripped.</strong></li>
  888. <li><strong>Prompt string is printed to the standard output before reading input.</strong></li>
  889. </ul>
  890. <pre><code class="python language-python hljs">&lt;str&gt; = input(prompt=<span class="hljs-keyword">None</span>)
  891. </code></pre>
  892. <h4 id="printslinesuntileof">Prints lines until EOF:</h4>
  893. <pre><code class="python language-python hljs"><span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  894. <span class="hljs-keyword">try</span>:
  895. print(input())
  896. <span class="hljs-keyword">except</span> EOFError:
  897. <span class="hljs-keyword">break</span>
  898. </code></pre>
  899. <h2 id="commandlinearguments"><a href="#commandlinearguments" name="commandlinearguments">#</a>Command Line Arguments</h2>
  900. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sys
  901. script_name = sys.argv[<span class="hljs-number">0</span>]
  902. arguments = sys.argv[<span class="hljs-number">1</span>:]
  903. </code></pre>
  904. <h3 id="argparse">Argparse</h3>
  905. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> argparse <span class="hljs-keyword">import</span> ArgumentParser, FileType
  906. p = ArgumentParser(description=&lt;str&gt;)
  907. 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>
  908. 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>
  909. 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>
  910. 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>
  911. args = p.parse_args()
  912. value = args.&lt;name&gt;
  913. </code></pre>
  914. <ul>
  915. <li><strong>Use <code class="python hljs"><span class="hljs-string">'help=&lt;str&gt;'</span></code> for argument description.</strong></li>
  916. <li><strong>Use <code class="python hljs"><span class="hljs-string">'type=FileType(&lt;mode&gt;)'</span></code> for files.</strong></li>
  917. </ul>
  918. <h2 id="open"><a href="#open" name="open">#</a>Open</h2>
  919. <p><strong>Opens a file and returns a corresponding file object.</strong></p>
  920. <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>)
  921. </code></pre>
  922. <h3 id="modes">Modes</h3>
  923. <ul>
  924. <li><strong><code class="python hljs"><span class="hljs-string">'r'</span></code> - Read (default).</strong></li>
  925. <li><strong><code class="python hljs"><span class="hljs-string">'w'</span></code> - Write (truncate).</strong></li>
  926. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - Write or fail if the file already exists.</strong></li>
  927. <li><strong><code class="python hljs"><span class="hljs-string">'a'</span></code> - Append.</strong></li>
  928. <li><strong><code class="python hljs"><span class="hljs-string">'w+'</span></code> - Read and write (truncate).</strong></li>
  929. <li><strong><code class="python hljs"><span class="hljs-string">'r+'</span></code> - Read and write from the start.</strong></li>
  930. <li><strong><code class="python hljs"><span class="hljs-string">'a+'</span></code> - Read and write from the end.</strong></li>
  931. <li><strong><code class="python hljs"><span class="hljs-string">'t'</span></code> - Text mode (default).</strong></li>
  932. <li><strong><code class="python hljs"><span class="hljs-string">'b'</span></code> - Binary mode.</strong></li>
  933. </ul>
  934. <h3 id="file">File</h3>
  935. <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>
  936. &lt;file&gt;.seek(offset) <span class="hljs-comment"># Moves 'offset' chars/bytes from the start.</span>
  937. &lt;file&gt;.seek(offset, &lt;anchor&gt;) <span class="hljs-comment"># Anchor: 0 start, 1 current pos., 2 end.</span>
  938. </code></pre>
  939. <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>
  940. &lt;str/bytes&gt; = &lt;file&gt;.readline() <span class="hljs-comment"># Returns a line.</span>
  941. &lt;list&gt; = &lt;file&gt;.readlines() <span class="hljs-comment"># Returns a list of lines.</span>
  942. &lt;str/bytes&gt; = next(&lt;file&gt;) <span class="hljs-comment"># Returns a line using buffer. Do not mix.</span>
  943. </code></pre>
  944. <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>
  945. &lt;file&gt;.writelines(&lt;list&gt;) <span class="hljs-comment"># Writes a list of strings or bytes objects.</span>
  946. &lt;file&gt;.flush() <span class="hljs-comment"># Flushes write buffer.</span>
  947. </code></pre>
  948. <ul>
  949. <li><strong>Methods do not add or strip trailing newlines.</strong></li>
  950. </ul>
  951. <h3 id="readtextfromfile">Read Text from File</h3>
  952. <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>
  953. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  954. <span class="hljs-keyword">return</span> file.readlines()
  955. </code></pre>
  956. <h3 id="writetexttofile">Write Text to File</h3>
  957. <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>
  958. <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:
  959. file.write(text)
  960. </code></pre>
  961. <h2 id="path"><a href="#path" name="path">#</a>Path</h2>
  962. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> os <span class="hljs-keyword">import</span> path, listdir
  963. &lt;bool&gt; = path.exists(<span class="hljs-string">'&lt;path&gt;'</span>)
  964. &lt;bool&gt; = path.isfile(<span class="hljs-string">'&lt;path&gt;'</span>)
  965. &lt;bool&gt; = path.isdir(<span class="hljs-string">'&lt;path&gt;'</span>)
  966. &lt;list&gt; = listdir(<span class="hljs-string">'&lt;path&gt;'</span>)
  967. </code></pre>
  968. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> glob <span class="hljs-keyword">import</span> glob
  969. <span class="hljs-meta">&gt;&gt;&gt; </span>glob(<span class="hljs-string">'../*.gif'</span>)
  970. [<span class="hljs-string">'1.gif'</span>, <span class="hljs-string">'card.gif'</span>]
  971. </code></pre>
  972. <h3 id="pathlib">Pathlib</h3>
  973. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> pathlib <span class="hljs-keyword">import</span> Path
  974. cwd = Path()
  975. &lt;Path&gt; = Path(<span class="hljs-string">'&lt;path&gt;'</span> [, <span class="hljs-string">'&lt;path&gt;'</span>, &lt;Path&gt;, ...])
  976. &lt;Path&gt; = &lt;Path&gt; / <span class="hljs-string">'&lt;dir&gt;'</span> / <span class="hljs-string">'&lt;file&gt;'</span>
  977. </code></pre>
  978. <pre><code class="python language-python hljs">&lt;bool&gt; = &lt;Path&gt;.exists()
  979. &lt;bool&gt; = &lt;Path&gt;.is_file()
  980. &lt;bool&gt; = &lt;Path&gt;.is_dir()
  981. &lt;iter&gt; = &lt;Path&gt;.iterdir()
  982. </code></pre>
  983. <pre><code class="python language-python hljs">&lt;iter&gt; = &lt;Path&gt;.glob(<span class="hljs-string">'&lt;pattern&gt;'</span>)
  984. </code></pre>
  985. <pre><code class="python language-python hljs">&lt;str&gt; = str(&lt;Path&gt;) <span class="hljs-comment"># Returns path as a string.</span>
  986. &lt;tup.&gt; = &lt;Path&gt;.parts <span class="hljs-comment"># Returns all components as strings.</span>
  987. &lt;Path&gt; = &lt;Path&gt;.resolve() <span class="hljs-comment"># Returns absolute Path without symlinks.</span>
  988. </code></pre>
  989. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;Path&gt;.name <span class="hljs-comment"># Final component.</span>
  990. &lt;str&gt; = &lt;Path&gt;.stem <span class="hljs-comment"># Final component without extension.</span>
  991. &lt;str&gt; = &lt;Path&gt;.suffix <span class="hljs-comment"># Final component's extension.</span>
  992. &lt;Path&gt; = &lt;Path&gt;.parent <span class="hljs-comment"># Path without final component.</span>
  993. </code></pre>
  994. <h2 id="commandexecution"><a href="#commandexecution" name="commandexecution">#</a>Command Execution</h2>
  995. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> os
  996. &lt;str&gt; = os.popen(&lt;command&gt;).read()
  997. </code></pre>
  998. <h3 id="subprocess">Subprocess</h3>
  999. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> subprocess
  1000. <span class="hljs-meta">&gt;&gt;&gt; </span>a = subprocess.run([<span class="hljs-string">'ls'</span>, <span class="hljs-string">'-a'</span>], stdout=subprocess.PIPE)
  1001. <span class="hljs-meta">&gt;&gt;&gt; </span>a.stdout
  1002. <span class="hljs-string">b'.\n..\nfile1.txt\nfile2.txt\n'</span>
  1003. <span class="hljs-meta">&gt;&gt;&gt; </span>a.returncode
  1004. <span class="hljs-number">0</span>
  1005. </code></pre>
  1006. <h2 id="csv"><a href="#csv" name="csv">#</a>CSV</h2>
  1007. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> csv
  1008. </code></pre>
  1009. <h3 id="readrowsfromcsvfile">Read Rows from CSV File</h3>
  1010. <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>
  1011. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1012. <span class="hljs-keyword">return</span> csv.reader(file, delimiter=<span class="hljs-string">';'</span>)
  1013. </code></pre>
  1014. <h3 id="writerowstocsvfile">Write Rows to CSV File</h3>
  1015. <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>
  1016. <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:
  1017. writer = csv.writer(file, delimiter=<span class="hljs-string">';'</span>)
  1018. writer.writerows(rows)
  1019. </code></pre>
  1020. <h2 id="json"><a href="#json" name="json">#</a>JSON</h2>
  1021. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> json
  1022. &lt;str&gt; = json.dumps(&lt;object&gt;, ensure_ascii=<span class="hljs-keyword">True</span>, indent=<span class="hljs-keyword">None</span>)
  1023. &lt;object&gt; = json.loads(&lt;str&gt;)
  1024. </code></pre>
  1025. <h3 id="readobjectfromjsonfile">Read Object from JSON File</h3>
  1026. <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>
  1027. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1028. <span class="hljs-keyword">return</span> json.load(file)
  1029. </code></pre>
  1030. <h3 id="writeobjecttojsonfile">Write Object to JSON File</h3>
  1031. <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>
  1032. <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:
  1033. json.dump(an_object, file, ensure_ascii=<span class="hljs-keyword">False</span>, indent=<span class="hljs-number">2</span>)
  1034. </code></pre>
  1035. <h2 id="pickle"><a href="#pickle" name="pickle">#</a>Pickle</h2>
  1036. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> pickle
  1037. &lt;bytes&gt; = pickle.dumps(&lt;object&gt;)
  1038. &lt;object&gt; = pickle.loads(&lt;bytes&gt;)
  1039. </code></pre>
  1040. <h3 id="readobjectfromfile">Read Object from File</h3>
  1041. <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>
  1042. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1043. <span class="hljs-keyword">return</span> pickle.load(file)
  1044. </code></pre>
  1045. <h3 id="writeobjecttofile">Write Object to File</h3>
  1046. <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>
  1047. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1048. pickle.dump(an_object, file)
  1049. </code></pre>
  1050. <h2 id="sqlite"><a href="#sqlite" name="sqlite">#</a>SQLite</h2>
  1051. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> sqlite3
  1052. db = sqlite3.connect(<span class="hljs-string">'&lt;path&gt;'</span>)
  1053. ...
  1054. db.close()
  1055. </code></pre>
  1056. <h3 id="read">Read</h3>
  1057. <pre><code class="python language-python hljs">cursor = db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1058. <span class="hljs-keyword">if</span> cursor:
  1059. &lt;tuple&gt; = cursor.fetchone() <span class="hljs-comment"># First row.</span>
  1060. &lt;list&gt; = cursor.fetchall() <span class="hljs-comment"># Remaining rows.</span>
  1061. </code></pre>
  1062. <h3 id="write">Write</h3>
  1063. <pre><code class="python language-python hljs">db.execute(<span class="hljs-string">'&lt;query&gt;'</span>)
  1064. db.commit()
  1065. </code></pre>
  1066. <h2 id="bytes"><a href="#bytes" name="bytes">#</a>Bytes</h2>
  1067. <p><strong>Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.</strong></p>
  1068. <pre><code class="python language-python hljs">&lt;bytes&gt; = <span class="hljs-string">b'&lt;str&gt;'</span>
  1069. &lt;int&gt; = &lt;bytes&gt;[&lt;index&gt;]
  1070. &lt;bytes&gt; = &lt;bytes&gt;[&lt;slice&gt;]
  1071. &lt;ints&gt; = list(&lt;bytes&gt;)
  1072. &lt;bytes&gt; = <span class="hljs-string">b''</span>.join(&lt;coll_of_bytes&gt;)
  1073. </code></pre>
  1074. <h3 id="encode-1">Encode</h3>
  1075. <pre><code class="python language-python hljs">&lt;bytes&gt; = &lt;str&gt;.encode(encoding=<span class="hljs-string">'utf-8'</span>)
  1076. &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>)
  1077. &lt;bytes&gt; = bytes.fromhex(<span class="hljs-string">'&lt;hex&gt;'</span>)
  1078. </code></pre>
  1079. <h3 id="decode-1">Decode</h3>
  1080. <pre><code class="python language-python hljs">&lt;str&gt; = &lt;bytes&gt;.decode(encoding=<span class="hljs-string">'utf-8'</span>)
  1081. &lt;int&gt; = int.from_bytes(&lt;bytes&gt;, byteorder=<span class="hljs-string">'big|little'</span>, signed=<span class="hljs-keyword">False</span>)
  1082. &lt;hex&gt; = &lt;bytes&gt;.hex()
  1083. </code></pre>
  1084. <h3 id="readbytesfromfile">Read Bytes from File</h3>
  1085. <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>
  1086. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> file:
  1087. <span class="hljs-keyword">return</span> file.read()
  1088. </code></pre>
  1089. <h3 id="writebytestofile">Write Bytes to File</h3>
  1090. <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>
  1091. <span class="hljs-keyword">with</span> open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> file:
  1092. file.write(bytes_obj)
  1093. </code></pre>
  1094. <h2 id="struct"><a href="#struct" name="struct">#</a>Struct</h2>
  1095. <ul>
  1096. <li><strong>Module that performs conversions between Python values and a C struct, represented as a Python bytes object.</strong></li>
  1097. <li><strong>Machine’s native type sizes and byte order are used by default.</strong></li>
  1098. </ul>
  1099. <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
  1100. &lt;bytes&gt; = pack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;value_1&gt; [, &lt;value_2&gt;, ...])
  1101. &lt;tuple&gt; = unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1102. &lt;tuples&gt; = iter_unpack(<span class="hljs-string">'&lt;format&gt;'</span>, &lt;bytes&gt;)
  1103. </code></pre>
  1104. <h3 id="example">Example</h3>
  1105. <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>)
  1106. <span class="hljs-string">b'\x00\x01\x00\x02\x00\x00\x00\x03'</span>
  1107. <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>)
  1108. (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
  1109. <span class="hljs-meta">&gt;&gt;&gt; </span>calcsize(<span class="hljs-string">'&gt;hhl'</span>)
  1110. <span class="hljs-number">8</span>
  1111. </code></pre>
  1112. <h3 id="format-2">Format</h3>
  1113. <h4 id="forstandardsizesstartformatstringwith">For standard sizes start format string with:</h4>
  1114. <ul>
  1115. <li><strong><code class="python hljs"><span class="hljs-string">'='</span></code> - native byte order</strong></li>
  1116. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;'</span></code> - little-endian</strong></li>
  1117. <li><strong><code class="python hljs"><span class="hljs-string">'&gt;'</span></code> - big-endian</strong></li>
  1118. </ul>
  1119. <h4 id="usecapitalletterforunsignedtypestandardsizesareinbrackets">Use capital letter for unsigned type. Standard sizes are in brackets:</h4>
  1120. <ul>
  1121. <li><strong><code class="python hljs"><span class="hljs-string">'x'</span></code> - pad byte</strong></li>
  1122. <li><strong><code class="python hljs"><span class="hljs-string">'c'</span></code> - char (1)</strong></li>
  1123. <li><strong><code class="python hljs"><span class="hljs-string">'h'</span></code> - short (2)</strong></li>
  1124. <li><strong><code class="python hljs"><span class="hljs-string">'i'</span></code> - int (4)</strong></li>
  1125. <li><strong><code class="python hljs"><span class="hljs-string">'l'</span></code> - long (4)</strong></li>
  1126. <li><strong><code class="python hljs"><span class="hljs-string">'q'</span></code> - long long (8)</strong></li>
  1127. <li><strong><code class="python hljs"><span class="hljs-string">'f'</span></code> - float (4)</strong></li>
  1128. <li><strong><code class="python hljs"><span class="hljs-string">'d'</span></code> - double (8)</strong></li>
  1129. </ul>
  1130. <h2 id="array"><a href="#array" name="array">#</a>Array</h2>
  1131. <p><strong>List that can hold only elements of predefined type. Available types are listed above.</strong></p>
  1132. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> array <span class="hljs-keyword">import</span> array
  1133. &lt;array&gt; = array(<span class="hljs-string">'&lt;typecode&gt;'</span> [, &lt;collection&gt;])
  1134. </code></pre>
  1135. <h2 id="memoryview"><a href="#memoryview" name="memoryview">#</a>Memory View</h2>
  1136. <p><strong>Used for accessing the internal data of an object that supports the buffer protocol.</strong></p>
  1137. <pre><code class="python language-python hljs">&lt;memoryview&gt; = memoryview(&lt;bytes&gt; / &lt;bytearray&gt; / &lt;array&gt;)
  1138. &lt;memoryview&gt;.release()
  1139. </code></pre>
  1140. <h2 id="deque"><a href="#deque" name="deque">#</a>Deque</h2>
  1141. <p><strong>Thread-safe list with efficient appends and pops from either side. Pronounced "deck".</strong></p>
  1142. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> deque
  1143. &lt;deque&gt; = deque(&lt;collection&gt;, maxlen=<span class="hljs-keyword">None</span>)
  1144. </code></pre>
  1145. <pre><code class="python language-python hljs">&lt;deque&gt;.appendleft(&lt;el&gt;)
  1146. &lt;el&gt; = &lt;deque&gt;.popleft()
  1147. </code></pre>
  1148. <pre><code class="python language-python hljs">&lt;deque&gt;.extendleft(&lt;collection&gt;) <span class="hljs-comment"># Collection gets reversed.</span>
  1149. &lt;deque&gt;.rotate(n=<span class="hljs-number">1</span>) <span class="hljs-comment"># Rotates elements to the right.</span>
  1150. </code></pre>
  1151. <h2 id="threading"><a href="#threading" name="threading">#</a>Threading</h2>
  1152. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> threading <span class="hljs-keyword">import</span> Thread, RLock
  1153. </code></pre>
  1154. <h3 id="thread">Thread</h3>
  1155. <pre><code class="python language-python hljs">thread = Thread(target=&lt;function&gt;, args=(&lt;first_arg&gt;, ))
  1156. thread.start()
  1157. ...
  1158. thread.join()
  1159. </code></pre>
  1160. <h3 id="lock">Lock</h3>
  1161. <pre><code class="python language-python hljs">lock = RLock()
  1162. lock.acquire()
  1163. ...
  1164. lock.release()
  1165. </code></pre>
  1166. <h2 id="introspection"><a href="#introspection" name="introspection">#</a>Introspection</h2>
  1167. <p><strong>Inspecting code at runtime.</strong></p>
  1168. <h3 id="variables">Variables</h3>
  1169. <pre><code class="python language-python hljs">&lt;list&gt; = dir() <span class="hljs-comment"># Names of variables in current scope.</span>
  1170. &lt;dict&gt; = locals() <span class="hljs-comment"># Dict of local variables. Also vars().</span>
  1171. &lt;dict&gt; = globals() <span class="hljs-comment"># Dict of global variables.</span>
  1172. </code></pre>
  1173. <h3 id="attributes">Attributes</h3>
  1174. <pre><code class="python language-python hljs">&lt;dict&gt; = vars(&lt;object&gt;)
  1175. &lt;bool&gt; = hasattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1176. value = getattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>)
  1177. setattr(&lt;object&gt;, <span class="hljs-string">'&lt;attr_name&gt;'</span>, value)
  1178. </code></pre>
  1179. <h3 id="parameters">Parameters</h3>
  1180. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> inspect <span class="hljs-keyword">import</span> signature
  1181. &lt;sig&gt; = signature(&lt;function&gt;)
  1182. no_of_params = len(&lt;sig&gt;.parameters)
  1183. param_names = list(&lt;sig&gt;.parameters.keys())
  1184. </code></pre>
  1185. <h2 id="metaprograming"><a href="#metaprograming" name="metaprograming">#</a>Metaprograming</h2>
  1186. <p><strong>Code that generates code.</strong></p>
  1187. <h3 id="type-1">Type</h3>
  1188. <p><strong>Type is the root class. If only passed the object it returns its type (class). Otherwise it creates a new class.</strong></p>
  1189. <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>
  1190. </span></code></pre>
  1191. <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>})
  1192. <span class="hljs-meta">&gt;&gt;&gt; </span>z = Z()
  1193. </code></pre>
  1194. <h3 id="metaclass">Meta Class</h3>
  1195. <p><strong>Class that creates class.</strong></p>
  1196. <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>
  1197. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1198. <span class="hljs-keyword">return</span> type(name, parents, attrs)
  1199. </code></pre>
  1200. <h4 id="or">Or:</h4>
  1201. <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>
  1202. <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>
  1203. attrs[<span class="hljs-string">'a'</span>] = <span class="hljs-string">'abcde'</span>
  1204. <span class="hljs-keyword">return</span> type.__new__(cls, name, parents, attrs)
  1205. </code></pre>
  1206. <ul>
  1207. <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>
  1208. <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>
  1209. <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>
  1210. </ul>
  1211. <h3 id="metaclassattribute">Metaclass Attribute</h3>
  1212. <p><strong>When 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>
  1213. <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>
  1214. b = <span class="hljs-number">12345</span>
  1215. </code></pre>
  1216. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>MyClass.a, MyClass.b
  1217. (<span class="hljs-string">'abcde'</span>, <span class="hljs-number">12345</span>)
  1218. </code></pre>
  1219. <h4 id="typediagramabcisastrstrisatype">Type diagram ('abc' is a str, str is a type, …):</h4>
  1220. <pre><code class="text language-text">┏━━━━━━━━━┯━━━━━━━━━━━━━┓
  1221. ┃ classes │ metaclasses ┃
  1222. ┠─────────┼─────────────┨
  1223. ┃ MyClass → MyMetaClass ┃
  1224. ┃ │ ↓ ┃
  1225. ┃ object ───→ type ←╮ ┃
  1226. ┃ │ ↑ ╰───╯ ┃
  1227. ┃ str ───────╯ ┃
  1228. ┗━━━━━━━━━┷━━━━━━━━━━━━━┛
  1229. </code></pre>
  1230. <h4 id="inheritancediagramstrinheritsfromobject">Inheritance diagram (str inherits from object, …):</h4>
  1231. <pre><code class="text language-text">┏━━━━━━━━━┯━━━━━━━━━━━━━┓
  1232. ┃ classes │ metaclasses ┃
  1233. ┠─────────┼─────────────┨
  1234. ┃ MyClass │ MyMetaClass ┃
  1235. ┃ ↓ │ ↓ ┃
  1236. ┃ object ←─── type ┃
  1237. ┃ ↑ │ ┃
  1238. ┃ str │ ┃
  1239. ┗━━━━━━━━━┷━━━━━━━━━━━━━┛
  1240. </code></pre>
  1241. <h2 id="operator"><a href="#operator" name="operator">#</a>Operator</h2>
  1242. <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
  1243. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> eq, ne, lt, le, gt, ge
  1244. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> not_, and_, or_
  1245. <span class="hljs-keyword">from</span> operator <span class="hljs-keyword">import</span> itemgetter, attrgetter, methodcaller
  1246. </code></pre>
  1247. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  1248. product_of_elems = functools.reduce(op.mul, &lt;collection&gt;)
  1249. sorted_by_second = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>))
  1250. sorted_by_both = sorted(&lt;collection&gt;, key=op.itemgetter(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>))
  1251. 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_})
  1252. last_el = op.methodcaller(<span class="hljs-string">'pop'</span>)(&lt;list&gt;)
  1253. </code></pre>
  1254. <h2 id="eval"><a href="#eval" name="eval">#</a>Eval</h2>
  1255. <h3 id="basic">Basic</h3>
  1256. <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
  1257. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'1 + 2'</span>)
  1258. <span class="hljs-number">3</span>
  1259. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'[1, 2, 3]'</span>)
  1260. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
  1261. <span class="hljs-meta">&gt;&gt;&gt; </span>literal_eval(<span class="hljs-string">'abs(1)'</span>)
  1262. ValueError: malformed node <span class="hljs-keyword">or</span> string
  1263. </code></pre>
  1264. <h3 id="usingabstractsyntaxtrees">Using Abstract Syntax Trees</h3>
  1265. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> ast
  1266. <span class="hljs-keyword">from</span> ast <span class="hljs-keyword">import</span> Num, BinOp, UnaryOp
  1267. <span class="hljs-keyword">import</span> operator <span class="hljs-keyword">as</span> op
  1268. LEGAL_OPERATORS = {ast.Add: op.add, <span class="hljs-comment"># &lt;el&gt; + &lt;el&gt;</span>
  1269. ast.Sub: op.sub, <span class="hljs-comment"># &lt;el&gt; - &lt;el&gt;</span>
  1270. ast.Mult: op.mul, <span class="hljs-comment"># &lt;el&gt; * &lt;el&gt;</span>
  1271. ast.Div: op.truediv, <span class="hljs-comment"># &lt;el&gt; / &lt;el&gt;</span>
  1272. ast.Pow: op.pow, <span class="hljs-comment"># &lt;el&gt; ** &lt;el&gt;</span>
  1273. ast.BitXor: op.xor, <span class="hljs-comment"># &lt;el&gt; ^ &lt;el&gt;</span>
  1274. ast.USub: op.neg} <span class="hljs-comment"># - &lt;el&gt;</span>
  1275. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">evaluate</span><span class="hljs-params">(expression)</span>:</span>
  1276. root = ast.parse(expression, mode=<span class="hljs-string">'eval'</span>)
  1277. <span class="hljs-keyword">return</span> eval_node(root.body)
  1278. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">eval_node</span><span class="hljs-params">(node)</span>:</span>
  1279. node_type = type(node)
  1280. <span class="hljs-keyword">if</span> node_type == Num:
  1281. <span class="hljs-keyword">return</span> node.n
  1282. <span class="hljs-keyword">if</span> node_type <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> [BinOp, UnaryOp]:
  1283. <span class="hljs-keyword">raise</span> TypeError(node)
  1284. operator_type = type(node.op)
  1285. <span class="hljs-keyword">if</span> operator_type <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> LEGAL_OPERATORS:
  1286. <span class="hljs-keyword">raise</span> TypeError(<span class="hljs-string">f'Illegal operator <span class="hljs-subst">{node.op}</span>'</span>)
  1287. operator = LEGAL_OPERATORS[operator_type]
  1288. <span class="hljs-keyword">if</span> node_type == BinOp:
  1289. left, right = eval_node(node.left), eval_node(node.right)
  1290. <span class="hljs-keyword">return</span> operator(left, right)
  1291. <span class="hljs-keyword">elif</span> node_type == UnaryOp:
  1292. operand = eval_node(node.operand)
  1293. <span class="hljs-keyword">return</span> operator(operand)
  1294. </code></pre>
  1295. <pre><code class="python language-python hljs"><span class="hljs-meta">&gt;&gt;&gt; </span>evaluate(<span class="hljs-string">'2 ^ 6'</span>)
  1296. <span class="hljs-number">4</span>
  1297. <span class="hljs-meta">&gt;&gt;&gt; </span>evaluate(<span class="hljs-string">'2 ** 6'</span>)
  1298. <span class="hljs-number">64</span>
  1299. <span class="hljs-meta">&gt;&gt;&gt; </span>evaluate(<span class="hljs-string">'1 + 2 * 3 ** (4 ^ 5) / (6 + -7)'</span>)
  1300. <span class="hljs-number">-5.0</span>
  1301. </code></pre>
  1302. <h2 id="coroutine"><a href="#coroutine" name="coroutine">#</a>Coroutine</h2>
  1303. <ul>
  1304. <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>
  1305. <li><strong>Coroutines provide more powerful data routing possibilities than iterators.</strong></li>
  1306. <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>
  1307. </ul>
  1308. <h3 id="helperdecorator">Helper Decorator</h3>
  1309. <ul>
  1310. <li><strong>All coroutines must be "primed" by first calling next().</strong></li>
  1311. <li><strong>Remembering to call next() is easy to forget.</strong></li>
  1312. <li><strong>Solved by wrapping coroutines with a decorator:</strong></li>
  1313. </ul>
  1314. <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>
  1315. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">out</span><span class="hljs-params">(*args, **kwargs)</span>:</span>
  1316. cr = func(*args, **kwargs)
  1317. next(cr)
  1318. <span class="hljs-keyword">return</span> cr
  1319. <span class="hljs-keyword">return</span> out
  1320. </code></pre>
  1321. <h3 id="pipelineexample">Pipeline Example</h3>
  1322. <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>
  1323. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">10</span>):
  1324. target.send(i)
  1325. target.close()
  1326. <span class="hljs-meta">@coroutine</span>
  1327. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">adder</span><span class="hljs-params">(target)</span>:</span>
  1328. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1329. value = (<span class="hljs-keyword">yield</span>)
  1330. target.send(value + <span class="hljs-number">100</span>)
  1331. <span class="hljs-meta">@coroutine</span>
  1332. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">printer</span><span class="hljs-params">()</span>:</span>
  1333. <span class="hljs-keyword">while</span> <span class="hljs-keyword">True</span>:
  1334. value = (<span class="hljs-keyword">yield</span>)
  1335. print(value)
  1336. reader(adder(printer())) <span class="hljs-comment"># 100, 101, ..., 109</span>
  1337. </code></pre>
  1338. <p><br><br></p>
  1339. <h1 id="libraries">Libraries</h1>
  1340. <h2 id="progressbar"><a href="#progressbar" name="progressbar">#</a>Progress Bar</h2>
  1341. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install tqdm</span>
  1342. <span class="hljs-keyword">from</span> tqdm <span class="hljs-keyword">import</span> tqdm
  1343. <span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> sleep
  1344. <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>]):
  1345. sleep(<span class="hljs-number">0.2</span>)
  1346. <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> tqdm(range(<span class="hljs-number">100</span>)):
  1347. sleep(<span class="hljs-number">0.02</span>)
  1348. </code></pre>
  1349. <h2 id="plot"><a href="#plot" name="plot">#</a>Plot</h2>
  1350. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install matplotlib</span>
  1351. <span class="hljs-keyword">from</span> matplotlib <span class="hljs-keyword">import</span> pyplot
  1352. pyplot.plot(&lt;data_1&gt; [, &lt;data_2&gt;, ...])
  1353. pyplot.savefig(&lt;filename&gt;)
  1354. pyplot.show()
  1355. </code></pre>
  1356. <h2 id="table"><a href="#table" name="table">#</a>Table</h2>
  1357. <h4 id="printsacsvfileasanasciitable">Prints a CSV file as an ASCII table:</h4>
  1358. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install tabulate</span>
  1359. <span class="hljs-keyword">from</span> tabulate <span class="hljs-keyword">import</span> tabulate
  1360. <span class="hljs-keyword">import</span> csv
  1361. <span class="hljs-keyword">with</span> open(&lt;filename&gt;, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1362. lines = csv.reader(file, delimiter=<span class="hljs-string">';'</span>)
  1363. headers = [header.title() <span class="hljs-keyword">for</span> header <span class="hljs-keyword">in</span> next(lines)]
  1364. table = tabulate(lines, headers)
  1365. print(table)
  1366. </code></pre>
  1367. <h2 id="curses"><a href="#curses" name="curses">#</a>Curses</h2>
  1368. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> curses <span class="hljs-keyword">import</span> wrapper, ascii
  1369. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1370. wrapper(draw)
  1371. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">draw</span><span class="hljs-params">(screen)</span>:</span>
  1372. screen.clear()
  1373. screen.addstr(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, <span class="hljs-string">'Press ESC to quit.'</span>)
  1374. <span class="hljs-keyword">while</span> screen.getch() != ascii.ESC:
  1375. <span class="hljs-keyword">pass</span>
  1376. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_border</span><span class="hljs-params">(screen)</span>:</span>
  1377. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1378. P = namedtuple(<span class="hljs-string">'P'</span>, <span class="hljs-string">'y x'</span>)
  1379. height, width = screen.getmaxyx()
  1380. <span class="hljs-keyword">return</span> P(height<span class="hljs-number">-1</span>, width<span class="hljs-number">-1</span>)
  1381. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1382. main()
  1383. </code></pre>
  1384. <h2 id="logging"><a href="#logging" name="logging">#</a>Logging</h2>
  1385. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install loguru</span>
  1386. <span class="hljs-keyword">from</span> loguru <span class="hljs-keyword">import</span> logger
  1387. </code></pre>
  1388. <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>
  1389. 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>
  1390. logger.&lt;level&gt;(<span class="hljs-string">'A logging message'</span>)
  1391. </code></pre>
  1392. <ul>
  1393. <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>
  1394. </ul>
  1395. <h3 id="rotation">Rotation</h3>
  1396. <p><strong>Parameter that sets a condition when a new log file is created.</strong></p>
  1397. <pre><code class="python language-python hljs">rotation=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;datetime.time&gt;|&lt;str&gt;
  1398. </code></pre>
  1399. <ul>
  1400. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max file size in bytes.</strong></li>
  1401. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1402. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;time&gt;'</span></code> - Time of day.</strong></li>
  1403. <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>
  1404. </ul>
  1405. <h3 id="retention">Retention</h3>
  1406. <p><strong>Sets a condition which old log files are deleted.</strong></p>
  1407. <pre><code class="python language-python hljs">retention=&lt;int&gt;|&lt;datetime.timedelta&gt;|&lt;str&gt;
  1408. </code></pre>
  1409. <ul>
  1410. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;int&gt;'</span></code> - Max number of files.</strong></li>
  1411. <li><strong><code class="python hljs"><span class="hljs-string">'&lt;timedelta&gt;'</span></code> - Max age of a file.</strong></li>
  1412. <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>
  1413. </ul>
  1414. <h3 id="compression">Compression</h3>
  1415. <p><strong>Sets how inactive log files are compressed.</strong></p>
  1416. <pre><code class="python language-python hljs">compression=<span class="hljs-string">'gz'</span>|<span class="hljs-string">'bz2'</span>|<span class="hljs-string">'tar'</span>|<span class="hljs-string">'tar.gz'</span>|<span class="hljs-string">'tar.bz2'</span>|<span class="hljs-string">'zip'</span>
  1417. </code></pre>
  1418. <h2 id="scraping"><a href="#scraping" name="scraping">#</a>Scraping</h2>
  1419. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests beautifulsoup4</span>
  1420. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests
  1421. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">from</span> bs4 <span class="hljs-keyword">import</span> BeautifulSoup
  1422. <span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'https://en.wikipedia.org/wiki/Python_(programming_language)'</span>
  1423. <span class="hljs-meta">&gt;&gt;&gt; </span>page = requests.get(url)
  1424. <span class="hljs-meta">&gt;&gt;&gt; </span>doc = BeautifulSoup(page.text, <span class="hljs-string">'html.parser'</span>)
  1425. <span class="hljs-meta">&gt;&gt;&gt; </span>table = doc.find(<span class="hljs-string">'table'</span>, class_=<span class="hljs-string">'infobox vevent'</span>)
  1426. <span class="hljs-meta">&gt;&gt;&gt; </span>rows = table.find_all(<span class="hljs-string">'tr'</span>)
  1427. <span class="hljs-meta">&gt;&gt;&gt; </span>link = rows[<span class="hljs-number">11</span>].find(<span class="hljs-string">'a'</span>)[<span class="hljs-string">'href'</span>]
  1428. <span class="hljs-meta">&gt;&gt;&gt; </span>ver = rows[<span class="hljs-number">6</span>].find(<span class="hljs-string">'div'</span>).text.split()[<span class="hljs-number">0</span>]
  1429. <span class="hljs-meta">&gt;&gt;&gt; </span>link, ver
  1430. (<span class="hljs-string">'https://www.python.org/'</span>, <span class="hljs-string">'3.7.2'</span>)
  1431. </code></pre>
  1432. <h2 id="web"><a href="#web" name="web">#</a>Web</h2>
  1433. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install bottle</span>
  1434. <span class="hljs-keyword">from</span> bottle <span class="hljs-keyword">import</span> run, route, post, template, request, response
  1435. <span class="hljs-keyword">import</span> json
  1436. </code></pre>
  1437. <h3 id="run">Run</h3>
  1438. <pre><code class="python language-python hljs">run(host=<span class="hljs-string">'localhost'</span>, port=<span class="hljs-number">8080</span>)
  1439. 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>)
  1440. </code></pre>
  1441. <h3 id="staticrequest">Static Request</h3>
  1442. <pre><code class="python language-python hljs"><span class="hljs-meta">@route('/img/&lt;image&gt;')</span>
  1443. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_image</span><span class="hljs-params">(image)</span>:</span>
  1444. <span class="hljs-keyword">return</span> static_file(image, <span class="hljs-string">'images/'</span>, mimetype=<span class="hljs-string">'image/png'</span>)
  1445. </code></pre>
  1446. <h3 id="dynamicrequest">Dynamic Request</h3>
  1447. <pre><code class="python language-python hljs"><span class="hljs-meta">@route('/&lt;sport&gt;')</span>
  1448. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">send_page</span><span class="hljs-params">(sport)</span>:</span>
  1449. <span class="hljs-keyword">return</span> template(<span class="hljs-string">'&lt;h1&gt;{{title}}&lt;/h1&gt;'</span>, title=sport)
  1450. </code></pre>
  1451. <h3 id="restrequest">REST Request</h3>
  1452. <pre><code class="python language-python hljs"><span class="hljs-meta">@post('/odds/&lt;sport&gt;')</span>
  1453. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">odds_handler</span><span class="hljs-params">(sport)</span>:</span>
  1454. team = request.forms.get(<span class="hljs-string">'team'</span>)
  1455. home_odds, away_odds = <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>
  1456. response.headers[<span class="hljs-string">'Content-Type'</span>] = <span class="hljs-string">'application/json'</span>
  1457. response.headers[<span class="hljs-string">'Cache-Control'</span>] = <span class="hljs-string">'no-cache'</span>
  1458. <span class="hljs-keyword">return</span> json.dumps([team, home_odds, away_odds])
  1459. </code></pre>
  1460. <h4 id="test">Test:</h4>
  1461. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install requests</span>
  1462. <span class="hljs-meta">&gt;&gt;&gt; </span><span class="hljs-keyword">import</span> requests
  1463. <span class="hljs-meta">&gt;&gt;&gt; </span>url = <span class="hljs-string">'http://localhost:8080/odds/football'</span>
  1464. <span class="hljs-meta">&gt;&gt;&gt; </span>data = {<span class="hljs-string">'team'</span>: <span class="hljs-string">'arsenal f.c.'</span>}
  1465. <span class="hljs-meta">&gt;&gt;&gt; </span>response = requests.post(url, data=data)
  1466. <span class="hljs-meta">&gt;&gt;&gt; </span>response.json()
  1467. [<span class="hljs-string">'arsenal f.c.'</span>, <span class="hljs-number">2.44</span>, <span class="hljs-number">3.29</span>]
  1468. </code></pre>
  1469. <h2 id="profile"><a href="#profile" name="profile">#</a>Profile</h2>
  1470. <h3 id="basic-1">Basic</h3>
  1471. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> time <span class="hljs-keyword">import</span> time
  1472. start_time = time() <span class="hljs-comment"># Seconds since Epoch.</span>
  1473. ...
  1474. duration = time() - start_time
  1475. </code></pre>
  1476. <h3 id="highperformance">High Performance</h3>
  1477. <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
  1478. start_time = pc() <span class="hljs-comment"># Seconds since restart.</span>
  1479. ...
  1480. duration = pc() - start_time
  1481. </code></pre>
  1482. <h3 id="timingasnippet">Timing a Snippet</h3>
  1483. <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
  1484. <span class="hljs-meta">&gt;&gt;&gt; </span>timeit(<span class="hljs-string">'"-".join(str(a) for a in range(100))'</span>,
  1485. <span class="hljs-meta">... </span> number=<span class="hljs-number">10000</span>, globals=globals(), setup=<span class="hljs-string">'pass'</span>)
  1486. <span class="hljs-number">0.34986</span>
  1487. </code></pre>
  1488. <h3 id="lineprofiler">Line Profiler</h3>
  1489. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install line_profiler</span>
  1490. <span class="hljs-meta">@profile</span>
  1491. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1492. a = [*range(<span class="hljs-number">10000</span>)]
  1493. b = {*range(<span class="hljs-number">10000</span>)}
  1494. main()
  1495. </code></pre>
  1496. <h4 id="usage">Usage:</h4>
  1497. <pre><code class="text language-text">$ kernprof -lv test.py
  1498. Line # Hits Time Per Hit % Time Line Contents
  1499. ==============================================================
  1500. 1 @profile
  1501. 2 def main():
  1502. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1503. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1504. </code></pre>
  1505. <h3 id="callgraph">Call Graph</h3>
  1506. <h4 id="generatesapngimageofacallgraphwithhighlightedbottlenecks">Generates a PNG image of a call graph with highlighted bottlenecks:</h4>
  1507. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pycallgraph</span>
  1508. <span class="hljs-keyword">from</span> pycallgraph <span class="hljs-keyword">import</span> output, PyCallGraph
  1509. <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
  1510. time_str = datetime.now().strftime(<span class="hljs-string">'%Y%m%d%H%M%S'</span>)
  1511. filename = <span class="hljs-string">f'profile-<span class="hljs-subst">{time_str}</span>.png'</span>
  1512. drawer = output.GraphvizOutput(output_file=filename)
  1513. <span class="hljs-keyword">with</span> PyCallGraph(output=drawer):
  1514. &lt;code_to_be_profiled&gt;
  1515. </code></pre>
  1516. <h2 id="numpy"><a href="#numpy" name="numpy">#</a>NumPy</h2>
  1517. <p><strong>Array manipulation mini language. Can run up to one hundred times faster than equivalent Python code.</strong></p>
  1518. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install numpy</span>
  1519. <span class="hljs-keyword">import</span> numpy <span class="hljs-keyword">as</span> np
  1520. </code></pre>
  1521. <pre><code class="python language-python hljs">&lt;array&gt; = np.array(&lt;list&gt;)
  1522. &lt;array&gt; = np.arange(from_inclusive, to_exclusive, ±step_size)
  1523. &lt;array&gt; = np.ones(&lt;shape&gt;)
  1524. &lt;array&gt; = np.random.randint(from_inclusive, to_exclusive, &lt;shape&gt;)
  1525. </code></pre>
  1526. <pre><code class="python language-python hljs">&lt;array&gt;.shape = &lt;shape&gt;
  1527. &lt;view&gt; = &lt;array&gt;.reshape(&lt;shape&gt;)
  1528. &lt;view&gt; = np.broadcast_to(&lt;array&gt;, &lt;shape&gt;)
  1529. </code></pre>
  1530. <pre><code class="python language-python hljs">&lt;array&gt; = &lt;array&gt;.sum(axis)
  1531. indexes = &lt;array&gt;.argmin(axis)
  1532. </code></pre>
  1533. <ul>
  1534. <li><strong>Shape is a tuple of dimension sizes.</strong></li>
  1535. <li><strong>Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.</strong></li>
  1536. </ul>
  1537. <h3 id="indexing">Indexing</h3>
  1538. <pre><code class="bash language-bash hljs">&lt;el&gt; = &lt;2d_array&gt;[0, 0] <span class="hljs-comment"># First element.</span>
  1539. &lt;1d_view&gt; = &lt;2d_array&gt;[0] <span class="hljs-comment"># First row.</span>
  1540. &lt;1d_view&gt; = &lt;2d_array&gt;[:, 0] <span class="hljs-comment"># First column. Also [..., 0].</span>
  1541. &lt;3d_view&gt; = &lt;2d_array&gt;[None, :, :] <span class="hljs-comment"># Expanded by dimension of size 1.</span>
  1542. </code></pre>
  1543. <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;]
  1544. &lt;2d_array&gt; = &lt;2d_array&gt;[&lt;2d_row_indexes&gt;, &lt;2d_column_indexes&gt;]
  1545. </code></pre>
  1546. <pre><code class="bash language-bash hljs">&lt;2d_bools&gt; = &lt;2d_array&gt; &gt; 0
  1547. &lt;1d_array&gt; = &lt;2d_array&gt;[&lt;2d_bools&gt;]
  1548. </code></pre>
  1549. <ul>
  1550. <li><strong>If row and column indexes differ in shape, they are combined with broadcasting.</strong></li>
  1551. </ul>
  1552. <h3 id="broadcasting">Broadcasting</h3>
  1553. <p><strong>Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.</strong></p>
  1554. <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>
  1555. 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>
  1556. </code></pre>
  1557. <h4 id="1ifarrayshapesdifferinlengthleftpadtheshortershapewithones">1. If array shapes differ in length, left-pad the shorter shape with ones:</h4>
  1558. <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>
  1559. 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>
  1560. </code></pre>
  1561. <h4 id="2ifanydimensionsdifferinsizeexpandtheonesthathavesize1byduplicatingtheirelements">2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:</h4>
  1562. <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>
  1563. 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>
  1564. </code></pre>
  1565. <h4 id="3ifneithernonmatchingdimensionhassize1riseanerror">3. If neither non-matching dimension has size 1, rise an error.</h4>
  1566. <h3 id="example-1">Example</h3>
  1567. <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>
  1568. <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>])
  1569. [ <span class="hljs-number">0.1</span>, <span class="hljs-number">0.6</span>, <span class="hljs-number">0.8</span>]
  1570. <span class="hljs-meta">&gt;&gt;&gt; </span>wrapped_points = points.reshape(<span class="hljs-number">3</span>, <span class="hljs-number">1</span>)
  1571. [[ <span class="hljs-number">0.1</span>],
  1572. [ <span class="hljs-number">0.6</span>],
  1573. [ <span class="hljs-number">0.8</span>]]
  1574. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = wrapped_points - points
  1575. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">-0.5</span>, <span class="hljs-number">-0.7</span>],
  1576. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">-0.2</span>],
  1577. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1578. <span class="hljs-meta">&gt;&gt;&gt; </span>distances = np.abs(distances)
  1579. [[ <span class="hljs-number">0.</span> , <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1580. [ <span class="hljs-number">0.5</span>, <span class="hljs-number">0.</span> , <span class="hljs-number">0.2</span>],
  1581. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, <span class="hljs-number">0.</span> ]]
  1582. <span class="hljs-meta">&gt;&gt;&gt; </span>i = np.arange(<span class="hljs-number">3</span>)
  1583. [<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
  1584. <span class="hljs-meta">&gt;&gt;&gt; </span>distances[i, i] = np.inf
  1585. [[ inf, <span class="hljs-number">0.5</span>, <span class="hljs-number">0.7</span>],
  1586. [ <span class="hljs-number">0.5</span>, inf, <span class="hljs-number">0.2</span>],
  1587. [ <span class="hljs-number">0.7</span>, <span class="hljs-number">0.2</span>, inf]]
  1588. <span class="hljs-meta">&gt;&gt;&gt; </span>distances.argmin(<span class="hljs-number">1</span>)
  1589. [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>]
  1590. </code></pre>
  1591. <h2 id="image"><a href="#image" name="image">#</a>Image</h2>
  1592. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install pillow</span>
  1593. <span class="hljs-keyword">from</span> PIL <span class="hljs-keyword">import</span> Image
  1594. </code></pre>
  1595. <h4 id="createsapngimageofarainbowgradient">Creates a PNG image of a rainbow gradient:</h4>
  1596. <pre><code class="python language-python hljs">width = <span class="hljs-number">100</span>
  1597. height = <span class="hljs-number">100</span>
  1598. size = width * height
  1599. pixels = [<span class="hljs-number">255</span> * i/size <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(size)]
  1600. img = Image.new(<span class="hljs-string">'HSV'</span>, (width, height))
  1601. 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])
  1602. img.convert(mode=<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1603. </code></pre>
  1604. <h4 id="addsnoisetoapngimage">Adds noise to a PNG image:</h4>
  1605. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint
  1606. 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>)))
  1607. img = Image.open(<span class="hljs-string">'test.png'</span>).convert(mode=<span class="hljs-string">'HSV'</span>)
  1608. img.putdata([(add_noise(h), s, v) <span class="hljs-keyword">for</span> h, s, v <span class="hljs-keyword">in</span> img.getdata()])
  1609. img.convert(mode=<span class="hljs-string">'RGB'</span>).save(<span class="hljs-string">'test.png'</span>)
  1610. </code></pre>
  1611. <h3 id="modes-1">Modes</h3>
  1612. <ul>
  1613. <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>
  1614. <li><strong><code class="python hljs"><span class="hljs-string">'L'</span></code> - 8-bit pixels, greyscale.</strong></li>
  1615. <li><strong><code class="python hljs"><span class="hljs-string">'RGB'</span></code> - 3x8-bit pixels, true color.</strong></li>
  1616. <li><strong><code class="python hljs"><span class="hljs-string">'RGBA'</span></code> - 4x8-bit pixels, true color with transparency mask.</strong></li>
  1617. <li><strong><code class="python hljs"><span class="hljs-string">'HSV'</span></code> - 3x8-bit pixels, Hue, Saturation, Value color space.</strong></li>
  1618. </ul>
  1619. <h2 id="audio"><a href="#audio" name="audio">#</a>Audio</h2>
  1620. <pre><code class="python language-python hljs"><span class="hljs-keyword">import</span> wave
  1621. <span class="hljs-keyword">from</span> struct <span class="hljs-keyword">import</span> pack, iter_unpack
  1622. </code></pre>
  1623. <h3 id="readframesfromwavfile">Read Frames from WAV File</h3>
  1624. <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>
  1625. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'rb'</span>) <span class="hljs-keyword">as</span> wf:
  1626. frames = wf.readframes(wf.getnframes())
  1627. <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)]
  1628. </code></pre>
  1629. <h3 id="writeframestowavfile">Write Frames to WAV File</h3>
  1630. <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>
  1631. 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)
  1632. <span class="hljs-keyword">with</span> wave.open(filename, <span class="hljs-string">'wb'</span>) <span class="hljs-keyword">as</span> wf:
  1633. 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>)
  1634. wf.setsampwidth(<span class="hljs-number">2</span>)
  1635. wf.setframerate(<span class="hljs-number">44100</span>)
  1636. wf.writeframes(<span class="hljs-string">b''</span>.join(frames_short))
  1637. </code></pre>
  1638. <h3 id="examples">Examples</h3>
  1639. <h4 id="savesasinewavetoamonowavfile">Saves a sine wave to a mono WAV file:</h4>
  1640. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> pi, sin
  1641. 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>))
  1642. 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)
  1643. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, frames_i)
  1644. </code></pre>
  1645. <h4 id="addsnoisetoamonowavfile">Adds noise to a mono WAV file:</h4>
  1646. <pre><code class="python language-python hljs"><span class="hljs-keyword">from</span> random <span class="hljs-keyword">import</span> randint
  1647. 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>)))
  1648. 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>))
  1649. write_to_wav_file(<span class="hljs-string">'test.wav'</span>, frames_i)
  1650. </code></pre>
  1651. <h4 id="playspopcorn">Plays Popcorn:</h4>
  1652. <pre><code class="python language-python hljs"><span class="hljs-comment"># $ pip3 install simpleaudio</span>
  1653. <span class="hljs-keyword">import</span> simpleaudio, math, struct
  1654. <span class="hljs-keyword">from</span> itertools <span class="hljs-keyword">import</span> chain, repeat
  1655. F = <span class="hljs-number">44100</span>
  1656. P1 = <span class="hljs-string">'71♪,69,,71♪,66,,62♪,66,,59♪,,,'</span>
  1657. P2 = <span class="hljs-string">'71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,'</span>
  1658. get_pause = <span class="hljs-keyword">lambda</span> seconds: repeat(<span class="hljs-number">0</span>, int(seconds * F))
  1659. sin_f = <span class="hljs-keyword">lambda</span> i, hz: math.sin(i * <span class="hljs-number">2</span> * math.pi * hz / F)
  1660. 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)))
  1661. 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>)
  1662. parse_n = <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>)
  1663. get_note = <span class="hljs-keyword">lambda</span> note: get_wave(*parse_n(note)) <span class="hljs-keyword">if</span> note <span class="hljs-keyword">else</span> get_pause(<span class="hljs-number">0.125</span>)
  1664. frames_i = chain.from_iterable(get_note(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>))
  1665. frames_b = <span class="hljs-string">b''</span>.join(struct.pack(<span class="hljs-string">'&lt;h'</span>, int(a * <span class="hljs-number">30000</span>)) <span class="hljs-keyword">for</span> a <span class="hljs-keyword">in</span> frames_i)
  1666. simpleaudio.play_buffer(frames_b, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, F)
  1667. </code></pre>
  1668. <h2 id="basicscripttemplate"><a href="#basicscripttemplate" name="basicscripttemplate">#</a>Basic Script Template</h2>
  1669. <pre><code class="python language-python hljs"><span class="hljs-comment">#!/usr/bin/env python3</span>
  1670. <span class="hljs-comment">#</span>
  1671. <span class="hljs-comment"># Usage: .py</span>
  1672. <span class="hljs-comment">#</span>
  1673. <span class="hljs-keyword">from</span> collections <span class="hljs-keyword">import</span> namedtuple
  1674. <span class="hljs-keyword">from</span> enum <span class="hljs-keyword">import</span> Enum
  1675. <span class="hljs-keyword">import</span> re
  1676. <span class="hljs-keyword">import</span> sys
  1677. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span><span class="hljs-params">()</span>:</span>
  1678. <span class="hljs-keyword">pass</span>
  1679. <span class="hljs-comment">###</span>
  1680. <span class="hljs-comment">## UTIL</span>
  1681. <span class="hljs-comment">#</span>
  1682. <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">read_file</span><span class="hljs-params">(filename)</span>:</span>
  1683. <span class="hljs-keyword">with</span> open(filename, encoding=<span class="hljs-string">'utf-8'</span>) <span class="hljs-keyword">as</span> file:
  1684. <span class="hljs-keyword">return</span> file.readlines()
  1685. <span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
  1686. main()
  1687. </code></pre>
  1688. <footer>
  1689. <aside>March 14, 2018</aside>
  1690. <a href="../" rel="author">Jure Šorn</a>
  1691. </footer>
  1692. <br>
  1693. <br>
  1694. <br>
  1695. </body>
  1696. </html>