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.

1381 lines
28 KiB

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