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.

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