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.

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