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.

1407 lines
28 KiB

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