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.

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