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.

1384 lines
28 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
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
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
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
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
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
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
7 years ago
6 years ago
7 years ago
7 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
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
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
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
6 years ago
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 = [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 breakes 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 string.
  213. <Match_iter> = re.finditer(<regex>, text) # Searches for all occurences 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. # Warrning: Objects will share the objects that are initialized in the dict!
  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 structs represented as Python Bytes objects:**
  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'), ('b', 'b'), ('b', 'c'), ('c', 'c')]
  731. >>> permutations('abc', 2)
  732. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  733. >>> product('ab', [1, 2])
  734. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  735. >>> product([0, 1], repeat=3)
  736. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  737. ```
  738. ### Infinite iterators
  739. ```python
  740. >>> i = count(5, 2)
  741. >>> next(i), next(i), next(i)
  742. (5, 7, 9)
  743. >>> a = cycle('abc')
  744. >>> [next(a) for _ in range(10)]
  745. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  746. >>> repeat(10, 3)
  747. [10, 10, 10]
  748. ```
  749. ### Iterators
  750. ```python
  751. >>> chain([1, 2], range(3, 5))
  752. [1, 2, 3, 4]
  753. >>> compress('abc', [True, 0, 1])
  754. ['a', 'c']
  755. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  756. [2, 3]
  757. >>> people = [{'id': 1, 'name': 'bob'},
  758. {'id': 2, 'name': 'bob'},
  759. {'id': 3, 'name': 'peter'}]
  760. >>> {name: list(ppp) for name, ppp in groupby(people, key=lambda p: p['name'])}
  761. {'bob': [{'id': 1, 'name': 'bob'},
  762. {'id': 2, 'name': 'bob'}],
  763. 'peter': [{'id': 3, 'name': 'peter'}]}
  764. ```
  765. Introspection and Metaprograming
  766. --------------------------------
  767. **Inspecting code at runtime and code that generates code. You can:**
  768. * **Look at the attributes**
  769. * **Set new attributes**
  770. * **Create functions dynamically**
  771. * **Traverse the parent classes**
  772. * **Change values in the class**
  773. ### Variables
  774. ```python
  775. <list> = dir() # In-scope variables.
  776. <dict> = locals() # Local variables.
  777. <dict> = globals() # Global variables.
  778. ```
  779. ### Attributes
  780. ```python
  781. >>> class Z:
  782. ... def __init__(self):
  783. ... self.a = 'abcde'
  784. ... self.b = 12345
  785. >>> z = Z()
  786. ```
  787. ```python
  788. >>> getattr(z, 'a') # Same as Z.__getattribute__(z, 'a')
  789. 'abcde'
  790. >>> hasattr(z, 'c')
  791. False
  792. >>> setattr(z, 'c', 10)
  793. ```
  794. ### Parameters
  795. #### Getting the number of parameters of a function:
  796. ```python
  797. from inspect import signature
  798. sig = signature(<function>)
  799. no_of_params = len(sig.parameters)
  800. ```
  801. ### Type
  802. **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!):**
  803. ```python
  804. type(<class_name>, <parents_tuple>, <attributes_dict>)
  805. ```
  806. ```python
  807. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  808. >>> z = Z()
  809. ```
  810. ### MetaClass
  811. #### Class that creates class:
  812. ```python
  813. def my_meta_class(name, parents, attrs):
  814. ...
  815. return type(name, parents, attrs)
  816. ```
  817. #### Or:
  818. ```python
  819. class MyMetaClass(type):
  820. def __new__(klass, name, parents, attrs):
  821. ...
  822. return type.__new__(klass, name, parents, attrs)
  823. ```
  824. ### Metaclass Attribute
  825. **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:**
  826. ```python
  827. class BlaBla:
  828. __metaclass__ = Bla
  829. ```
  830. Eval
  831. ----
  832. ### Basic
  833. ```python
  834. >>> from ast import literal_eval
  835. >>> literal_eval('1 + 1')
  836. 2
  837. >>> literal_eval('[1, 2, 3]')
  838. [1, 2, 3]
  839. ```
  840. ### Detailed
  841. ```python
  842. from ast import parse, Num, BinOp, UnaryOp, \
  843. Add, Sub, Mult, Div, Pow, BitXor, USub
  844. import operator as op
  845. operators = {Add: op.add,
  846. Sub: op.sub,
  847. Mult: op.mul,
  848. Div: op.truediv,
  849. Pow: op.pow,
  850. BitXor: op.xor,
  851. USub: op.neg}
  852. def evaluate(expression):
  853. root = parse(expression, mode='eval')
  854. return eval_node(root.body)
  855. def eval_node(node):
  856. type_ = type(node)
  857. if type_ == Num:
  858. return node.n
  859. if type_ not in [BinOp, UnaryOp]:
  860. raise TypeError(node)
  861. operator = operators[type(node.op)]
  862. if type_ == BinOp:
  863. left, right = eval_node(node.left), eval_node(node.right)
  864. return operator(left, right)
  865. elif type_ == UnaryOp:
  866. operand = eval_node(node.operand)
  867. return operator(operand)
  868. ```
  869. ```python
  870. >>> evaluate('2^6')
  871. 4
  872. >>> evaluate('2**6')
  873. 64
  874. >>> evaluate('1 + 2*3**(4^5) / (6 + -7)')
  875. -5.0
  876. ```
  877. Coroutine
  878. ---------
  879. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  880. * **Coroutines provide more powerful data routing possibilities than iterators.**
  881. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  882. ### Helper Decorator
  883. * **All coroutines must be "primed" by first calling .next()**
  884. * **Remembering to call .next() is easy to forget.**
  885. * **Solved by wrapping coroutines with a decorator:**
  886. ```python
  887. def coroutine(func):
  888. def start(*args, **kwargs):
  889. cr = func(*args, **kwargs)
  890. next(cr)
  891. return cr
  892. return start
  893. ```
  894. ### Pipeline Example
  895. ```python
  896. def reader(target):
  897. for i in range(10):
  898. target.send(i)
  899. target.close()
  900. @coroutine
  901. def adder(target):
  902. while True:
  903. item = (yield)
  904. target.send(item + 100)
  905. @coroutine
  906. def printer():
  907. while True:
  908. item = (yield)
  909. print(item)
  910. reader(adder(printer()))
  911. ```
  912. <br><br>
  913. Libraries
  914. =========
  915. Plot
  916. ----
  917. ```python
  918. # $ pip3 install matplotlib
  919. from matplotlib import pyplot
  920. pyplot.plot(<data_1> [, <data_2>, ...])
  921. pyplot.show()
  922. pyplot.savefig(<filename>, transparent=True)
  923. ```
  924. Table
  925. -----
  926. #### Prints CSV file as ASCII table:
  927. ```python
  928. # $ pip3 install tabulate
  929. import csv
  930. from tabulate import tabulate
  931. with open(<filename>, newline='') as csv_file:
  932. reader = csv.reader(csv_file, delimiter=';')
  933. headers = [a.title() for a in next(reader)]
  934. print(tabulate(reader, headers))
  935. ```
  936. Curses
  937. ------
  938. ```python
  939. # $ pip3 install curses
  940. from curses import wrapper
  941. def main():
  942. wrapper(draw)
  943. def draw(screen):
  944. screen.clear()
  945. screen.addstr(0, 0, 'Press ESC to quit.')
  946. while screen.getch() != 27:
  947. pass
  948. def get_border(screen):
  949. from collections import namedtuple
  950. P = namedtuple('P', 'x y')
  951. height, width = screen.getmaxyx()
  952. return P(width - 1, height - 1)
  953. ```
  954. Image
  955. -----
  956. #### Creates PNG image of greyscale gradient:
  957. ```python
  958. # $ pip3 install pillow
  959. from PIL import Image
  960. width, height = 100, 100
  961. img = Image.new('L', (width, height), 'white')
  962. img.putdata([255*a/(width*height) for a in range(width*height)])
  963. img.save('out.png')
  964. ```
  965. ### Modes
  966. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  967. * `'L'` - 8-bit pixels, greyscale.
  968. * `'RGB'` - 3x8-bit pixels, true color.
  969. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  970. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  971. Audio
  972. -----
  973. #### Saves list of floats with values between 0 and 1 to a WAV file:
  974. ```python
  975. import wave, struct
  976. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  977. wf = wave.open(<filename>, 'wb')
  978. wf.setnchannels(1)
  979. wf.setsampwidth(4)
  980. wf.setframerate(44100)
  981. wf.writeframes(b''.join(frames))
  982. wf.close()
  983. ```
  984. Url
  985. ---
  986. ```python
  987. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  988. ```
  989. ### Encode
  990. ```python
  991. >>> quote("Can't be in URL!")
  992. 'Can%27t%20be%20in%20URL%21'
  993. >>> quote_plus("Can't be in URL!")
  994. 'Can%27t+be+in+URL%21'
  995. ```
  996. ### Decode
  997. ```python
  998. >>> unquote('Can%27t+be+in+URL%21')
  999. "Can't+be+in+URL!"'
  1000. >>> unquote_plus('Can%27t+be+in+URL%21')
  1001. "Can't be in URL!"
  1002. ```
  1003. Web
  1004. ---
  1005. ```python
  1006. # $ pip3 install bottle
  1007. import bottle
  1008. from urllib.parse import unquote
  1009. ```
  1010. ### Run
  1011. ```python
  1012. bottle.run(host='localhost', port=8080)
  1013. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1014. ```
  1015. ### Static request
  1016. ```python
  1017. @route('/img/<image>')
  1018. def send_image(image):
  1019. return static_file(image, 'images/', mimetype='image/png')
  1020. ```
  1021. ### Dynamic request
  1022. ```python
  1023. @route('/<sport>')
  1024. def send_page(sport):
  1025. sport = unquote(sport).lower()
  1026. page = read_file(sport)
  1027. return template(page)
  1028. ```
  1029. ### REST request
  1030. ```python
  1031. @post('/odds/<sport>')
  1032. def odds_handler(sport):
  1033. team = bottle.request.forms.get('team')
  1034. team = unquote(team).lower()
  1035. db = sqlite3.connect(<db_path>)
  1036. home_odds, away_odds = get_odds(db, sport, team)
  1037. db.close()
  1038. response.headers['Content-Type'] = 'application/json'
  1039. response.headers['Cache-Control'] = 'no-cache'
  1040. return json.dumps([home_odds, away_odds])
  1041. ```
  1042. Profile
  1043. -------
  1044. #### Basic:
  1045. ```python
  1046. from time import time
  1047. start_time = time()
  1048. ...
  1049. duration = time() - start_time
  1050. ```
  1051. #### Times execution of the passed code:
  1052. ```python
  1053. from timeit import timeit
  1054. timeit('"-".join(str(n) for n in range(100))', number=10000, globals=globals())
  1055. ```
  1056. #### Generates a PNG image of call graph and highlights the bottlenecks:
  1057. ```python
  1058. # $ pip3 install pycallgraph
  1059. import pycallgraph
  1060. graph = pycallgraph.output.GraphvizOutput()
  1061. graph.output_file = get_filename()
  1062. with pycallgraph.PyCallGraph(output=graph):
  1063. <code_to_be_profiled>
  1064. ```
  1065. ```python
  1066. def get_filename():
  1067. from datetime import datetime
  1068. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1069. return f'profile-{time_str}.png'
  1070. ```
  1071. Progress Bar
  1072. ------------
  1073. ### Basic:
  1074. ```python
  1075. import sys
  1076. class Bar():
  1077. @staticmethod
  1078. def range(*args):
  1079. bar = Bar(len(list(range(*args))))
  1080. for i in range(*args):
  1081. yield i
  1082. bar.tick()
  1083. @staticmethod
  1084. def foreach(elements):
  1085. bar = Bar(len(elements))
  1086. for el in elements:
  1087. yield el
  1088. bar.tick()
  1089. def __init__(s, steps, width=40):
  1090. s.st, s.wi, s.fl, s.i = steps, width, 0, 0
  1091. s.th = s.fl * s.st / s.wi
  1092. s.p(f"[{' ' * s.wi}]")
  1093. s.p('\b' * (s.wi + 1))
  1094. def tick(s):
  1095. s.i += 1
  1096. while s.i > s.th:
  1097. s.fl += 1
  1098. s.th = s.fl * s.st / s.wi
  1099. s.p('-')
  1100. if s.i == s.st:
  1101. s.p('\n')
  1102. def p(t):
  1103. sys.stdout.write(t)
  1104. sys.stdout.flush()
  1105. ```
  1106. #### Usage:
  1107. ```python
  1108. from time import sleep
  1109. # Range:
  1110. for i in Bar.range(100):
  1111. sleep(0.02)
  1112. # Foreach:
  1113. for el in Bar.foreach([1, 2, 3]):
  1114. sleep(0.02)
  1115. ```
  1116. ### Progress:
  1117. ```python
  1118. # $ pip3 install progress
  1119. from progress.bar import Bar
  1120. from time import sleep
  1121. STEPS = 100
  1122. bar = Bar('Processing', max=STEPS)
  1123. for i in range(STEPS):
  1124. sleep(0.02)
  1125. bar.next()
  1126. bar.finish()
  1127. ```
  1128. Basic Script Template
  1129. ---------------------
  1130. ```python
  1131. # Linux:
  1132. #!/usr/bin/env python3
  1133. # Mac:
  1134. #!/usr/local/bin/python3
  1135. #
  1136. # Usage: .py
  1137. #
  1138. from collections import namedtuple
  1139. from enum import Enum
  1140. import re
  1141. import sys
  1142. def main():
  1143. pass
  1144. ###
  1145. ## UTIL
  1146. #
  1147. def read_file(filename):
  1148. with open(filename, encoding='utf-8') as file:
  1149. return file.readlines()
  1150. if __name__ == '__main__':
  1151. main()
  1152. ```