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.

1549 lines
32 KiB

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