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.

1720 lines
36 KiB

7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. <sup>[Download text file](https://raw.githubusercontent.com/gto76/python-cheatsheet/master/README.md)
  4. or [Fork me on GitHub](https://github.com/gto76/python-cheatsheet).
  5. </sup>
  6. ![Monty Python](web/image_888.jpeg)
  7. Main
  8. ----
  9. ```python
  10. if __name__ == '__main__':
  11. main()
  12. ```
  13. List
  14. ----
  15. ```python
  16. <list> = <list>[from_inclusive : to_exclusive : step_size]
  17. <list>.append(<el>)
  18. <list>.extend(<collection>)
  19. <list> += [<el>]
  20. <list> += <collection>
  21. ```
  22. ```python
  23. <list>.sort()
  24. <list>.reverse()
  25. <list> = sorted(<collection>)
  26. <iter> = reversed(<list>)
  27. ```
  28. ```python
  29. sum_of_elements = sum(<collection>)
  30. elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
  31. sorted_by_second = sorted(<collection>, key=lambda el: el[1])
  32. sorted_by_both = sorted(<collection>, key=lambda el: (el[1], el[0]))
  33. flattened_list = list(itertools.chain.from_iterable(<list>))
  34. list_of_chars = list(<str>)
  35. product_of_elems = functools.reduce(lambda out, x: out * x, <collection>)
  36. no_duplicates = list(dict.fromkeys(<list>))
  37. ```
  38. ```python
  39. index = <list>.index(<el>) # Returns first index of item.
  40. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  41. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  42. <list>.remove(<el>) # Removes first occurrence of item.
  43. <list>.clear() # Removes all items.
  44. ```
  45. Dictionary
  46. ----------
  47. ```python
  48. <view> = <dict>.keys()
  49. <view> = <dict>.values()
  50. <view> = <dict>.items()
  51. ```
  52. ```python
  53. value = <dict>.get(key, default) # Returns default if key does not exist.
  54. value = <dict>.setdefault(key, default) # Same, but also adds default to dict.
  55. <dict> = collections.defaultdict(<type>) # Creates a dictionary with default value of type.
  56. <dict> = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
  57. ```
  58. ```python
  59. <dict>.update(<dict>) # Or: dict_a = {**dict_a, **dict_b}.
  60. <dict> = dict(<list>) # Initiates a dict from list of key-value pairs.
  61. <dict> = dict(zip(keys, values)) # Initiates a dict from two lists.
  62. <dict> = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys.
  63. ```
  64. ```python
  65. value = <dict>.pop(key) # Removes item from dictionary.
  66. {k: v for k, v in <dict>.items() if k in keys} # Filters dictionary by keys.
  67. ```
  68. ### Counter
  69. ```python
  70. >>> from collections import Counter
  71. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  72. >>> counter = Counter(colors)
  73. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  74. >>> counter.most_common()[0][0]
  75. 'blue'
  76. ```
  77. Set
  78. ---
  79. ```python
  80. <set> = set()
  81. <set>.add(<el>)
  82. <set>.update(<collection>)
  83. <set> |= {<el>}
  84. <set> |= <set>
  85. ```
  86. ```python
  87. <set> = <set>.union(<coll.>) # Or: <set> | <set>
  88. <set> = <set>.intersection(<coll.>) # Or: <set> & <set>
  89. <set> = <set>.difference(<coll.>) # Or: <set> - <set>
  90. <set> = <set>.symmetric_difference(<coll.>) # Or: <set> ^ <set>
  91. <bool> = <set>.issubset(<coll.>) # Or: <set> <= <set>
  92. <bool> = <set>.issuperset(<coll.>) # Or: <set> >= <set>
  93. ```
  94. ### Frozenset
  95. #### Is hashable and can be used as a key in dictionary.
  96. ```python
  97. <frozenset> = frozenset(<collection>)
  98. ```
  99. Range
  100. -----
  101. ```python
  102. range(to_exclusive)
  103. range(from_inclusive, to_exclusive)
  104. range(from_inclusive, to_exclusive, step_size)
  105. range(from_inclusive, to_exclusive, -step_size)
  106. ```
  107. ```python
  108. from_inclusive = <range>.start
  109. to_exclusive = <range>.stop
  110. ```
  111. Enumerate
  112. ---------
  113. ```python
  114. for i, el in enumerate(<collection> [, i_start]):
  115. ...
  116. ```
  117. Named Tuple
  118. -----------
  119. ```python
  120. >>> Point = collections.namedtuple('Point', 'x y')
  121. >>> p = Point(1, y=2)
  122. Point(x=1, y=2)
  123. >>> p[0]
  124. 1
  125. >>> p.x
  126. 1
  127. >>> getattr(p, 'y')
  128. 2
  129. >>> p._fields # Or: Point._fields
  130. ('x', 'y')
  131. ```
  132. Iterator
  133. --------
  134. ```python
  135. <iter> = iter(<collection>)
  136. <iter> = iter(<function>, to_exclusive)
  137. ```
  138. #### Skips first element:
  139. ```python
  140. next(<iter>)
  141. for element in <iter>:
  142. ...
  143. ```
  144. #### Reads input until it reaches an empty line:
  145. ```python
  146. for line in iter(input, ''):
  147. ...
  148. ```
  149. #### Same, but prints a message every time:
  150. ```python
  151. from functools import partial
  152. for line in iter(partial(input, 'Please enter value: '), ''):
  153. ...
  154. ```
  155. Generator
  156. ---------
  157. **Convenient way to implement the iterator protocol.**
  158. ```python
  159. def step(start, step_size):
  160. while True:
  161. yield start
  162. start += step_size
  163. ```
  164. ```python
  165. >>> stepper = step(10, 2)
  166. >>> next(stepper), next(stepper), next(stepper)
  167. (10, 12, 14)
  168. ```
  169. Type
  170. ----
  171. ```python
  172. <type> = type(<el>) # <class 'int'> / <class 'str'> / ...
  173. ```
  174. ```python
  175. from numbers import Number, Integral, Real, Rational, Complex
  176. <bool> = isinstance(<el>, Number)
  177. ```
  178. ```python
  179. <bool> = callable(<el>)
  180. ```
  181. String
  182. ------
  183. ```python
  184. <str> = <str>.strip() # Strips all whitespace characters.
  185. <str> = <str>.strip('<chars>') # Strips all passed characters.
  186. ```
  187. ```python
  188. <list> = <str>.split() # Splits on any whitespace character.
  189. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
  190. <str> = <str>.join(<list>) # Joins elements using string as separator.
  191. ```
  192. ```python
  193. <str> = <str>.replace(old_str, new_str)
  194. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  195. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  196. <int> = <str>.index(<sub_str>) # Returns first index of a substring.
  197. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  198. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  199. ```
  200. ### Char
  201. ```python
  202. <str> = chr(<int>) # Converts int to unicode char.
  203. <int> = ord(<str>) # Converts unicode char to int.
  204. ```
  205. ```python
  206. >>> ord('0'), ord('9')
  207. (48, 57)
  208. >>> ord('A'), ord('Z')
  209. (65, 90)
  210. >>> ord('a'), ord('z')
  211. (97, 122)
  212. ```
  213. Regex
  214. -----
  215. ```python
  216. import re
  217. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  218. <list> = re.findall(<regex>, text) # Returns all occurrences.
  219. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  220. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  221. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  222. <Matches> = re.finditer(<regex>, text) # Searches for all occurrences of pattern.
  223. ```
  224. * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.**
  225. * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.**
  226. * **Use `r'\1'` or `'\\\\1'` for backreference.**
  227. * **Use `'?'` to make operators non-greedy.**
  228. ### Match Object
  229. ```python
  230. <str> = <Match>.group() # Whole match.
  231. <str> = <Match>.group(1) # Part in first bracket.
  232. <int> = <Match>.start() # Start index of a match.
  233. <int> = <Match>.end() # Exclusive end index of a match.
  234. ```
  235. ### Special Sequences
  236. **Use capital letter for negation.**
  237. ```python
  238. '\d' == '[0-9]' # Digit
  239. '\s' == '[ \t\n\r\f\v]' # Whitespace
  240. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  241. ```
  242. Print
  243. -----
  244. **Use `'file=sys.stderr'` for errors.**
  245. ```python
  246. print(<el_1> [, <el_2>, end='', sep='', file=<file>])
  247. ```
  248. ```python
  249. >>> from pprint import pprint
  250. >>> pprint(locals())
  251. {'__doc__': None,
  252. '__name__': '__main__',
  253. '__package__': None, ...}
  254. ```
  255. Format
  256. ------
  257. ```python
  258. <str> = f'{<el_1>}, {<el_2>}'
  259. <str> = '{}, {}'.format(<el_1>, <el_2>)
  260. ```
  261. ```python
  262. >>> Person = namedtuple('Person', 'name height')
  263. >>> person = Person('Jean-Luc', 187)
  264. >>> f'{person.height:10}'
  265. ' 187'
  266. >>> '{p.height:10}'.format(p=person)
  267. ' 187'
  268. ```
  269. ### General Options
  270. ```python
  271. {<el>:<10} # '<el> '
  272. {<el>:>10} # ' <el>'
  273. {<el>:^10} # ' <el> '
  274. {<el>:->10} # '------<el>'
  275. {<el>:>0} # '<el>'
  276. ```
  277. ### String Options
  278. **`'!r'` calls object's repr() method, instead of format(), to get a string.**
  279. ```python
  280. {'abcde'!r:<10} # "'abcde' "
  281. ```
  282. ```python
  283. {'abcde':.3} # 'abc'
  284. {'abcde':10.3} # 'abc '
  285. ```
  286. ### Number Options
  287. ```python
  288. {1.23456:.3f} # '1.235'
  289. {1.23456:10.3f} # ' 1.235'
  290. ```
  291. ```python
  292. { 123456:10,} # ' 123,456'
  293. { 123456:10_} # ' 123_456'
  294. { 123456:+10} # ' +123456'
  295. {-123456:=10} # '- 123456'
  296. { 123456: } # ' 123456'
  297. {-123456: } # '-123456'
  298. ```
  299. ```python
  300. {65:c} # 'A'
  301. {3:08b} # '00000011' -> Binary with leading zeros.
  302. {3:0<8b} # '11000000' -> Binary with trailing zeros.
  303. ```
  304. #### Float presentation types:
  305. * `'f'` - Fixed point: `.<precision>f`
  306. * `'%'` - Percent: `.<precision>%`
  307. * `'e'` - Exponent
  308. #### Integer presentation types:
  309. * `'c'` - Character
  310. * `'b'` - Binary
  311. * `'x'` - Hex
  312. * `'X'` - HEX
  313. Numbers
  314. -------
  315. ### Basic Functions
  316. ```python
  317. <num> = pow(<num>, <num>) # Or: <num> ** <num>
  318. <real> = abs(<num>)
  319. <real> = round(<real> [, ndigits])
  320. ```
  321. ### Constants
  322. ```python
  323. from math import e, pi
  324. ```
  325. ### Trigonometry
  326. ```python
  327. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  328. ```
  329. ### Logarithm
  330. ```python
  331. from math import log, log10, log2
  332. <float> = log(<real> [, base]) # Base e, if not specified.
  333. ```
  334. ### Infinity, nan
  335. ```python
  336. from math import inf, nan, isinf, isnan
  337. ```
  338. #### Or:
  339. ```python
  340. float('inf'), float('nan')
  341. ```
  342. ### Random
  343. ```python
  344. from random import random, randint, choice, shuffle
  345. <float> = random()
  346. <int> = randint(from_inclusive, to_inclusive)
  347. <el> = choice(<list>)
  348. shuffle(<list>)
  349. ```
  350. Datetime
  351. --------
  352. ```python
  353. from datetime import datetime, strptime
  354. now = datetime.now()
  355. now.month # 3
  356. now.strftime('%Y%m%d') # '20180315'
  357. now.strftime('%Y%m%d%H%M%S') # '20180315002834'
  358. <datetime> = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
  359. ```
  360. Arguments
  361. ---------
  362. **`'*'` is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.**
  363. ```python
  364. args = (1, 2)
  365. kwargs = {'x': 3, 'y': 4, 'z': 5}
  366. func(*args, **kwargs)
  367. ```
  368. #### Is the same as:
  369. ```python
  370. func(1, 2, x=3, y=4, z=5)
  371. ```
  372. #### Splat operator can also be used in function declarations:
  373. ```python
  374. def add(*a):
  375. return sum(a)
  376. ```
  377. ```python
  378. >>> add(1, 2, 3)
  379. 6
  380. ```
  381. #### And in few other places:
  382. ```python
  383. >>> a = (1, 2, 3)
  384. >>> [*a]
  385. [1, 2, 3]
  386. ```
  387. ```python
  388. >>> head, *body, tail = [1, 2, 3, 4]
  389. >>> body
  390. [2, 3]
  391. ```
  392. Inline
  393. ------
  394. ### Lambda
  395. ```python
  396. lambda: <return_value>
  397. lambda <argument_1>, <argument_2>: <return_value>
  398. ```
  399. ### Comprehension
  400. ```python
  401. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  402. <set> = {i for i in range(10) if i > 5} # {6, 7, 8, 9}
  403. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  404. <iter> = (i+5 for i in range(10)) # (5, 6, ..., 14)
  405. ```
  406. ```python
  407. out = [i+j for i in range(10) for j in range(10)]
  408. ```
  409. #### Is the same as:
  410. ```python
  411. out = []
  412. for i in range(10):
  413. for j in range(10):
  414. out.append(i+j)
  415. ```
  416. ### Map, Filter, Reduce
  417. ```python
  418. from functools import reduce
  419. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  420. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9)
  421. <int> = reduce(lambda out, x: out + x, range(10)) # 45
  422. ```
  423. ### Any, All
  424. ```python
  425. <bool> = any(<collection>) # False if empty.
  426. <bool> = all(el[1] for el in <collection>) # True if empty.
  427. ```
  428. ### If - Else
  429. ```python
  430. <expression_if_true> if <condition> else <expression_if_false>
  431. ```
  432. ```python
  433. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  434. ['zero', 1, 'zero', 3]
  435. ```
  436. ### Namedtuple, Enum, Class
  437. ```python
  438. from collections import namedtuple
  439. Point = namedtuple('Point', 'x y')
  440. point = Point(0, 0)
  441. ```
  442. ```python
  443. from enum import Enum
  444. Direction = Enum('Direction', 'n e s w')
  445. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  446. ```
  447. ```python
  448. # Warning: Objects will share the objects that are initialized in the dictionary!
  449. Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
  450. creature = Creature()
  451. ```
  452. Closure
  453. -------
  454. ```python
  455. def get_multiplier(a):
  456. def out(b):
  457. return a * b
  458. return out
  459. ```
  460. ```python
  461. >>> multiply_by_3 = get_multiplier(3)
  462. >>> multiply_by_3(10)
  463. 30
  464. ```
  465. #### Or:
  466. ```python
  467. from functools import partial
  468. <function> = partial(<function>, <argument_1> [, <argument_2>, ...])
  469. ```
  470. ```python
  471. >>> multiply_by_3 = partial(operator.mul, 3)
  472. >>> multiply_by_3(10)
  473. 30
  474. ```
  475. Decorator
  476. ---------
  477. ```python
  478. @closure_name
  479. def function_that_gets_passed_to_closure():
  480. ...
  481. ```
  482. #### Debugger example:
  483. ```python
  484. from functools import wraps
  485. def debug(func):
  486. @wraps(func) # Needed for metadata copying (func name, ...).
  487. def out(*args, **kwargs):
  488. print(func.__name__)
  489. return func(*args, **kwargs)
  490. return out
  491. @debug
  492. def add(x, y):
  493. return x + y
  494. ```
  495. Class
  496. -----
  497. ```python
  498. class <name>:
  499. def __init__(self, a):
  500. self.a = a
  501. def __repr__(self):
  502. class_name = type(self).__name__
  503. return f'{class_name}({self.a!r})'
  504. def __str__(self):
  505. return str(self.a)
  506. @classmethod
  507. def get_class_name(cls):
  508. return cls.__name__
  509. ```
  510. ### Constructor Overloading
  511. ```python
  512. class <name>:
  513. def __init__(self, a=None):
  514. self.a = a
  515. ```
  516. ### Inheritance
  517. ```python
  518. class Person:
  519. def __init__(self, name, age):
  520. self.name = name
  521. self.age = age
  522. class Employee(Person):
  523. def __init__(self, name, age, staff_num):
  524. super().__init__(name, age)
  525. self.staff_num = staff_num
  526. ```
  527. ### Comparable
  528. **If eq() method is not overriden, it returns `id(self) == id(other)`, which is the same as `self is other`, meaning all objects compare not equal by default.**
  529. ```python
  530. class MyComparable:
  531. def __init__(self, a):
  532. self.a = a
  533. def __eq__(self, other):
  534. if isinstance(other, type(self)):
  535. return self.a == other.a
  536. return False
  537. ```
  538. ### Hashable
  539. **Hashable object needs both hash() and eq() methods and it's hash value should not change. Objects that compare equal must have the same hash value, meaning default hash() that returns `id(self)` will not do. That is why Python automatically makes classes unhashable if you only implement eq().**
  540. ```python
  541. class MyHashable:
  542. def __init__(self, a):
  543. self.__a = a
  544. @property
  545. def a(self):
  546. return self.__a
  547. def __eq__(self, other):
  548. if isinstance(other, type(self)):
  549. return self.a == other.a
  550. return False
  551. def __hash__(self):
  552. return hash(self.a)
  553. ```
  554. ### Sequence
  555. ```python
  556. class MySequence:
  557. def __init__(self, a):
  558. self.a = a
  559. def __len__(self):
  560. return len(self.a)
  561. def __getitem__(self, i):
  562. return self.a[i]
  563. def __iter__(self):
  564. for el in self.a:
  565. yield el
  566. ```
  567. ### Copy
  568. ```python
  569. from copy import copy, deepcopy
  570. <object> = copy(<object>)
  571. <object> = deepcopy(<object>)
  572. ```
  573. Enum
  574. ----
  575. ```python
  576. from enum import Enum, auto
  577. class <enum_name>(Enum):
  578. <member_name_1> = <value_1>
  579. <member_name_2> = <value_2_a>, <value_2_b>
  580. <member_name_3> = auto() # Can be used for automatic indexing.
  581. @classmethod
  582. def get_member_names(cls):
  583. return [a.name for a in cls.__members__.values()]
  584. ```
  585. ```python
  586. <member> = <enum>.<member_name>
  587. <member> = <enum>['<member_name>']
  588. <member> = <enum>(<value>)
  589. name = <member>.name
  590. value = <member>.value
  591. ```
  592. ```python
  593. list_of_members = list(<enum>)
  594. member_names = [a.name for a in <enum>]
  595. member_values = [a.value for a in <enum>]
  596. random_member = random.choice(list(<enum>))
  597. ```
  598. ### Inline
  599. ```python
  600. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  601. Cutlery = Enum('Cutlery', 'knife fork spoon')
  602. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  603. ```
  604. #### Functions can not be values, so they must be wrapped:
  605. ```python
  606. from functools import partial
  607. LogicOp = Enum('LogicOp', {'and': partial(lambda l, r: l and r),
  608. 'or' : partial(lambda l, r: l or r)})
  609. ```
  610. System
  611. ------
  612. ### Arguments
  613. ```python
  614. import sys
  615. script_name = sys.argv[0]
  616. arguments = sys.argv[1:]
  617. ```
  618. ### Read File
  619. ```python
  620. def read_file(filename):
  621. with open(filename, encoding='utf-8') as file:
  622. return file.readlines()
  623. ```
  624. ### Write to File
  625. ```python
  626. def write_to_file(filename, text):
  627. with open(filename, 'w', encoding='utf-8') as file:
  628. file.write(text)
  629. ```
  630. ### Path
  631. ```python
  632. from os import path, listdir
  633. <bool> = path.exists(<path>)
  634. <bool> = path.isfile(<path>)
  635. <bool> = path.isdir(<path>)
  636. <list> = listdir(<path>)
  637. ```
  638. ```python
  639. >>> from glob import glob
  640. >>> glob('../*.gif')
  641. ['1.gif', 'card.gif']
  642. ```
  643. ### Execute Command
  644. ```python
  645. import os
  646. <str> = os.popen(<command>).read()
  647. ```
  648. #### Or:
  649. ```python
  650. >>> import subprocess
  651. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  652. >>> a.stdout
  653. b'.\n..\nfile1.txt\nfile2.txt\n'
  654. >>> a.returncode
  655. 0
  656. ```
  657. ### Input
  658. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  659. ```python
  660. filename = input('Enter a file name: ')
  661. ```
  662. #### Prints lines until EOF:
  663. ```python
  664. while True:
  665. try:
  666. print(input())
  667. except EOFError:
  668. break
  669. ```
  670. ### Recursion Limit
  671. ```python
  672. >>> import sys
  673. >>> sys.getrecursionlimit()
  674. 1000
  675. >>> sys.setrecursionlimit(5000)
  676. ```
  677. JSON
  678. ----
  679. ```python
  680. import json
  681. ```
  682. ### Serialization
  683. ```python
  684. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  685. <dict> = json.loads(<str>)
  686. ```
  687. #### To preserve order:
  688. ```python
  689. from collections import OrderedDict
  690. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  691. ```
  692. ### Read File
  693. ```python
  694. def read_json_file(filename):
  695. with open(filename, encoding='utf-8') as file:
  696. return json.load(file)
  697. ```
  698. ### Write to File
  699. ```python
  700. def write_to_json_file(filename, an_object):
  701. with open(filename, 'w', encoding='utf-8') as file:
  702. json.dump(an_object, file, ensure_ascii=False, indent=2)
  703. ```
  704. SQLite
  705. ------
  706. ```python
  707. import sqlite3
  708. db = sqlite3.connect(<filename>)
  709. ...
  710. db.close()
  711. ```
  712. ### Read
  713. ```python
  714. cursor = db.execute(<query>)
  715. if cursor:
  716. <tuple> = cursor.fetchone() # First row.
  717. <list> = cursor.fetchall() # Remaining rows.
  718. ```
  719. ### Write
  720. ```python
  721. db.execute(<query>)
  722. db.commit()
  723. ```
  724. Pickle
  725. ------
  726. ```python
  727. >>> import pickle
  728. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  729. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  730. >>> pickle.load(open('data.p', 'rb'))
  731. {'lion': 'yellow', 'kitty': 'red'}
  732. ```
  733. Exceptions
  734. ----------
  735. ```python
  736. while True:
  737. try:
  738. x = int(input('Please enter a number: '))
  739. except ValueError:
  740. print('Oops! That was no valid number. Try again...')
  741. else:
  742. print('Thank you.')
  743. break
  744. ```
  745. #### Raising exception:
  746. ```python
  747. raise ValueError('A very specific message!')
  748. ```
  749. ### Finally
  750. ```python
  751. >>> try:
  752. ... raise KeyboardInterrupt
  753. ... finally:
  754. ... print('Goodbye, world!')
  755. Goodbye, world!
  756. Traceback (most recent call last):
  757. File "<stdin>", line 2, in <module>
  758. KeyboardInterrupt
  759. ```
  760. Bytes
  761. -----
  762. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  763. ```python
  764. <bytes> = b'<str>'
  765. <int> = <bytes>[<index>]
  766. <bytes> = <bytes>[<slice>]
  767. <bytes> = b''.join(<coll_of_bytes>)
  768. ```
  769. ### Encode
  770. ```python
  771. <bytes> = <str>.encode(encoding='utf-8')
  772. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  773. <bytes> = bytes.fromhex(<hex>)
  774. ```
  775. ### Decode
  776. ```python
  777. <str> = <bytes>.decode('utf-8')
  778. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  779. <hex> = <bytes>.hex()
  780. ```
  781. ### Read Bytes from File
  782. ```python
  783. def read_bytes(filename):
  784. with open(filename, 'rb') as file:
  785. return file.read()
  786. ```
  787. ### Write Bytes to File
  788. ```python
  789. def write_bytes(filename, bytes_obj):
  790. with open(filename, 'wb') as file:
  791. file.write(bytes_obj)
  792. ```
  793. Struct
  794. ------
  795. **This module performs conversions between Python values and C struct represented as Python bytes object. Machine’s native type sizes and byte order are used by default.**
  796. ```python
  797. from struct import pack, unpack, calcsize
  798. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  799. <tuple> = unpack('<format>', <bytes>)
  800. ```
  801. ### Example
  802. ```python
  803. >>> pack('>hhl', 1, 2, 3)
  804. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  805. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  806. (1, 2, 3)
  807. >>> calcsize('>hhl')
  808. 8
  809. ```
  810. ### Format
  811. #### For standard sizes start format string with:
  812. * `'='` - native byte order
  813. * `'<'` - little-endian
  814. * `'>'` - big-endian
  815. #### Use capital leter for unsigned type. Standard size in brackets:
  816. * `'x'` - pad byte
  817. * `'c'` - char (1)
  818. * `'h'` - short (2)
  819. * `'i'` - int (4)
  820. * `'l'` - long (4)
  821. * `'q'` - long long (8)
  822. * `'f'` - float (4)
  823. * `'d'` - double (8)
  824. Array
  825. -----
  826. **List that can only hold elements of predefined type. Available types are listed above.**
  827. ```python
  828. from array import array
  829. <array> = array(<typecode> [, <collection>])
  830. ```
  831. Deque
  832. -----
  833. **Short for “double-ended queue” and pronounced “deck”. They are thread-safe lists with efficient appends and pops from either side.**
  834. ```python
  835. from collections import deque
  836. <deque> = deque(<collection>, maxlen=None)
  837. ```
  838. ```python
  839. <deque>.appendleft(<el>)
  840. <deque>.extendleft(<collection>) # Collection gets reversed.
  841. <el> = <deque>.popleft()
  842. <deque>.rotate(n=1) # Rotates elements to the right.
  843. ```
  844. Threading
  845. ---------
  846. ```python
  847. from threading import Thread, RLock
  848. ```
  849. ### Thread
  850. ```python
  851. thread = Thread(target=<function>, args=(<first_arg>, ))
  852. thread.start()
  853. ...
  854. thread.join()
  855. ```
  856. ### Lock
  857. ```python
  858. lock = RLock()
  859. lock.acquire()
  860. ...
  861. lock.release()
  862. ```
  863. Hashlib
  864. -------
  865. ```python
  866. >>> import hashlib
  867. >>> hashlib.md5(<str>.encode()).hexdigest()
  868. '33d0eba106da4d3ebca17fcd3f4c3d77'
  869. ```
  870. Itertools
  871. ---------
  872. **Every function returns an iterator and can accept any collection and/or iterator. If you want to print the iterator, you need to pass it to the list() function!**
  873. ```python
  874. from itertools import *
  875. ```
  876. ### Combinatoric iterators
  877. ```python
  878. >>> combinations('abc', 2)
  879. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  880. >>> combinations_with_replacement('abc', 2)
  881. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  882. ('b', 'b'), ('b', 'c'),
  883. ('c', 'c')]
  884. >>> permutations('abc', 2)
  885. [('a', 'b'), ('a', 'c'),
  886. ('b', 'a'), ('b', 'c'),
  887. ('c', 'a'), ('c', 'b')]
  888. >>> product('ab', [1, 2])
  889. [('a', 1), ('a', 2),
  890. ('b', 1), ('b', 2)]
  891. >>> product([0, 1], repeat=3)
  892. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  893. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  894. ```
  895. ### Infinite iterators
  896. ```python
  897. >>> i = count(5, 2)
  898. >>> next(i), next(i), next(i)
  899. (5, 7, 9)
  900. >>> a = cycle('abc')
  901. >>> [next(a) for _ in range(10)]
  902. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  903. >>> repeat(10, 3)
  904. [10, 10, 10]
  905. ```
  906. ### Iterators
  907. ```python
  908. >>> chain([1, 2], range(3, 5))
  909. [1, 2, 3, 4]
  910. >>> compress('abc', [True, 0, 1])
  911. ['a', 'c']
  912. >>> # islice(<collection>, from_inclusive, to_exclusive)
  913. >>> islice([1, 2, 3], 1, None)
  914. [2, 3]
  915. >>> people = [{'id': 1, 'name': 'Bob'},
  916. {'id': 2, 'name': 'Bob'},
  917. {'id': 3, 'name': 'Peter'}]
  918. >>> groups = groupby(people, key=lambda a: a['name'])
  919. >>> {name: list(group) for name, group in groups}
  920. {'Bob': [{'id': 1, 'name': 'Bob'},
  921. {'id': 2, 'name': 'Bob'}],
  922. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  923. ```
  924. Introspection and Metaprograming
  925. --------------------------------
  926. **Inspecting code at runtime and code that generates code. You can:**
  927. * **Look at the attributes**
  928. * **Set new attributes**
  929. * **Create functions dynamically**
  930. * **Traverse the parent classes**
  931. * **Change values in the class**
  932. ### Variables
  933. ```python
  934. <list> = dir() # Names of in-scope variables.
  935. <dict> = locals() # Dict of local variables. Also vars().
  936. <dict> = globals() # Dict of global variables.
  937. ```
  938. ### Attributes
  939. ```python
  940. >>> class Z:
  941. ... def __init__(self):
  942. ... self.a = 'abcde'
  943. ... self.b = 12345
  944. >>> z = Z()
  945. ```
  946. ```python
  947. >>> vars(z)
  948. {'a': 'abcde', 'b': 12345}
  949. >>> getattr(z, 'a')
  950. 'abcde'
  951. >>> hasattr(z, 'c')
  952. False
  953. >>> setattr(z, 'c', 10)
  954. ```
  955. ### Parameters
  956. ```python
  957. from inspect import signature
  958. sig = signature(<function>)
  959. no_of_params = len(sig.parameters)
  960. param_names = list(sig.parameters.keys())
  961. ```
  962. ### Type
  963. **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).**
  964. ```python
  965. type(<class_name>, <parents_tuple>, <attributes_dict>)
  966. ```
  967. ```python
  968. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  969. >>> z = Z()
  970. ```
  971. ### Meta Class
  972. **Class that creates class.**
  973. ```python
  974. def my_meta_class(name, parents, attrs):
  975. attrs['a'] = 'abcde'
  976. return type(name, parents, attrs)
  977. ```
  978. #### Or:
  979. ```python
  980. class MyMetaClass(type):
  981. def __new__(klass, name, parents, attrs):
  982. attrs['a'] = 'abcde'
  983. return type.__new__(klass, name, parents, attrs)
  984. ```
  985. ### Metaclass Attribute
  986. **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.**
  987. ```python
  988. class MyClass(metaclass=MyMetaClass):
  989. def __init__(self):
  990. self.b = 12345
  991. ```
  992. Operator
  993. --------
  994. ```python
  995. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  996. eq, ne, lt, le, gt, ge, \
  997. not_, and_, or_, \
  998. itemgetter
  999. ```
  1000. ```python
  1001. import operator as op
  1002. product_of_elems = functools.reduce(op.mul, <list>)
  1003. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  1004. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  1005. LogicOp = enum.Enum('LogicOp', {'and': op.and_, 'or' : op.or_})
  1006. ```
  1007. Eval
  1008. ----
  1009. ### Basic
  1010. ```python
  1011. >>> from ast import literal_eval
  1012. >>> literal_eval('1 + 2')
  1013. 3
  1014. >>> literal_eval('[1, 2, 3]')
  1015. [1, 2, 3]
  1016. >>> ast.literal_eval('abs(1)')
  1017. ValueError: malformed node or string
  1018. ```
  1019. ### Using Abstract Syntax Trees
  1020. ```python
  1021. import ast
  1022. from ast import Num, BinOp, UnaryOp
  1023. import operator as op
  1024. legal_operators = {ast.Add: op.add,
  1025. ast.Sub: op.sub,
  1026. ast.Mult: op.mul,
  1027. ast.Div: op.truediv,
  1028. ast.Pow: op.pow,
  1029. ast.BitXor: op.xor,
  1030. ast.USub: op.neg}
  1031. def evaluate(expression):
  1032. root = ast.parse(expression, mode='eval')
  1033. return eval_node(root.body)
  1034. def eval_node(node):
  1035. node_type = type(node)
  1036. if node_type == Num:
  1037. return node.n
  1038. if node_type not in [BinOp, UnaryOp]:
  1039. raise TypeError(node)
  1040. operator_type = type(node.op)
  1041. if operator_type not in legal_operators:
  1042. raise TypeError(f'Illegal operator {node.op}')
  1043. operator = legal_operators[operator_type]
  1044. if node_type == BinOp:
  1045. left, right = eval_node(node.left), eval_node(node.right)
  1046. return operator(left, right)
  1047. elif node_type == UnaryOp:
  1048. operand = eval_node(node.operand)
  1049. return operator(operand)
  1050. ```
  1051. ```python
  1052. >>> evaluate('2 ^ 6')
  1053. 4
  1054. >>> evaluate('2 ** 6')
  1055. 64
  1056. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  1057. -5.0
  1058. ```
  1059. Coroutine
  1060. ---------
  1061. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  1062. * **Coroutines provide more powerful data routing possibilities than iterators.**
  1063. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1064. ### Helper Decorator
  1065. * **All coroutines must be "primed" by first calling next().**
  1066. * **Remembering to call next() is easy to forget.**
  1067. * **Solved by wrapping coroutines with a decorator:**
  1068. ```python
  1069. def coroutine(func):
  1070. def out(*args, **kwargs):
  1071. cr = func(*args, **kwargs)
  1072. next(cr)
  1073. return cr
  1074. return out
  1075. ```
  1076. ### Pipeline Example
  1077. ```python
  1078. def reader(target):
  1079. for i in range(10):
  1080. target.send(i)
  1081. target.close()
  1082. @coroutine
  1083. def adder(target):
  1084. while True:
  1085. item = (yield)
  1086. target.send(item + 100)
  1087. @coroutine
  1088. def printer():
  1089. while True:
  1090. item = (yield)
  1091. print(item)
  1092. reader(adder(printer())) # 100, 101, ..., 109
  1093. ```
  1094. <br><br>
  1095. Libraries
  1096. =========
  1097. Argparse
  1098. --------
  1099. ```python
  1100. import argparse
  1101. parser = argparse.ArgumentParser(description='calculate X to the power of Y')
  1102. group = parser.add_mutually_exclusive_group()
  1103. group.add_argument('-v', '--verbose', action='store_true')
  1104. group.add_argument('-q', '--quiet', action='store_true')
  1105. parser.add_argument('x', type=int, help='the base')
  1106. parser.add_argument('y', type=int, help='the exponent')
  1107. args = parser.parse_args()
  1108. answer = args.x ** args.y
  1109. if args.quiet:
  1110. print(answer)
  1111. elif args.verbose:
  1112. print(f'{args.x} to the power {args.y} equals {answer}')
  1113. else:
  1114. print(f'{args.x}^{args.y} == {answer}')
  1115. ```
  1116. ### Usage
  1117. ```text
  1118. $ python3 prog.py --help
  1119. usage: test2.py [-h] [-v | -q] x y
  1120. calculate X to the power of Y
  1121. positional arguments:
  1122. x the base
  1123. y the exponent
  1124. optional arguments:
  1125. -h, --help show this help message and exit
  1126. -v, --verbose
  1127. -q, --quiet
  1128. ```
  1129. Plot
  1130. ----
  1131. ```python
  1132. # $ pip3 install matplotlib
  1133. from matplotlib import pyplot
  1134. pyplot.plot(<data_1> [, <data_2>, ...])
  1135. pyplot.savefig(<filename>, transparent=True)
  1136. pyplot.show()
  1137. ```
  1138. Progress Bar
  1139. ------------
  1140. ```python
  1141. # $ pip3 install tqdm
  1142. from tqdm import tqdm
  1143. from time import sleep
  1144. for i in tqdm([1, 2, 3]):
  1145. sleep(0.2)
  1146. for i in tqdm(range(100)):
  1147. sleep(0.02)
  1148. ```
  1149. Table
  1150. -----
  1151. #### Prints CSV file as ASCII table:
  1152. ```python
  1153. # $ pip3 install tabulate
  1154. from csv import reader
  1155. from tabulate import tabulate
  1156. with open(<filename>, encoding='utf-8', newline='') as csv_file:
  1157. reader = reader(csv_file, delimiter=';')
  1158. headers = [a.title() for a in next(reader)]
  1159. print(tabulate(reader, headers))
  1160. ```
  1161. Curses
  1162. ------
  1163. ```python
  1164. # $ pip3 install curses
  1165. from curses import wrapper
  1166. def main():
  1167. wrapper(draw)
  1168. def draw(screen):
  1169. screen.clear()
  1170. screen.addstr(0, 0, 'Press ESC to quit.')
  1171. while screen.getch() != 27:
  1172. pass
  1173. def get_border(screen):
  1174. from collections import namedtuple
  1175. P = namedtuple('P', 'x y')
  1176. height, width = screen.getmaxyx()
  1177. return P(width - 1, height - 1)
  1178. ```
  1179. Image
  1180. -----
  1181. #### Creates PNG image of greyscale gradient:
  1182. ```python
  1183. # $ pip3 install pillow
  1184. from PIL import Image
  1185. width, height = 100, 100
  1186. img = Image.new('L', (width, height), 'white')
  1187. img.putdata([255*a/(width*height) for a in range(width*height)])
  1188. img.save('out.png')
  1189. ```
  1190. ### Modes
  1191. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1192. * `'L'` - 8-bit pixels, greyscale.
  1193. * `'RGB'` - 3x8-bit pixels, true color.
  1194. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1195. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1196. Audio
  1197. -----
  1198. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1199. ```python
  1200. import wave, struct
  1201. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1202. wf = wave.open(<filename>, 'wb')
  1203. wf.setnchannels(1)
  1204. wf.setsampwidth(4)
  1205. wf.setframerate(44100)
  1206. wf.writeframes(b''.join(frames))
  1207. wf.close()
  1208. ```
  1209. Url
  1210. ---
  1211. ```python
  1212. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1213. ```
  1214. ### Encode
  1215. ```python
  1216. >>> quote("Can't be in URL!")
  1217. 'Can%27t%20be%20in%20URL%21'
  1218. >>> quote_plus("Can't be in URL!")
  1219. 'Can%27t+be+in+URL%21'
  1220. ```
  1221. ### Decode
  1222. ```python
  1223. >>> unquote('Can%27t+be+in+URL%21')
  1224. "Can't+be+in+URL!"
  1225. >>> unquote_plus('Can%27t+be+in+URL%21')
  1226. "Can't be in URL!"
  1227. ```
  1228. Scraping
  1229. --------
  1230. ```python
  1231. # $ pip3 install requests beautifulsoup4
  1232. >>> import requests
  1233. >>> from bs4 import BeautifulSoup
  1234. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1235. >>> page = requests.get(url)
  1236. >>> document = BeautifulSoup(page.text, 'html.parser')
  1237. >>> table = document.find('table', class_='infobox vevent')
  1238. >>> rows = table.find_all('tr')
  1239. >>> link = rows[11].find('a')['href']
  1240. 'https://www.python.org/'
  1241. >>> latest_v = rows[6].find('div').text.split()[0]
  1242. '3.7.2'
  1243. ```
  1244. Web
  1245. ---
  1246. ```python
  1247. # $ pip3 install bottle
  1248. import bottle
  1249. from urllib.parse import unquote
  1250. ```
  1251. ### Run
  1252. ```python
  1253. bottle.run(host='localhost', port=8080)
  1254. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1255. ```
  1256. ### Static Request
  1257. ```python
  1258. @route('/img/<image>')
  1259. def send_image(image):
  1260. return static_file(image, 'images/', mimetype='image/png')
  1261. ```
  1262. ### Dynamic Request
  1263. ```python
  1264. @route('/<sport>')
  1265. def send_page(sport):
  1266. sport = unquote(sport).lower()
  1267. page = read_file(sport)
  1268. return template(page)
  1269. ```
  1270. ### REST Request
  1271. ```python
  1272. @post('/odds/<sport>')
  1273. def odds_handler(sport):
  1274. team = bottle.request.forms.get('team')
  1275. team = unquote(team).lower()
  1276. db = sqlite3.connect(<db_path>)
  1277. home_odds, away_odds = get_odds(db, sport, team)
  1278. db.close()
  1279. response.headers['Content-Type'] = 'application/json'
  1280. response.headers['Cache-Control'] = 'no-cache'
  1281. return json.dumps([home_odds, away_odds])
  1282. ```
  1283. Profile
  1284. -------
  1285. ### Basic
  1286. ```python
  1287. from time import time
  1288. start_time = time() # Seconds since Epoch.
  1289. ...
  1290. duration = time() - start_time
  1291. ```
  1292. ### High Performance
  1293. ```python
  1294. from time import perf_counter as pc
  1295. start_time = pc() # Seconds since restart.
  1296. ...
  1297. duration = pc() - start_time
  1298. ```
  1299. ### Timing a Snippet
  1300. ```python
  1301. from timeit import timeit
  1302. timeit('"-".join(str(a) for a in range(100))',
  1303. number=10000, globals=globals(), setup='pass')
  1304. ```
  1305. ### Line Profiler
  1306. ```python
  1307. # $ pip3 install line_profiler
  1308. @profile
  1309. def main():
  1310. a = [*range(10000)]
  1311. b = {*range(10000)}
  1312. main()
  1313. ```
  1314. #### Usage:
  1315. ```text
  1316. $ kernprof -lv test.py
  1317. Line # Hits Time Per Hit % Time Line Contents
  1318. ==============================================================
  1319. 1 @profile
  1320. 2 def main():
  1321. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1322. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1323. ```
  1324. ### Call Graph
  1325. #### Generates a PNG image of call graph with highlighted bottlenecks:
  1326. ```python
  1327. # $ pip3 install pycallgraph
  1328. from pycallgraph import output, PyCallGraph
  1329. from datetime import datetime
  1330. graph = output.GraphvizOutput()
  1331. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1332. graph.output_file = f'profile-{time_str}.png'
  1333. with PyCallGraph(output=graph):
  1334. <code_to_be_profiled>
  1335. ```
  1336. NumPy
  1337. -----
  1338. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1339. ```python
  1340. # $ pip3 install numpy
  1341. import numpy as np
  1342. ```
  1343. ```python
  1344. <array> = np.array(<list>)
  1345. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1346. <array> = np.ones(<shape>)
  1347. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1348. ```
  1349. ```python
  1350. first_column = <array>[:, 0] # Or: <array>[..., 0]
  1351. value = <array>.min([axis])
  1352. index = <array>.argmin([axis])
  1353. ```
  1354. ```python
  1355. <array>.shape = <shape>
  1356. <view> = <array>.reshape(<shape>)
  1357. <view> = np.broadcast_to(<array>, <shape>)
  1358. <el_or_array> = <array>[filter_expression]
  1359. ```
  1360. ### Broadcasting
  1361. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions.**
  1362. ```python
  1363. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1364. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1365. ```
  1366. #### 1. If array shapes differ, left-pad the smaller shape with ones:
  1367. ```python
  1368. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1369. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1370. ```
  1371. #### 2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements:
  1372. ```python
  1373. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1374. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1375. ```
  1376. #### 3. If neither non-matching dimension has size 1, rise an error.
  1377. ### Example
  1378. #### For each point returns index of its nearest point (`[0.1, 0.6, 0.8] => [1, 2, 1]`):
  1379. ```python
  1380. >>> points = np.array([0.1, 0.6, 0.8])
  1381. [ 0.1, 0.6, 0.8]
  1382. >>> wrapped_points = points.reshape(3, 1)
  1383. [[ 0.1],
  1384. [ 0.6],
  1385. [ 0.8]]
  1386. >>> distances = wrapped_points - points
  1387. [[ 0. , -0.5, -0.7],
  1388. [ 0.5, 0. , -0.2],
  1389. [ 0.7, 0.2, 0. ]]
  1390. >>> distances = np.abs(distances)
  1391. [[ 0. , 0.5, 0.7],
  1392. [ 0.5, 0. , 0.2],
  1393. [ 0.7, 0.2, 0. ]]
  1394. >>> i = np.arange(3)
  1395. [0, 1, 2]
  1396. >>> distances[i, i] = np.inf
  1397. [[ inf, 0.5, 0.7],
  1398. [ 0.5, inf, 0.2],
  1399. [ 0.7, 0.2, inf]]
  1400. >>> distances.argmin(1)
  1401. [1, 2, 1]
  1402. ```
  1403. Basic Script Template
  1404. ---------------------
  1405. ```python
  1406. #!/usr/bin/env python3
  1407. #
  1408. # Usage: .py
  1409. #
  1410. from collections import namedtuple
  1411. from enum import Enum
  1412. import re
  1413. import sys
  1414. def main():
  1415. pass
  1416. ###
  1417. ## UTIL
  1418. #
  1419. def read_file(filename):
  1420. with open(filename, encoding='utf-8') as file:
  1421. return file.readlines()
  1422. if __name__ == '__main__':
  1423. main()
  1424. ```