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.

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