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.

1625 lines
34 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
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
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
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
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
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
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
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
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
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
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
7 years ago
6 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
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
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
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
  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(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" uses 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. from enum import Enum
  442. Direction = Enum('Direction', 'n e s w')
  443. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  444. # Warning: Objects will share the objects that are initialized in the dictionary!
  445. Creature = type('Creature', (), {'p': Point(0, 0), 'd': Direction.n})
  446. creature = Creature()
  447. ```
  448. Closure
  449. -------
  450. ```python
  451. def get_multiplier(a):
  452. def out(b):
  453. return a * b
  454. return out
  455. ```
  456. ```python
  457. >>> multiply_by_3 = get_multiplier(3)
  458. >>> multiply_by_3(10)
  459. 30
  460. ```
  461. #### Or:
  462. ```python
  463. from functools import partial
  464. <function> = partial(<function>, <argument_1> [, <argument_2>, ...])
  465. ```
  466. ```python
  467. >>> multiply_by_3 = partial(operator.mul, 3)
  468. >>> multiply_by_3(10)
  469. 30
  470. ```
  471. Decorator
  472. ---------
  473. ```python
  474. @closure_name
  475. def function_that_gets_passed_to_closure():
  476. ...
  477. ```
  478. #### Debugger example:
  479. ```python
  480. from functools import wraps
  481. def debug(func):
  482. @wraps(func) # Needed for metadata copying (func name, ...).
  483. def out(*args, **kwargs):
  484. print(func.__name__)
  485. return func(*args, **kwargs)
  486. return out
  487. @debug
  488. def add(x, y):
  489. return x + y
  490. ```
  491. Class
  492. -----
  493. ```python
  494. class <name>:
  495. def __init__(self, a):
  496. self.a = a
  497. def __repr__(self):
  498. class_name = type(self).__name__
  499. return f'{class_name}({self.a:!r})'
  500. def __str__(self):
  501. return str(self.a)
  502. @classmethod
  503. def get_class_name(cls):
  504. return cls.__name__
  505. ```
  506. ### Constructor Overloading
  507. ```python
  508. class <name>:
  509. def __init__(self, a=None):
  510. self.a = a
  511. ```
  512. ### Inheritance
  513. ```python
  514. class Person:
  515. def __init__(self, name, age):
  516. self.name = name
  517. self.age = age
  518. class Employee(Person):
  519. def __init__(self, name, age, staff_num):
  520. super().__init__(name, age)
  521. self.staff_num = staff_num
  522. ```
  523. ### Copy
  524. ```python
  525. from copy import copy, deepcopy
  526. <object> = copy(<object>)
  527. <object> = deepcopy(<object>)
  528. ```
  529. Enum
  530. ----
  531. ```python
  532. from enum import Enum, auto
  533. class <enum_name>(Enum):
  534. <member_name_1> = <value_1>
  535. <member_name_2> = <value_2_a>, <value_2_b>
  536. <member_name_3> = auto() # Can be used for automatic indexing.
  537. @classmethod
  538. def get_member_names(cls):
  539. return [a.name for a in cls.__members__.values()]
  540. ```
  541. ```python
  542. <member> = <enum>.<member_name>
  543. <member> = <enum>['<member_name>']
  544. <member> = <enum>(<value>)
  545. name = <member>.name
  546. value = <member>.value
  547. ```
  548. ```python
  549. list_of_members = list(<enum>)
  550. member_names = [a.name for a in <enum>]
  551. member_values = [a.value for a in <enum>]
  552. random_member = random.choice(list(<enum>))
  553. ```
  554. ### Inline
  555. ```python
  556. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  557. Cutlery = Enum('Cutlery', 'knife fork spoon')
  558. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  559. # Functions can not be values, so they must be enclosed in tuple:
  560. LogicOp = Enum('LogicOp', {'AND': (lambda l, r: l and r, ),
  561. 'OR' : (lambda l, r: l or r, )})
  562. # But 'list(<enum>)' will only work if there is another value in the tuple:
  563. LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r),
  564. 'OR' : (auto(), lambda l, r: l or r)})
  565. ```
  566. System
  567. ------
  568. ### Arguments
  569. ```python
  570. import sys
  571. script_name = sys.argv[0]
  572. arguments = sys.argv[1:]
  573. ```
  574. ### Read File
  575. ```python
  576. def read_file(filename):
  577. with open(filename, encoding='utf-8') as file:
  578. return file.readlines()
  579. ```
  580. ### Write to File
  581. ```python
  582. def write_to_file(filename, text):
  583. with open(filename, 'w', encoding='utf-8') as file:
  584. file.write(text)
  585. ```
  586. ### Path
  587. ```python
  588. from os import path, listdir
  589. <bool> = path.exists(<path>)
  590. <bool> = path.isfile(<path>)
  591. <bool> = path.isdir(<path>)
  592. <list> = listdir(<path>)
  593. ```
  594. ```python
  595. >>> from glob import glob
  596. >>> glob('../*.gif')
  597. ['1.gif', 'card.gif']
  598. ```
  599. ### Execute Command
  600. ```python
  601. import os
  602. <str> = os.popen(<command>).read()
  603. ```
  604. #### Or:
  605. ```python
  606. >>> import subprocess
  607. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  608. >>> a.stdout
  609. b'.\n..\nfile1.txt\nfile2.txt\n'
  610. >>> a.returncode
  611. 0
  612. ```
  613. ### Input
  614. **Reads a line from user input or pipe if present. The trailing newline gets stripped.**
  615. ```python
  616. filename = input('Enter a file name: ')
  617. ```
  618. #### Prints lines until EOF:
  619. ```python
  620. while True:
  621. try:
  622. print(input())
  623. except EOFError:
  624. break
  625. ```
  626. ### Recursion Limit
  627. ```python
  628. >>> import sys
  629. >>> sys.getrecursionlimit()
  630. 1000
  631. >>> sys.setrecursionlimit(5000)
  632. ```
  633. JSON
  634. ----
  635. ```python
  636. import json
  637. ```
  638. ### Serialization
  639. ```python
  640. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  641. <dict> = json.loads(<str>)
  642. ```
  643. #### To preserve order:
  644. ```python
  645. from collections import OrderedDict
  646. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  647. ```
  648. ### Read File
  649. ```python
  650. def read_json_file(filename):
  651. with open(filename, encoding='utf-8') as file:
  652. return json.load(file)
  653. ```
  654. ### Write to File
  655. ```python
  656. def write_to_json_file(filename, an_object):
  657. with open(filename, 'w', encoding='utf-8') as file:
  658. json.dump(an_object, file, ensure_ascii=False, indent=2)
  659. ```
  660. SQLite
  661. ------
  662. ```python
  663. import sqlite3
  664. db = sqlite3.connect(<filename>)
  665. ...
  666. db.close()
  667. ```
  668. ### Read
  669. ```python
  670. cursor = db.execute(<query>)
  671. if cursor:
  672. <tuple> = cursor.fetchone() # First row.
  673. <list> = cursor.fetchall() # Remaining rows.
  674. ```
  675. ### Write
  676. ```python
  677. db.execute(<query>)
  678. db.commit()
  679. ```
  680. Pickle
  681. ------
  682. ```python
  683. >>> import pickle
  684. >>> favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  685. >>> pickle.dump(favorite_color, open('data.p', 'wb'))
  686. >>> pickle.load(open('data.p', 'rb'))
  687. {'lion': 'yellow', 'kitty': 'red'}
  688. ```
  689. Exceptions
  690. ----------
  691. ```python
  692. while True:
  693. try:
  694. x = int(input('Please enter a number: '))
  695. except ValueError:
  696. print('Oops! That was no valid number. Try again...')
  697. else:
  698. print('Thank you.')
  699. break
  700. ```
  701. #### Raising exception:
  702. ```python
  703. raise ValueError('A very specific message!')
  704. ```
  705. ### Finally
  706. ```python
  707. >>> try:
  708. ... raise KeyboardInterrupt
  709. ... finally:
  710. ... print('Goodbye, world!')
  711. Goodbye, world!
  712. Traceback (most recent call last):
  713. File "<stdin>", line 2, in <module>
  714. KeyboardInterrupt
  715. ```
  716. Bytes
  717. -----
  718. **Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.**
  719. ```python
  720. <int> = <bytes>[<index>]
  721. <bytes> = <bytes>[<slice>]
  722. <bytes> = b''.join(<coll_of_bytes>)
  723. ```
  724. ### Encode
  725. ```python
  726. <bytes> = b'<str>'
  727. <bytes> = <str>.encode(encoding='utf-8')
  728. <bytes> = <int>.to_bytes(length, byteorder='big|little', signed=False)
  729. <bytes> = bytes.fromhex(<hex>)
  730. ```
  731. ### Decode
  732. ```python
  733. <str> = <bytes>.decode('utf-8')
  734. <int> = int.from_bytes(<bytes>, byteorder='big|little', signed=False)
  735. <hex> = <bytes>.hex()
  736. ```
  737. ### Read Bytes from File
  738. ```python
  739. def read_bytes(filename):
  740. with open(filename, 'rb') as file:
  741. return file.read()
  742. ```
  743. ### Write Bytes to File
  744. ```python
  745. def write_bytes(filename, bytes_obj):
  746. with open(filename, 'wb') as file:
  747. file.write(bytes_obj)
  748. ```
  749. Struct
  750. ------
  751. **This module performs conversions between Python values and C struct represented as Python bytes object. By default machine’s native sizes and byte order are used.**
  752. ```python
  753. from struct import pack, unpack, calcsize
  754. <bytes> = pack('<format>', <value_1> [, <value_2>, ...])
  755. <tuple> = unpack('<format>', <bytes>)
  756. ```
  757. ### Example
  758. ```python
  759. >>> pack('>hhl', 1, 2, 3)
  760. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  761. >>> unpack('>hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  762. (1, 2, 3)
  763. >>> calcsize('>hhl')
  764. 8
  765. ```
  766. ### Format
  767. **For standard sizes start format string with:**
  768. * `'='` - native byte order
  769. * `'<'` - little-endian
  770. * `'>'` - big-endian
  771. **Use capital leter for unsigned type. Standard size in brackets.**
  772. * `'x'` - pad byte
  773. * `'c'` - char (1)
  774. * `'h'` - short (2)
  775. * `'i'` - int (4)
  776. * `'l'` - long (4)
  777. * `'q'` - long long (8)
  778. * `'f'` - float (4)
  779. * `'d'` - double (8)
  780. Hashlib
  781. -------
  782. ```python
  783. >>> import hashlib
  784. >>> hashlib.md5(<str>.encode()).hexdigest()
  785. '33d0eba106da4d3ebca17fcd3f4c3d77'
  786. ```
  787. Threading
  788. ---------
  789. ```python
  790. from threading import Thread, RLock
  791. ```
  792. ### Thread
  793. ```python
  794. thread = Thread(target=<function>, args=(<first_arg>, ))
  795. thread.start()
  796. ...
  797. thread.join()
  798. ```
  799. ### Lock
  800. ```python
  801. lock = RLock()
  802. lock.acquire()
  803. ...
  804. lock.release()
  805. ```
  806. Itertools
  807. ---------
  808. **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!**
  809. ```python
  810. from itertools import *
  811. ```
  812. ### Combinatoric iterators
  813. ```python
  814. >>> combinations('abc', 2)
  815. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  816. >>> combinations_with_replacement('abc', 2)
  817. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  818. ('b', 'b'), ('b', 'c'),
  819. ('c', 'c')]
  820. >>> permutations('abc', 2)
  821. [('a', 'b'), ('a', 'c'),
  822. ('b', 'a'), ('b', 'c'),
  823. ('c', 'a'), ('c', 'b')]
  824. >>> product('ab', [1, 2])
  825. [('a', 1), ('a', 2),
  826. ('b', 1), ('b', 2)]
  827. >>> product([0, 1], repeat=3)
  828. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  829. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  830. ```
  831. ### Infinite iterators
  832. ```python
  833. >>> i = count(5, 2)
  834. >>> next(i), next(i), next(i)
  835. (5, 7, 9)
  836. >>> a = cycle('abc')
  837. >>> [next(a) for _ in range(10)]
  838. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  839. >>> repeat(10, 3)
  840. [10, 10, 10]
  841. ```
  842. ### Iterators
  843. ```python
  844. >>> chain([1, 2], range(3, 5))
  845. [1, 2, 3, 4]
  846. >>> compress('abc', [True, 0, 1])
  847. ['a', 'c']
  848. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  849. [2, 3]
  850. >>> people = [{'id': 1, 'name': 'Bob'},
  851. {'id': 2, 'name': 'Bob'},
  852. {'id': 3, 'name': 'Peter'}]
  853. >>> groups = groupby(people, key=lambda a: a['name'])
  854. >>> {name: list(group) for name, group in groups}
  855. {'Bob': [{'id': 1, 'name': 'Bob'},
  856. {'id': 2, 'name': 'Bob'}],
  857. 'Peter': [{'id': 3, 'name': 'Peter'}]}
  858. ```
  859. Introspection and Metaprograming
  860. --------------------------------
  861. **Inspecting code at runtime and code that generates code. You can:**
  862. * **Look at the attributes**
  863. * **Set new attributes**
  864. * **Create functions dynamically**
  865. * **Traverse the parent classes**
  866. * **Change values in the class**
  867. ### Variables
  868. ```python
  869. <list> = dir() # Names of in-scope variables.
  870. <dict> = locals() # Dict of local variables, same as vars().
  871. <dict> = globals() # Dict of global variables.
  872. ```
  873. ### Attributes
  874. ```python
  875. >>> class Z:
  876. ... def __init__(self):
  877. ... self.a = 'abcde'
  878. ... self.b = 12345
  879. >>> z = Z()
  880. ```
  881. ```python
  882. >>> vars(z)
  883. {'a': 'abcde', 'b': 12345}
  884. >>> getattr(z, 'a')
  885. 'abcde'
  886. >>> hasattr(z, 'c')
  887. False
  888. >>> setattr(z, 'c', 10)
  889. ```
  890. ### Parameters
  891. ```python
  892. from inspect import signature
  893. sig = signature(<function>)
  894. no_of_params = len(sig.parameters)
  895. param_names = list(sig.parameters.keys())
  896. ```
  897. ### Type
  898. **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!):**
  899. ```python
  900. type(<class_name>, <parents_tuple>, <attributes_dict>)
  901. ```
  902. ```python
  903. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  904. >>> z = Z()
  905. ```
  906. ### Meta Class
  907. #### Class that creates class.
  908. ```python
  909. def my_meta_class(name, parents, attrs):
  910. attrs['a'] = 'abcde'
  911. return type(name, parents, attrs)
  912. ```
  913. #### Or:
  914. ```python
  915. class MyMetaClass(type):
  916. def __new__(klass, name, parents, attrs):
  917. attrs['a'] = 'abcde'
  918. return type.__new__(klass, name, parents, attrs)
  919. ```
  920. ### Metaclass Attribute
  921. **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.**
  922. ```python
  923. class MyClass(metaclass=MyMetaClass):
  924. def __init__(self):
  925. self.b = 12345
  926. ```
  927. Operator
  928. --------
  929. ```python
  930. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  931. eq, ne, lt, le, gt, ge, \
  932. not_, and_, or_, \
  933. itemgetter
  934. ```
  935. ```python
  936. import operator as op
  937. product_of_elems = functools.reduce(op.mul, <list>)
  938. sorted_by_second = sorted(<list>, key=op.itemgetter(1))
  939. sorted_by_both = sorted(<list>, key=op.itemgetter(1, 0))
  940. LogicOp = enum.Enum('LogicOp', {'AND': op.and_,
  941. 'OR' : op.or_})
  942. ```
  943. Eval
  944. ----
  945. ### Basic
  946. ```python
  947. >>> from ast import literal_eval
  948. >>> literal_eval('1 + 2')
  949. 3
  950. >>> literal_eval('[1, 2, 3]')
  951. [1, 2, 3]
  952. >>> ast.literal_eval('abs(1)')
  953. ValueError: malformed node or string
  954. ```
  955. ### Using Abstract Syntax Trees
  956. ```python
  957. import ast
  958. from ast import Num, BinOp, UnaryOp
  959. import operator as op
  960. legal_operators = {ast.Add: op.add,
  961. ast.Sub: op.sub,
  962. ast.Mult: op.mul,
  963. ast.Div: op.truediv,
  964. ast.Pow: op.pow,
  965. ast.BitXor: op.xor,
  966. ast.USub: op.neg}
  967. def evaluate(expression):
  968. root = ast.parse(expression, mode='eval')
  969. return eval_node(root.body)
  970. def eval_node(node):
  971. node_type = type(node)
  972. if node_type == Num:
  973. return node.n
  974. if node_type not in [BinOp, UnaryOp]:
  975. raise TypeError(node)
  976. operator_type = type(node.op)
  977. if operator_type not in legal_operators:
  978. raise TypeError(f'Illegal operator {node.op}')
  979. operator = legal_operators[operator_type]
  980. if node_type == BinOp:
  981. left, right = eval_node(node.left), eval_node(node.right)
  982. return operator(left, right)
  983. elif node_type == UnaryOp:
  984. operand = eval_node(node.operand)
  985. return operator(operand)
  986. ```
  987. ```python
  988. >>> evaluate('2 ^ 6')
  989. 4
  990. >>> evaluate('2 ** 6')
  991. 64
  992. >>> evaluate('1 + 2 * 3 ** (4 ^ 5) / (6 + -7)')
  993. -5.0
  994. ```
  995. Coroutine
  996. ---------
  997. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  998. * **Coroutines provide more powerful data routing possibilities than iterators.**
  999. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  1000. ### Helper Decorator
  1001. * **All coroutines must be "primed" by first calling next().**
  1002. * **Remembering to call next() is easy to forget.**
  1003. * **Solved by wrapping coroutines with a decorator:**
  1004. ```python
  1005. def coroutine(func):
  1006. def out(*args, **kwargs):
  1007. cr = func(*args, **kwargs)
  1008. next(cr)
  1009. return cr
  1010. return out
  1011. ```
  1012. ### Pipeline Example
  1013. ```python
  1014. def reader(target):
  1015. for i in range(10):
  1016. target.send(i)
  1017. target.close()
  1018. @coroutine
  1019. def adder(target):
  1020. while True:
  1021. item = (yield)
  1022. target.send(item + 100)
  1023. @coroutine
  1024. def printer():
  1025. while True:
  1026. item = (yield)
  1027. print(item)
  1028. reader(adder(printer())) # 100, 101, ..., 109
  1029. ```
  1030. <br><br>
  1031. Libraries
  1032. =========
  1033. Argparse
  1034. --------
  1035. ```python
  1036. import argparse
  1037. parser = argparse.ArgumentParser(description='calculate X to the power of Y')
  1038. group = parser.add_mutually_exclusive_group()
  1039. group.add_argument('-v', '--verbose', action='store_true')
  1040. group.add_argument('-q', '--quiet', action='store_true')
  1041. parser.add_argument('x', type=int, help='the base')
  1042. parser.add_argument('y', type=int, help='the exponent')
  1043. args = parser.parse_args()
  1044. answer = args.x ** args.y
  1045. if args.quiet:
  1046. print(answer)
  1047. elif args.verbose:
  1048. print(f'{args.x} to the power {args.y} equals {answer}')
  1049. else:
  1050. print(f'{args.x}^{args.y} == {answer}')
  1051. ```
  1052. #### Usage:
  1053. ```
  1054. $ python3 prog.py --help
  1055. usage: test2.py [-h] [-v | -q] x y
  1056. calculate X to the power of Y
  1057. positional arguments:
  1058. x the base
  1059. y the exponent
  1060. optional arguments:
  1061. -h, --help show this help message and exit
  1062. -v, --verbose
  1063. -q, --quiet
  1064. ```
  1065. Plot
  1066. ----
  1067. ```python
  1068. # $ pip3 install matplotlib
  1069. from matplotlib import pyplot
  1070. pyplot.plot(<data_1> [, <data_2>, ...])
  1071. pyplot.savefig(<filename>, transparent=True)
  1072. pyplot.show()
  1073. ```
  1074. Progress Bar
  1075. ------------
  1076. ```python
  1077. # $ pip3 install tqdm
  1078. from tqdm import tqdm
  1079. from time import sleep
  1080. for i in tqdm([1, 2, 3]):
  1081. sleep(0.2)
  1082. for i in tqdm(range(100)):
  1083. sleep(0.02)
  1084. ```
  1085. Table
  1086. -----
  1087. #### Prints CSV file as ASCII table:
  1088. ```python
  1089. # $ pip3 install tabulate
  1090. from csv import reader
  1091. from tabulate import tabulate
  1092. with open(<filename>, newline='') as csv_file:
  1093. reader = reader(csv_file, delimiter=';')
  1094. headers = [a.title() for a in next(reader)]
  1095. print(tabulate(reader, headers))
  1096. ```
  1097. Curses
  1098. ------
  1099. ```python
  1100. # $ pip3 install curses
  1101. from curses import wrapper
  1102. def main():
  1103. wrapper(draw)
  1104. def draw(screen):
  1105. screen.clear()
  1106. screen.addstr(0, 0, 'Press ESC to quit.')
  1107. while screen.getch() != 27:
  1108. pass
  1109. def get_border(screen):
  1110. from collections import namedtuple
  1111. P = namedtuple('P', 'x y')
  1112. height, width = screen.getmaxyx()
  1113. return P(width - 1, height - 1)
  1114. ```
  1115. Image
  1116. -----
  1117. #### Creates PNG image of greyscale gradient:
  1118. ```python
  1119. # $ pip3 install pillow
  1120. from PIL import Image
  1121. width, height = 100, 100
  1122. img = Image.new('L', (width, height), 'white')
  1123. img.putdata([255*a/(width*height) for a in range(width*height)])
  1124. img.save('out.png')
  1125. ```
  1126. ### Modes
  1127. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1128. * `'L'` - 8-bit pixels, greyscale.
  1129. * `'RGB'` - 3x8-bit pixels, true color.
  1130. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1131. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1132. Audio
  1133. -----
  1134. #### Saves a list of floats with values between 0 and 1 to a WAV file:
  1135. ```python
  1136. import wave, struct
  1137. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1138. wf = wave.open(<filename>, 'wb')
  1139. wf.setnchannels(1)
  1140. wf.setsampwidth(4)
  1141. wf.setframerate(44100)
  1142. wf.writeframes(b''.join(frames))
  1143. wf.close()
  1144. ```
  1145. Url
  1146. ---
  1147. ```python
  1148. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1149. ```
  1150. ### Encode
  1151. ```python
  1152. >>> quote("Can't be in URL!")
  1153. 'Can%27t%20be%20in%20URL%21'
  1154. >>> quote_plus("Can't be in URL!")
  1155. 'Can%27t+be+in+URL%21'
  1156. ```
  1157. ### Decode
  1158. ```python
  1159. >>> unquote('Can%27t+be+in+URL%21')
  1160. "Can't+be+in+URL!"'
  1161. >>> unquote_plus('Can%27t+be+in+URL%21')
  1162. "Can't be in URL!"
  1163. ```
  1164. Scraping
  1165. --------
  1166. ```python
  1167. # $ pip3 install requests beautifulsoup4
  1168. >>> import requests
  1169. >>> from bs4 import BeautifulSoup
  1170. >>> url = 'https://en.wikipedia.org/wiki/Python_(programming_language)'
  1171. >>> page = requests.get(url)
  1172. >>> document = BeautifulSoup(page.text, 'html.parser')
  1173. >>> table = document.find('table', class_='infobox vevent')
  1174. >>> rows = table.find_all('tr')
  1175. >>> link = rows[11].find('a')['href']
  1176. 'https://www.python.org/'
  1177. >>> latest_v = rows[6].find('div').text.split()[0]
  1178. '3.7.2'
  1179. ```
  1180. Web
  1181. ---
  1182. ```python
  1183. # $ pip3 install bottle
  1184. import bottle
  1185. from urllib.parse import unquote
  1186. ```
  1187. ### Run
  1188. ```python
  1189. bottle.run(host='localhost', port=8080)
  1190. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1191. ```
  1192. ### Static Request
  1193. ```python
  1194. @route('/img/<image>')
  1195. def send_image(image):
  1196. return static_file(image, 'images/', mimetype='image/png')
  1197. ```
  1198. ### Dynamic Request
  1199. ```python
  1200. @route('/<sport>')
  1201. def send_page(sport):
  1202. sport = unquote(sport).lower()
  1203. page = read_file(sport)
  1204. return template(page)
  1205. ```
  1206. ### REST Request
  1207. ```python
  1208. @post('/odds/<sport>')
  1209. def odds_handler(sport):
  1210. team = bottle.request.forms.get('team')
  1211. team = unquote(team).lower()
  1212. db = sqlite3.connect(<db_path>)
  1213. home_odds, away_odds = get_odds(db, sport, team)
  1214. db.close()
  1215. response.headers['Content-Type'] = 'application/json'
  1216. response.headers['Cache-Control'] = 'no-cache'
  1217. return json.dumps([home_odds, away_odds])
  1218. ```
  1219. Profile
  1220. -------
  1221. ### Basic
  1222. ```python
  1223. from time import time
  1224. start_time = time()
  1225. ...
  1226. duration = time() - start_time
  1227. ```
  1228. ### Timing a Snippet
  1229. ```python
  1230. from timeit import timeit
  1231. timeit('"-".join(str(a) for a in range(100))',
  1232. number=10000, globals=globals(), setup='pass')
  1233. ```
  1234. ### Line Profiler
  1235. ```python
  1236. # $ pip3 install line_profiler
  1237. @profile
  1238. def main():
  1239. a = [*range(10000)]
  1240. b = {*range(10000)}
  1241. main()
  1242. ```
  1243. ```
  1244. $ kernprof -lv test.py
  1245. Line # Hits Time Per Hit % Time Line Contents
  1246. ==============================================================
  1247. 1 @profile
  1248. 2 def main():
  1249. 3 1 1128.0 1128.0 27.4 a = [*range(10000)]
  1250. 4 1 2994.0 2994.0 72.6 b = {*range(10000)}
  1251. ```
  1252. ### Call Graph
  1253. #### Generates a PNG image of call graph with highlighted bottlenecks.
  1254. ```python
  1255. # $ pip3 install pycallgraph
  1256. from pycallgraph import output, PyCallGraph
  1257. from datetime import datetime
  1258. graph = output.GraphvizOutput()
  1259. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1260. graph.output_file = f'profile-{time_str}.png'
  1261. with PyCallGraph(output=graph):
  1262. <code_to_be_profiled>
  1263. ```
  1264. NumPy
  1265. -----
  1266. **Array manipulation mini language. Can run up to 100 times faster than equivalent Python code.**
  1267. ```python
  1268. # $ pip3 install numpy
  1269. import numpy as np
  1270. ```
  1271. ```python
  1272. <array> = np.array(<list>)
  1273. <array> = np.arange(from_inclusive, to_exclusive, step_size)
  1274. <array> = np.ones(<shape>)
  1275. <array> = np.random.randint(from_inclusive, to_exclusive, <shape>)
  1276. ```
  1277. ```python
  1278. value = <array>.min([axis])
  1279. index = <array>.argmin([axis])
  1280. ```
  1281. ```python
  1282. <view> = <array>.reshape(<shape>)
  1283. <view> = np.broadcast_to(<array>, <shape>)
  1284. <array> = <array>[filter_expression]
  1285. ```
  1286. ### Broadcasting
  1287. **Broadcasting is a set of rules by which NumPy functions operate on arrays of different sizes and/or dimensions:**
  1288. ```python
  1289. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1290. right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3)
  1291. ```
  1292. **1. If array shapes differ, left-pad the smaller shape with ones.**
  1293. ```python
  1294. left = [[0.1], [0.6], [0.8]] # Shape: (3, 1)
  1295. right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- !
  1296. ```
  1297. **2. If any dimensions differ in size, expand the ones that have size 1 by duplicating their elements.**
  1298. ```python
  1299. left = [[0.1, 0.1, 0.1], [0.6, 0.6, 0.6], [0.8, 0.8, 0.8]] # Shape: (3, 3) <- !
  1300. right = [[0.1, 0.6, 0.8], [0.1, 0.6, 0.8], [0.1, 0.6, 0.8]] # Shape: (3, 3) <- !
  1301. ```
  1302. **3. If neither non-matching dimension has size 1, rise an error.**
  1303. ### Example
  1304. **For each point returns index of its nearest point: `[0.1, 0.6, 0.8] => [1, 2, 1]`.**
  1305. ```python
  1306. >>> points = np.array([0.1, 0.6, 0.8])
  1307. [ 0.1, 0.6, 0.8]
  1308. >>> wrapped_points = points.reshape(3, 1)
  1309. [[ 0.1],
  1310. [ 0.6],
  1311. [ 0.8]]
  1312. >>> distances = wrapped_points - points
  1313. [[ 0. , -0.5, -0.7],
  1314. [ 0.5, 0. , -0.2],
  1315. [ 0.7, 0.2, 0. ]]
  1316. >>> distances = np.abs(distances)
  1317. [[ 0. , 0.5, 0.7],
  1318. [ 0.5, 0. , 0.2],
  1319. [ 0.7, 0.2, 0. ]]
  1320. >>> i = np.arange(3)
  1321. [0, 1, 2]
  1322. >>> distances[i, i] = np.inf
  1323. [[ inf, 0.5, 0.7],
  1324. [ 0.5, inf, 0.2],
  1325. [ 0.7, 0.2, inf]]
  1326. >>> distances.argmin(1)
  1327. [1, 2, 1]
  1328. ```
  1329. Basic Script Template
  1330. ---------------------
  1331. ```python
  1332. #!/usr/bin/env python3
  1333. #
  1334. # Usage: .py
  1335. #
  1336. from collections import namedtuple
  1337. from enum import Enum
  1338. import re
  1339. import sys
  1340. def main():
  1341. pass
  1342. ###
  1343. ## UTIL
  1344. #
  1345. def read_file(filename):
  1346. with open(filename, encoding='utf-8') as file:
  1347. return file.readlines()
  1348. if __name__ == '__main__':
  1349. main()
  1350. ```