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.

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