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.

1555 lines
32 KiB

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