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.

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