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.

1363 lines
28 KiB

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