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.

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