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.

1859 lines
39 KiB

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