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.

1449 lines
29 KiB

7 years ago
7 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
7 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
6 years ago
7 years ago
7 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
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
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
7 years ago
6 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
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
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
7 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
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
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
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
6 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
6 years ago
6 years ago
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
7 years ago
7 years ago
7 years ago
7 years ago
7 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
7 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
6 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
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
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
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
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
6 years ago
6 years ago
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
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
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
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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
6 years ago
7 years ago
7 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
  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(<list>)
  19. <list> += [<el>]
  20. <list> += <list>
  21. ```
  22. ```python
  23. <list>.sort()
  24. <list>.reverse()
  25. <list> = sorted(<list>)
  26. <iter> = reversed(<list>)
  27. ```
  28. ```python
  29. sum_of_elements = sum(<list>)
  30. elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)]
  31. sorted_by_second = sorted(<list>, key=lambda el: el[1])
  32. sorted_by_both = sorted(<list>, 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, <list>)
  36. ```
  37. ```python
  38. index = <list>.index(<el>) # Returns first index of item.
  39. <list>.insert(index, <el>) # Inserts item at index and moves the rest to the right.
  40. <el> = <list>.pop([index]) # Removes and returns item at index or from the end.
  41. <list>.remove(<el>) # Removes first occurrence of item.
  42. <list>.clear() # Removes all items.
  43. ```
  44. Dictionary
  45. ----------
  46. ```python
  47. <view> = <dict>.keys()
  48. <view> = <dict>.values()
  49. <view> = <dict>.items()
  50. <value> = <dict>.get(key, default) # Returns default if key does not exist.
  51. <value> = <dict>.setdefault(key, default) # Same, but also adds default to dict.
  52. <dict>.update(<dict>)
  53. ```
  54. ```python
  55. collections.defaultdict(<type>) # Creates a dictionary with default value of type.
  56. collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1.
  57. collections.OrderedDict() # Creates ordered dictionary.
  58. ```
  59. ```python
  60. dict(<list>) # Initiates a dict from list of key-value pairs.
  61. dict(zip(keys, values)) # Initiates a dict from two lists.
  62. {k: v for k, v in <dict>.items() if k in <list>} # Filters a dict by keys.
  63. ```
  64. ### Counter
  65. ```python
  66. >>> from collections import Counter
  67. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  68. >>> Counter(colors)
  69. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  70. >>> <counter>.most_common()[0][0]
  71. 'blue'
  72. ```
  73. Set
  74. ---
  75. ```python
  76. <set> = set()
  77. <set>.add(<el>)
  78. <set>.update(<set>)
  79. <set>.clear()
  80. ```
  81. ```python
  82. <set> = <set>.union(<set>) # Or: <set> | <set>
  83. <set> = <set>.intersection(<set>) # Or: <set> & <set>
  84. <set> = <set>.difference(<set>) # Or: <set> - <set>
  85. <set> = <set>.symmetric_difference(<set>) # Or: <set> ^ <set>
  86. <bool> = <set>.issubset(<set>)
  87. <bool> = <set>.issuperset(<set>)
  88. ```
  89. ### Frozenset
  90. #### Is hashable and can be used as a key in dictionary.
  91. ```python
  92. <frozenset> = frozenset(<collection>)
  93. ```
  94. Range
  95. -----
  96. ```python
  97. range(to_exclusive)
  98. range(from_inclusive, to_exclusive)
  99. range(from_inclusive, to_exclusive, step_size)
  100. range(from_inclusive, to_exclusive, -step_size)
  101. ```
  102. ```python
  103. from_inclusive = <range>.start
  104. to_exclusive = <range>.stop
  105. ```
  106. Enumerate
  107. ---------
  108. ```python
  109. for i, <el> in enumerate(<collection> [, i_start]):
  110. ...
  111. ```
  112. Named Tuple
  113. -----------
  114. ```python
  115. >>> Point = collections.namedtuple('Point', ['x', 'y'])
  116. >>> a = Point(1, y=2)
  117. Point(x=1, y=2)
  118. >>> a.x
  119. 1
  120. >>> getattr(a, 'y')
  121. 2
  122. >>> Point._fields
  123. ('x', 'y')
  124. ```
  125. Iterator
  126. --------
  127. #### Skips first element:
  128. ```python
  129. next(<iter>)
  130. for element in <iter>:
  131. ...
  132. ```
  133. #### Reads input until it reaches an empty line:
  134. ```python
  135. for line in iter(input, ''):
  136. ...
  137. ```
  138. #### Same, but prints a message every time:
  139. ```python
  140. from functools import partial
  141. for line in iter(partial(input, 'Please enter value'), ''):
  142. ...
  143. ```
  144. Generator
  145. ---------
  146. **Convenient way to implement the iterator protocol.**
  147. ```python
  148. def step(start, step):
  149. while True:
  150. yield start
  151. start += step
  152. ```
  153. ```python
  154. >>> stepper = step(10, 2)
  155. >>> next(stepper), next(stepper), next(stepper)
  156. (10, 12, 14)
  157. ```
  158. Type
  159. ----
  160. ```python
  161. <type> = type(<el>) # <class 'int'> / <class 'str'> / ...
  162. ```
  163. ```python
  164. from numbers import Number, Integral, Real, Rational, Complex
  165. is_number = isinstance(<el>, Number)
  166. is_function = callable(<el>)
  167. ```
  168. String
  169. ------
  170. ```python
  171. <str> = <str>.strip() # Strips all whitespace characters.
  172. <str> = <str>.strip('<chars>') # Strips all passed characters.
  173. ```
  174. ```python
  175. <list> = <str>.split() # Splits on any whitespace character.
  176. <list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' at most 'maxsplit' times.
  177. <str> = <str>.join(<list>) # Joins elements using string as separator.
  178. ```
  179. ```python
  180. <str> = <str>.replace(old_str, new_str)
  181. <bool> = <str>.startswith(<sub_str>) # Pass tuple of strings for multiple options.
  182. <bool> = <str>.endswith(<sub_str>) # Pass tuple of strings for multiple options.
  183. <int> = <str>.index(<sub_str>) # Returns first index of a substring.
  184. <bool> = <str>.isnumeric() # True if str contains only numeric characters.
  185. <list> = textwrap.wrap(<str>, width) # Nicely breaks string into lines.
  186. ```
  187. ### Char
  188. ```python
  189. <str> = chr(<int>) # Converts int to unicode char.
  190. <int> = ord(<str>) # Converts unicode char to int.
  191. ```
  192. ```python
  193. >>> ord('0'), ord('9')
  194. (48, 57)
  195. >>> ord('A'), ord('Z')
  196. (65, 90)
  197. >>> ord('a'), ord('z')
  198. (97, 122)
  199. ```
  200. ### Print
  201. ```python
  202. print(<el_1> [, <el_2>, end='', sep='', file=<file>]) # Use 'file=sys.stderr' for errors.
  203. ```
  204. ```python
  205. >>> from pprint import pprint
  206. >>> pprint(locals())
  207. {'__doc__': None,
  208. '__name__': '__main__',
  209. '__package__': None, ...}
  210. ```
  211. Regex
  212. -----
  213. ```python
  214. import re
  215. <str> = re.sub(<regex>, new, text, count=0) # Substitutes all occurrences.
  216. <list> = re.findall(<regex>, text)
  217. <list> = re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  218. <Match> = re.search(<regex>, text) # Searches for first occurrence of pattern.
  219. <Match> = re.match(<regex>, text) # Searches only at the beginning of the text.
  220. <Match_iter> = re.finditer(<regex>, text) # Searches for all occurrences of pattern.
  221. ```
  222. * **Parameter 'flags=re.IGNORECASE' can be used with all functions. Parameter 'flags=re.DOTALL' makes dot also accept newline.**
  223. * **Use '\\\\1' or r'\1' for backreference.**
  224. * **Use ? to make operators non-greedy.**
  225. ### Match Object
  226. ```python
  227. <str> = <Match>.group() # Whole match.
  228. <str> = <Match>.group(1) # Part in first bracket.
  229. <int> = <Match>.start() # Start index of a match.
  230. <int> = <Match>.end() # Exclusive end index of a match.
  231. ```
  232. ### Special Sequences
  233. **Use capital letter for negation.**
  234. ```python
  235. '\d' == '[0-9]' # Digit
  236. '\s' == '[ \t\n\r\f\v]' # Whitespace
  237. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  238. ```
  239. Format
  240. ------
  241. ```python
  242. <str> = f'{<el_1>}, {<el_2>}'
  243. <str> = '{}, {}'.format(<el_1>, <el_2>)
  244. ```
  245. ```python
  246. >>> Person = namedtuple('Person', 'name height')
  247. >>> person = Person('Jean-Luc', 187)
  248. >>> f'{person.height:10}'
  249. ' 187'
  250. >>> '{p.height:10}'.format(p=person)
  251. ' 187'
  252. ```
  253. ### General Options
  254. ```python
  255. {<el>:<10} # '<el> '
  256. {<el>:>10} # ' <el>'
  257. {<el>:^10} # ' <el> '
  258. {<el>:->10} # '------<el>'
  259. {<el>:>0} # '<el>'
  260. ```
  261. ### String Options
  262. ```python
  263. {'abcde':.3} # 'abc'
  264. {'abcde':10.3} # 'abc '
  265. ```
  266. ### Number Options
  267. ```python
  268. {1.23456:.3f} # '1.235'
  269. {1.23456:10.3f} # ' 1.235'
  270. ```
  271. ```python
  272. {123456:10,} # ' 123,456'
  273. {123456:10_} # ' 123_456'
  274. {123456:+10} # ' +123456'
  275. ```
  276. ```python
  277. {65:c} # 'A'
  278. {3:08b} # '00000011' -> Binary with leading zeros.
  279. {3:0<8b} # '11000000' -> Binary with trailing zeros.
  280. ```
  281. #### Float presentation types:
  282. * `'f'` - Fixed point: `.<precision>f`
  283. * `'e'` - Exponent
  284. #### Integer presentation types:
  285. * `'c'` - Character
  286. * `'b'` - Binary
  287. * `'x'` - Hex
  288. * `'X'` - HEX
  289. Numbers
  290. -------
  291. ### Basic Functions
  292. ```python
  293. round(<num> [, ndigits])
  294. abs(<num>)
  295. math.pow(x, y) # Or: x ** y
  296. ```
  297. ### Constants
  298. ```python
  299. from math import e, pi
  300. ```
  301. ### Trigonometry
  302. ```python
  303. from math import cos, acos, sin, asin, tan, atan, degrees, radians
  304. ```
  305. ### Logarithm
  306. ```python
  307. from math import log, log10, log2
  308. log(x [, base]) # Base e, if not specified.
  309. log10(x) # Base 10.
  310. log2(x) # Base 2.
  311. ```
  312. ### Infinity, nan
  313. ```python
  314. from math import inf, nan, isfinite, isinf, isnan
  315. ```
  316. #### Or:
  317. ```python
  318. float('inf'), float('nan')
  319. ```
  320. ### Random
  321. ```python
  322. from random import random, randint, choice, shuffle
  323. <float> = random()
  324. <int> = randint(from_inclusive, to_inclusive)
  325. <el> = choice(<list>)
  326. shuffle(<list>)
  327. ```
  328. Datetime
  329. --------
  330. ```python
  331. from datetime import datetime, strptime
  332. now = datetime.now()
  333. now.month # 3
  334. now.strftime('%Y%m%d') # '20180315'
  335. now.strftime('%Y%m%d%H%M%S') # '20180315002834'
  336. <datetime> = strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M')
  337. ```
  338. Arguments
  339. ---------
  340. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.**
  341. ```python
  342. args = (1, 2)
  343. kwargs = {'x': 3, 'y': 4, 'z': 5}
  344. func(*args, **kwargs)
  345. ```
  346. #### Is the same as:
  347. ```python
  348. func(1, 2, x=3, y=4, z=5)
  349. ```
  350. #### Splat operator can also be used in function declarations:
  351. ```python
  352. def add(*a):
  353. return sum(a)
  354. ```
  355. ```python
  356. >>> add(1, 2, 3)
  357. 6
  358. ```
  359. #### And in few other places:
  360. ```python
  361. >>> a = (1, 2, 3)
  362. >>> [*a]
  363. [1, 2, 3]
  364. ```
  365. ```python
  366. >>> head, *body, tail = [1, 2, 3, 4]
  367. >>> body
  368. [2, 3]
  369. ```
  370. Inline
  371. ------
  372. ### Lambda
  373. ```python
  374. lambda: <return_value>
  375. lambda <argument_1>, <argument_2>: <return_value>
  376. ```
  377. ### Comprehension
  378. ```python
  379. <list> = [i+1 for i in range(10)] # [1, 2, ..., 10]
  380. <set> = {i for i in range(10) if i > 5} # {6, 7, ..., 9}
  381. <dict> = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  382. <iter> = (x+5 for x in range(10)) # (5, 6, ..., 14)
  383. ```
  384. ```python
  385. out = [i+j for i in range(10) for j in range(10)]
  386. ```
  387. #### Is the same as:
  388. ```python
  389. out = []
  390. for i in range(10):
  391. for j in range(10):
  392. out.append(i+j)
  393. ```
  394. ### Map, Filter, Reduce
  395. ```python
  396. from functools import reduce
  397. <iter> = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10)
  398. <iter> = filter(lambda x: x > 5, range(10)) # (6, 7, ..., 9)
  399. <any_type> = reduce(lambda sum, x: sum+x, range(10)) # 45
  400. ```
  401. ### Any, All
  402. ```python
  403. <bool> = any(el[1] for el in <collection>)
  404. ```
  405. ### If - Else
  406. ```python
  407. <expression_if_true> if <condition> else <expression_if_false>
  408. ```
  409. ```python
  410. >>> [a if a else 'zero' for a in (0, 1, 0, 3)]
  411. ['zero', 1, 'zero', 3]
  412. ```
  413. ### Namedtuple, Enum, Class
  414. ```python
  415. from collections import namedtuple
  416. Point = namedtuple('Point', 'x y')
  417. from enum import Enum
  418. Direction = Enum('Direction', 'n e s w')
  419. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  420. # Warning: Objects will share the objects that are initialized in the dictionary!
  421. Creature = type('Creature', (), {'position': Point(0, 0), 'direction': Direction.n})
  422. creature = Creature()
  423. ```
  424. Closure
  425. -------
  426. ```python
  427. def get_multiplier(a):
  428. def out(b):
  429. return a * b
  430. return out
  431. ```
  432. ```python
  433. >>> multiply_by_3 = get_multiplier(3)
  434. >>> multiply_by_3(10)
  435. 30
  436. ```
  437. #### Or:
  438. ```python
  439. from functools import partial
  440. partial(<function>, <arg_1> [, <arg_2>, ...])
  441. ```
  442. Decorator
  443. ---------
  444. ```python
  445. @closure_name
  446. def function_that_gets_passed_to_closure():
  447. ...
  448. ```
  449. #### Debugger example:
  450. ```python
  451. from functools import wraps
  452. def debug(func):
  453. @wraps(func) # Needed for metadata copying (func name, ...).
  454. def out(*args, **kwargs):
  455. print(func.__name__)
  456. return func(*args, **kwargs)
  457. return out
  458. @debug
  459. def add(x, y):
  460. return x + y
  461. ```
  462. Class
  463. -----
  464. ```python
  465. class <name>:
  466. def __init__(self, a):
  467. self.a = a
  468. def __str__(self):
  469. return str(self.a)
  470. def __repr__(self):
  471. return str({'a': self.a}) # Or: return f'{self.__dict__}'
  472. @classmethod
  473. def get_class_name(cls):
  474. return cls.__name__
  475. ```
  476. ### Constructor Overloading
  477. ```python
  478. class <name>:
  479. def __init__(self, a=None):
  480. self.a = a
  481. ```
  482. ### Copy
  483. ```python
  484. from copy import copy, deepcopy
  485. <object> = copy(<object>)
  486. <object> = deepcopy(<object>)
  487. ```
  488. Enum
  489. ----
  490. ```python
  491. from enum import Enum, auto
  492. class <enum_name>(Enum):
  493. <member_name_1> = <value_1>
  494. <member_name_2> = <value_2_a>, <value_2_b>
  495. <member_name_3> = auto() # Can be used for automatic indexing.
  496. ...
  497. @classmethod
  498. def get_names(cls):
  499. return [a.name for a in cls.__members__.values()]
  500. @classmethod
  501. def get_values(cls):
  502. return [a.value for a in cls.__members__.values()]
  503. ```
  504. ```python
  505. <member> = <enum>.<member_name>
  506. <member> = <enum>['<member_name>']
  507. <member> = <enum>(<value>)
  508. <name> = <member>.name
  509. <value> = <member>.value
  510. ```
  511. ```python
  512. list_of_members = list(<enum>)
  513. member_names = [a.name for a in <enum>]
  514. random_member = random.choice(list(<enum>))
  515. ```
  516. ### Inline
  517. ```python
  518. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  519. Cutlery = Enum('Cutlery', 'knife fork spoon')
  520. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  521. # Functions can not be values, so they must be enclosed in tuple:
  522. LogicOp = Enum('LogicOp', {'AND': (lambda l, r: l and r, ),
  523. 'OR' : (lambda l, r: l or r, )})
  524. # But 'list(<enum>)' will only work if there is another value in the tuple:
  525. LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r),
  526. 'OR' : (auto(), lambda l, r: l or r)})
  527. ```
  528. System
  529. ------
  530. ### Arguments
  531. ```python
  532. import sys
  533. script_name = sys.argv[0]
  534. arguments = sys.argv[1:]
  535. ```
  536. ### Read File
  537. ```python
  538. def read_file(filename):
  539. with open(filename, encoding='utf-8') as file:
  540. return file.readlines()
  541. ```
  542. ### Write to File
  543. ```python
  544. def write_to_file(filename, text):
  545. with open(filename, 'w', encoding='utf-8') as file:
  546. file.write(text)
  547. ```
  548. ### Path
  549. ```python
  550. import os
  551. <bool> = os.path.exists(<path>)
  552. <bool> = os.path.isfile(<path>)
  553. <bool> = os.path.isdir(<path>)
  554. <list> = os.listdir(<path>)
  555. ```
  556. ### Execute Command
  557. ```python
  558. import os
  559. <str> = os.popen(<command>).read()
  560. ```
  561. #### Or:
  562. ```python
  563. >>> import subprocess
  564. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  565. >>> a.stdout
  566. b'.\n..\nfile1.txt\nfile2.txt\n'
  567. >>> a.returncode
  568. 0
  569. ```
  570. ### Input
  571. ```python
  572. filename = input('Enter a file name: ')
  573. ```
  574. #### Prints lines until EOF:
  575. ```python
  576. while True:
  577. try:
  578. print(input())
  579. except EOFError:
  580. break
  581. ```
  582. ### Recursion Limit
  583. ```python
  584. >>> sys.getrecursionlimit()
  585. 1000
  586. >>> sys.setrecursionlimit(10000)
  587. ```
  588. JSON
  589. ----
  590. ```python
  591. import json
  592. ```
  593. ### Serialization
  594. ```python
  595. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  596. <dict> = json.loads(<str>)
  597. ```
  598. #### To preserve order:
  599. ```python
  600. from collections import OrderedDict
  601. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  602. ```
  603. ### Read File
  604. ```python
  605. def read_json_file(filename):
  606. with open(filename, encoding='utf-8') as file:
  607. return json.load(file)
  608. ```
  609. ### Write to File
  610. ```python
  611. def write_to_json_file(filename, an_object):
  612. with open(filename, 'w', encoding='utf-8') as file:
  613. json.dump(an_object, file, ensure_ascii=False, indent=2)
  614. ```
  615. SQLite
  616. ------
  617. ```python
  618. import sqlite3
  619. db = sqlite3.connect(<filename>)
  620. ```
  621. ### Read
  622. ```python
  623. cursor = db.execute(<query>)
  624. if cursor:
  625. cursor.fetchall() # Or cursor.fetchone()
  626. db.close()
  627. ```
  628. ### Write
  629. ```python
  630. db.execute(<query>)
  631. db.commit()
  632. ```
  633. Pickle
  634. ------
  635. ```python
  636. import pickle
  637. favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  638. pickle.dump(favorite_color, open('data.p', 'wb'))
  639. favorite_color = pickle.load(open('data.p', 'rb'))
  640. ```
  641. Exceptions
  642. ----------
  643. ```python
  644. while True:
  645. try:
  646. x = int(input('Please enter a number: '))
  647. except ValueError:
  648. print('Oops! That was no valid number. Try again...')
  649. else:
  650. print('Thank you.')
  651. break
  652. ```
  653. #### Raising exception:
  654. ```python
  655. raise ValueError('A very specific message!')
  656. ```
  657. #### Finally:
  658. ```python
  659. >>> try:
  660. ... raise KeyboardInterrupt
  661. ... finally:
  662. ... print('Goodbye, world!')
  663. ...
  664. Goodbye, world!
  665. Traceback (most recent call last):
  666. File "<stdin>", line 2, in <module>
  667. KeyboardInterrupt
  668. ```
  669. Bytes
  670. -----
  671. **Bytes objects are immutable sequences of single bytes.**
  672. ### Encode
  673. ```python
  674. <Bytes> = b'<str>'
  675. <Bytes> = <str>.encode(encoding='utf-8')
  676. <Bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
  677. <Bytes> = bytes.fromhex(<hex>)
  678. ```
  679. ### Decode
  680. ```python
  681. <str> = <Bytes>.decode('utf-8')
  682. <int> = int.from_bytes(<Bytes>, byteorder='big|little', signed=False)
  683. <hex> = <Bytes>.hex()
  684. ```
  685. ### Read Bytes from File
  686. ```python
  687. def read_bytes(filename):
  688. with open(filename, 'rb') as file:
  689. return file.read()
  690. ```
  691. ### Write Bytes to File
  692. ```python
  693. def write_bytes(filename, bytes):
  694. with open(filename, 'wb') as file:
  695. file.write(bytes)
  696. ```
  697. ```python
  698. <Bytes> = b''.join(<list_of_Bytes>)
  699. ```
  700. Struct
  701. ------
  702. **This module performs conversions between Python values and C struct represented as Python Bytes object.**
  703. ```python
  704. <Bytes> = struct.pack('<format>', <value_1> [, <value_2>, ...])
  705. <tuple> = struct.unpack('<format>', <Bytes>)
  706. ```
  707. ### Example
  708. ```python
  709. >>> from struct import pack, unpack, calcsize
  710. >>> pack('hhl', 1, 2, 3)
  711. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  712. >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  713. (1, 2, 3)
  714. >>> calcsize('hhl')
  715. 8
  716. ```
  717. ### Format
  718. **Use capital leters for unsigned type.**
  719. * `'x'` - pad byte
  720. * `'c'` - char
  721. * `'h'` - short
  722. * `'i'` - int
  723. * `'l'` - long
  724. * `'q'` - long long
  725. * `'f'` - float
  726. * `'d'` - double
  727. Hashlib
  728. -------
  729. ```python
  730. >>> hashlib.md5(<str>.encode()).hexdigest()
  731. '33d0eba106da4d3ebca17fcd3f4c3d77'
  732. ```
  733. Threading
  734. ---------
  735. ```python
  736. from threading import Thread, RLock
  737. ```
  738. ### Thread
  739. ```python
  740. thread = Thread(target=<function>, args=(<first_arg>, ))
  741. thread.start()
  742. ...
  743. thread.join()
  744. ```
  745. ### Lock
  746. ```python
  747. lock = Rlock()
  748. lock.acquire()
  749. ...
  750. lock.release()
  751. ```
  752. Itertools
  753. ---------
  754. **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.**
  755. ```python
  756. from itertools import *
  757. ```
  758. ### Combinatoric iterators
  759. ```python
  760. >>> combinations('abc', 2)
  761. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  762. >>> combinations_with_replacement('abc', 2)
  763. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  764. ('b', 'b'), ('b', 'c'), ('c', 'c')]
  765. >>> permutations('abc', 2)
  766. [('a', 'b'), ('a', 'c'),
  767. ('b', 'a'), ('b', 'c'),
  768. ('c', 'a'), ('c', 'b')]
  769. >>> product('ab', [1, 2])
  770. [('a', 1), ('a', 2),
  771. ('b', 1), ('b', 2)]
  772. >>> product([0, 1], repeat=3)
  773. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  774. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  775. ```
  776. ### Infinite iterators
  777. ```python
  778. >>> i = count(5, 2)
  779. >>> next(i), next(i), next(i)
  780. (5, 7, 9)
  781. >>> a = cycle('abc')
  782. >>> [next(a) for _ in range(10)]
  783. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  784. >>> repeat(10, 3)
  785. [10, 10, 10]
  786. ```
  787. ### Iterators
  788. ```python
  789. >>> chain([1, 2], range(3, 5))
  790. [1, 2, 3, 4]
  791. >>> compress('abc', [True, 0, 1])
  792. ['a', 'c']
  793. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  794. [2, 3]
  795. >>> people = [{'id': 1, 'name': 'bob'},
  796. {'id': 2, 'name': 'bob'},
  797. {'id': 3, 'name': 'peter'}]
  798. >>> {name: list(ppp) for name, ppp in groupby(people, key=lambda p: p['name'])}
  799. {'bob': [{'id': 1, 'name': 'bob'},
  800. {'id': 2, 'name': 'bob'}],
  801. 'peter': [{'id': 3, 'name': 'peter'}]}
  802. ```
  803. Introspection and Metaprograming
  804. --------------------------------
  805. **Inspecting code at runtime and code that generates code. You can:**
  806. * **Look at the attributes**
  807. * **Set new attributes**
  808. * **Create functions dynamically**
  809. * **Traverse the parent classes**
  810. * **Change values in the class**
  811. ### Variables
  812. ```python
  813. <list> = dir() # In-scope variables.
  814. <dict> = locals() # Local variables.
  815. <dict> = globals() # Global variables.
  816. ```
  817. ### Attributes
  818. ```python
  819. >>> class Z:
  820. ... def __init__(self):
  821. ... self.a = 'abcde'
  822. ... self.b = 12345
  823. >>> z = Z()
  824. ```
  825. ```python
  826. >>> vars(z)
  827. {'a': 'abcde', 'b': 12345}
  828. >>> getattr(z, 'a')
  829. 'abcde'
  830. >>> hasattr(z, 'c')
  831. False
  832. >>> setattr(z, 'c', 10)
  833. ```
  834. ### Parameters
  835. #### Getting the number of parameters of a function:
  836. ```python
  837. from inspect import signature
  838. sig = signature(<function>)
  839. no_of_params = len(sig.parameters)
  840. ```
  841. ### Type
  842. **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!):**
  843. ```python
  844. type(<class_name>, <parents_tuple>, <attributes_dict>)
  845. ```
  846. ```python
  847. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  848. >>> z = Z()
  849. ```
  850. ### MetaClass
  851. #### Class that creates class:
  852. ```python
  853. def my_meta_class(name, parents, attrs):
  854. ...
  855. return type(name, parents, attrs)
  856. ```
  857. #### Or:
  858. ```python
  859. class MyMetaClass(type):
  860. def __new__(klass, name, parents, attrs):
  861. ...
  862. return type.__new__(klass, name, parents, attrs)
  863. ```
  864. ### Metaclass Attribute
  865. **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:**
  866. ```python
  867. class BlaBla:
  868. __metaclass__ = Bla
  869. ```
  870. Operator
  871. --------
  872. ```python
  873. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  874. eq, ne, lt, le, gt, ge, \
  875. not_, and_, or_, xor, \
  876. itemgetter
  877. ```
  878. ```python
  879. from enum import Enum
  880. from functools import reduce
  881. product_of_elems = reduce(mul, <list>)
  882. sorted_by_second = sorted(<list>, key=itemgetter(1))
  883. sorted_by_both = sorted(<list>, key=itemgetter(0, 1))
  884. LogicOp = Enum('LogicOp', {'AND': (and_, ),
  885. 'OR' : (or_, )})
  886. ```
  887. Eval
  888. ----
  889. ### Basic
  890. ```python
  891. >>> from ast import literal_eval
  892. >>> literal_eval('1 + 1')
  893. 2
  894. >>> literal_eval('[1, 2, 3]')
  895. [1, 2, 3]
  896. ```
  897. ### Detailed
  898. ```python
  899. from ast import parse, Num, BinOp, UnaryOp, \
  900. Add, Sub, Mult, Div, Pow, BitXor, USub
  901. import operator as op
  902. operators = {Add: op.add,
  903. Sub: op.sub,
  904. Mult: op.mul,
  905. Div: op.truediv,
  906. Pow: op.pow,
  907. BitXor: op.xor,
  908. USub: op.neg}
  909. def evaluate(expression):
  910. root = parse(expression, mode='eval')
  911. return eval_node(root.body)
  912. def eval_node(node):
  913. type_ = type(node)
  914. if type_ == Num:
  915. return node.n
  916. if type_ not in [BinOp, UnaryOp]:
  917. raise TypeError(node)
  918. operator = operators[type(node.op)]
  919. if type_ == BinOp:
  920. left, right = eval_node(node.left), eval_node(node.right)
  921. return operator(left, right)
  922. elif type_ == UnaryOp:
  923. operand = eval_node(node.operand)
  924. return operator(operand)
  925. ```
  926. ```python
  927. >>> evaluate('2^6')
  928. 4
  929. >>> evaluate('2**6')
  930. 64
  931. >>> evaluate('1 + 2*3**(4^5) / (6 + -7)')
  932. -5.0
  933. ```
  934. Coroutine
  935. ---------
  936. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  937. * **Coroutines provide more powerful data routing possibilities than iterators.**
  938. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  939. ### Helper Decorator
  940. * **All coroutines must be "primed" by first calling .next()**
  941. * **Remembering to call .next() is easy to forget.**
  942. * **Solved by wrapping coroutines with a decorator:**
  943. ```python
  944. def coroutine(func):
  945. def start(*args, **kwargs):
  946. cr = func(*args, **kwargs)
  947. next(cr)
  948. return cr
  949. return start
  950. ```
  951. ### Pipeline Example
  952. ```python
  953. def reader(target):
  954. for i in range(10):
  955. target.send(i)
  956. target.close()
  957. @coroutine
  958. def adder(target):
  959. while True:
  960. item = (yield)
  961. target.send(item + 100)
  962. @coroutine
  963. def printer():
  964. while True:
  965. item = (yield)
  966. print(item)
  967. reader(adder(printer()))
  968. ```
  969. <br><br>
  970. Libraries
  971. =========
  972. Plot
  973. ----
  974. ```python
  975. # $ pip3 install matplotlib
  976. from matplotlib import pyplot
  977. pyplot.plot(<data_1> [, <data_2>, ...])
  978. pyplot.show()
  979. pyplot.savefig(<filename>, transparent=True)
  980. ```
  981. Table
  982. -----
  983. #### Prints CSV file as ASCII table:
  984. ```python
  985. # $ pip3 install tabulate
  986. import csv
  987. from tabulate import tabulate
  988. with open(<filename>, newline='') as csv_file:
  989. reader = csv.reader(csv_file, delimiter=';')
  990. headers = [a.title() for a in next(reader)]
  991. print(tabulate(reader, headers))
  992. ```
  993. Curses
  994. ------
  995. ```python
  996. # $ pip3 install curses
  997. from curses import wrapper
  998. def main():
  999. wrapper(draw)
  1000. def draw(screen):
  1001. screen.clear()
  1002. screen.addstr(0, 0, 'Press ESC to quit.')
  1003. while screen.getch() != 27:
  1004. pass
  1005. def get_border(screen):
  1006. from collections import namedtuple
  1007. P = namedtuple('P', 'x y')
  1008. height, width = screen.getmaxyx()
  1009. return P(width - 1, height - 1)
  1010. ```
  1011. Image
  1012. -----
  1013. #### Creates PNG image of greyscale gradient:
  1014. ```python
  1015. # $ pip3 install pillow
  1016. from PIL import Image
  1017. width, height = 100, 100
  1018. img = Image.new('L', (width, height), 'white')
  1019. img.putdata([255*a/(width*height) for a in range(width*height)])
  1020. img.save('out.png')
  1021. ```
  1022. ### Modes
  1023. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1024. * `'L'` - 8-bit pixels, greyscale.
  1025. * `'RGB'` - 3x8-bit pixels, true color.
  1026. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1027. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1028. Audio
  1029. -----
  1030. #### Saves list of floats with values between 0 and 1 to a WAV file:
  1031. ```python
  1032. import wave, struct
  1033. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1034. wf = wave.open(<filename>, 'wb')
  1035. wf.setnchannels(1)
  1036. wf.setsampwidth(4)
  1037. wf.setframerate(44100)
  1038. wf.writeframes(b''.join(frames))
  1039. wf.close()
  1040. ```
  1041. Url
  1042. ---
  1043. ```python
  1044. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1045. ```
  1046. ### Encode
  1047. ```python
  1048. >>> quote("Can't be in URL!")
  1049. 'Can%27t%20be%20in%20URL%21'
  1050. >>> quote_plus("Can't be in URL!")
  1051. 'Can%27t+be+in+URL%21'
  1052. ```
  1053. ### Decode
  1054. ```python
  1055. >>> unquote('Can%27t+be+in+URL%21')
  1056. "Can't+be+in+URL!"'
  1057. >>> unquote_plus('Can%27t+be+in+URL%21')
  1058. "Can't be in URL!"
  1059. ```
  1060. Web
  1061. ---
  1062. ```python
  1063. # $ pip3 install bottle
  1064. import bottle
  1065. from urllib.parse import unquote
  1066. ```
  1067. ### Run
  1068. ```python
  1069. bottle.run(host='localhost', port=8080)
  1070. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1071. ```
  1072. ### Static request
  1073. ```python
  1074. @route('/img/<image>')
  1075. def send_image(image):
  1076. return static_file(image, 'images/', mimetype='image/png')
  1077. ```
  1078. ### Dynamic request
  1079. ```python
  1080. @route('/<sport>')
  1081. def send_page(sport):
  1082. sport = unquote(sport).lower()
  1083. page = read_file(sport)
  1084. return template(page)
  1085. ```
  1086. ### REST request
  1087. ```python
  1088. @post('/odds/<sport>')
  1089. def odds_handler(sport):
  1090. team = bottle.request.forms.get('team')
  1091. team = unquote(team).lower()
  1092. db = sqlite3.connect(<db_path>)
  1093. home_odds, away_odds = get_odds(db, sport, team)
  1094. db.close()
  1095. response.headers['Content-Type'] = 'application/json'
  1096. response.headers['Cache-Control'] = 'no-cache'
  1097. return json.dumps([home_odds, away_odds])
  1098. ```
  1099. Profile
  1100. -------
  1101. #### Basic:
  1102. ```python
  1103. from time import time
  1104. start_time = time()
  1105. ...
  1106. duration = time() - start_time
  1107. ```
  1108. #### Times execution of the passed code:
  1109. ```python
  1110. from timeit import timeit
  1111. timeit('"-".join(str(n) for n in range(100))',
  1112. number=10000, globals=globals())
  1113. ```
  1114. #### Generates a PNG image of call graph and highlights the bottlenecks:
  1115. ```python
  1116. # $ pip3 install pycallgraph
  1117. import pycallgraph
  1118. graph = pycallgraph.output.GraphvizOutput()
  1119. graph.output_file = get_filename()
  1120. with pycallgraph.PyCallGraph(output=graph):
  1121. <code_to_be_profiled>
  1122. ```
  1123. ```python
  1124. def get_filename():
  1125. from datetime import datetime
  1126. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1127. return f'profile-{time_str}.png'
  1128. ```
  1129. Progress Bar
  1130. ------------
  1131. ### Tqdm
  1132. ```python
  1133. # $ pip3 install tqdm
  1134. from tqdm import tqdm
  1135. from time import sleep
  1136. for i in tqdm(range(100)):
  1137. sleep(0.02)
  1138. for i in tqdm([1, 2, 3]):
  1139. sleep(0.2)
  1140. ```
  1141. ### Basic
  1142. ```python
  1143. import sys
  1144. class Bar():
  1145. @staticmethod
  1146. def range(*args):
  1147. bar = Bar(len(list(range(*args))))
  1148. for i in range(*args):
  1149. yield i
  1150. bar.tick()
  1151. @staticmethod
  1152. def foreach(elements):
  1153. bar = Bar(len(elements))
  1154. for el in elements:
  1155. yield el
  1156. bar.tick()
  1157. def __init__(s, steps, width=40):
  1158. s.st, s.wi, s.fl, s.i = steps, width, 0, 0
  1159. s.th = s.fl * s.st / s.wi
  1160. s.p(f"[{' ' * s.wi}]")
  1161. s.p('\b' * (s.wi + 1))
  1162. def tick(s):
  1163. s.i += 1
  1164. while s.i > s.th:
  1165. s.fl += 1
  1166. s.th = s.fl * s.st / s.wi
  1167. s.p('-')
  1168. if s.i == s.st:
  1169. s.p('\n')
  1170. def p(s, t):
  1171. sys.stdout.write(t)
  1172. sys.stdout.flush()
  1173. ```
  1174. #### Usage:
  1175. ```python
  1176. from time import sleep
  1177. for i in Bar.range(100):
  1178. sleep(0.02)
  1179. for el in Bar.foreach([1, 2, 3]):
  1180. sleep(0.2)
  1181. ```
  1182. Basic Script Template
  1183. ---------------------
  1184. ```python
  1185. #!/usr/bin/env python3
  1186. #
  1187. # Usage: .py
  1188. #
  1189. from collections import namedtuple
  1190. from enum import Enum
  1191. import re
  1192. import sys
  1193. def main():
  1194. pass
  1195. ###
  1196. ## UTIL
  1197. #
  1198. def read_file(filename):
  1199. with open(filename, encoding='utf-8') as file:
  1200. return file.readlines()
  1201. if __name__ == '__main__':
  1202. main()
  1203. ```