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.

1503 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
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
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
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
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 sum, x: sum+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. partial(<function>, <arg_1> [, <arg_2>, ...])
  445. ```
  446. Decorator
  447. ---------
  448. ```python
  449. @closure_name
  450. def function_that_gets_passed_to_closure():
  451. ...
  452. ```
  453. #### Debugger example:
  454. ```python
  455. from functools import wraps
  456. def debug(func):
  457. @wraps(func) # Needed for metadata copying (func name, ...).
  458. def out(*args, **kwargs):
  459. print(func.__name__)
  460. return func(*args, **kwargs)
  461. return out
  462. @debug
  463. def add(x, y):
  464. return x + y
  465. ```
  466. Class
  467. -----
  468. ```python
  469. class <name>:
  470. def __init__(self, a):
  471. self.a = a
  472. def __str__(self):
  473. return str(self.a)
  474. def __repr__(self):
  475. return str({'a': self.a}) # Or: return f'{self.__dict__}'
  476. @classmethod
  477. def get_class_name(cls):
  478. return cls.__name__
  479. ```
  480. ### Constructor Overloading
  481. ```python
  482. class <name>:
  483. def __init__(self, a=None):
  484. self.a = a
  485. ```
  486. ### Copy
  487. ```python
  488. from copy import copy, deepcopy
  489. <object> = copy(<object>)
  490. <object> = deepcopy(<object>)
  491. ```
  492. Enum
  493. ----
  494. ```python
  495. from enum import Enum, auto
  496. class <enum_name>(Enum):
  497. <member_name_1> = <value_1>
  498. <member_name_2> = <value_2_a>, <value_2_b>
  499. <member_name_3> = auto() # Can be used for automatic indexing.
  500. ...
  501. @classmethod
  502. def get_names(cls):
  503. return [a.name for a in cls.__members__.values()]
  504. @classmethod
  505. def get_values(cls):
  506. return [a.value for a in cls.__members__.values()]
  507. ```
  508. ```python
  509. <member> = <enum>.<member_name>
  510. <member> = <enum>['<member_name>']
  511. <member> = <enum>(<value>)
  512. <name> = <member>.name
  513. <value> = <member>.value
  514. ```
  515. ```python
  516. list_of_members = list(<enum>)
  517. member_names = [a.name for a in <enum>]
  518. random_member = random.choice(list(<enum>))
  519. ```
  520. ### Inline
  521. ```python
  522. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  523. Cutlery = Enum('Cutlery', 'knife fork spoon')
  524. Cutlery = Enum('Cutlery', {'knife': 1, 'fork': 2, 'spoon': 3})
  525. # Functions can not be values, so they must be enclosed in tuple:
  526. LogicOp = Enum('LogicOp', {'AND': (lambda l, r: l and r, ),
  527. 'OR' : (lambda l, r: l or r, )})
  528. # But 'list(<enum>)' will only work if there is another value in the tuple:
  529. LogicOp = Enum('LogicOp', {'AND': (auto(), lambda l, r: l and r),
  530. 'OR' : (auto(), lambda l, r: l or r)})
  531. ```
  532. System
  533. ------
  534. ### Arguments
  535. ```python
  536. import sys
  537. script_name = sys.argv[0]
  538. arguments = sys.argv[1:]
  539. ```
  540. ### Read File
  541. ```python
  542. def read_file(filename):
  543. with open(filename, encoding='utf-8') as file:
  544. return file.readlines()
  545. ```
  546. ### Write to File
  547. ```python
  548. def write_to_file(filename, text):
  549. with open(filename, 'w', encoding='utf-8') as file:
  550. file.write(text)
  551. ```
  552. ### Path
  553. ```python
  554. import os
  555. <bool> = os.path.exists(<path>)
  556. <bool> = os.path.isfile(<path>)
  557. <bool> = os.path.isdir(<path>)
  558. <list> = os.listdir(<path>)
  559. ```
  560. ### Execute Command
  561. ```python
  562. import os
  563. <str> = os.popen(<command>).read()
  564. ```
  565. #### Or:
  566. ```python
  567. >>> import subprocess
  568. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  569. >>> a.stdout
  570. b'.\n..\nfile1.txt\nfile2.txt\n'
  571. >>> a.returncode
  572. 0
  573. ```
  574. ### Input
  575. ```python
  576. filename = input('Enter a file name: ')
  577. ```
  578. #### Prints lines until EOF:
  579. ```python
  580. while True:
  581. try:
  582. print(input())
  583. except EOFError:
  584. break
  585. ```
  586. ### Recursion Limit
  587. ```python
  588. >>> sys.getrecursionlimit()
  589. 1000
  590. >>> sys.setrecursionlimit(10000)
  591. ```
  592. JSON
  593. ----
  594. ```python
  595. import json
  596. ```
  597. ### Serialization
  598. ```python
  599. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  600. <dict> = json.loads(<str>)
  601. ```
  602. #### To preserve order:
  603. ```python
  604. from collections import OrderedDict
  605. <dict> = json.loads(<str>, object_pairs_hook=OrderedDict)
  606. ```
  607. ### Read File
  608. ```python
  609. def read_json_file(filename):
  610. with open(filename, encoding='utf-8') as file:
  611. return json.load(file)
  612. ```
  613. ### Write to File
  614. ```python
  615. def write_to_json_file(filename, an_object):
  616. with open(filename, 'w', encoding='utf-8') as file:
  617. json.dump(an_object, file, ensure_ascii=False, indent=2)
  618. ```
  619. SQLite
  620. ------
  621. ```python
  622. import sqlite3
  623. db = sqlite3.connect(<filename>)
  624. ```
  625. ### Read
  626. ```python
  627. cursor = db.execute(<query>)
  628. if cursor:
  629. cursor.fetchall() # Or cursor.fetchone()
  630. db.close()
  631. ```
  632. ### Write
  633. ```python
  634. db.execute(<query>)
  635. db.commit()
  636. ```
  637. Pickle
  638. ------
  639. ```python
  640. import pickle
  641. favorite_color = {'lion': 'yellow', 'kitty': 'red'}
  642. pickle.dump(favorite_color, open('data.p', 'wb'))
  643. favorite_color = pickle.load(open('data.p', 'rb'))
  644. ```
  645. Exceptions
  646. ----------
  647. ```python
  648. while True:
  649. try:
  650. x = int(input('Please enter a number: '))
  651. except ValueError:
  652. print('Oops! That was no valid number. Try again...')
  653. else:
  654. print('Thank you.')
  655. break
  656. ```
  657. #### Raising exception:
  658. ```python
  659. raise ValueError('A very specific message!')
  660. ```
  661. #### Finally:
  662. ```python
  663. >>> try:
  664. ... raise KeyboardInterrupt
  665. ... finally:
  666. ... print('Goodbye, world!')
  667. ...
  668. Goodbye, world!
  669. Traceback (most recent call last):
  670. File "<stdin>", line 2, in <module>
  671. KeyboardInterrupt
  672. ```
  673. Bytes
  674. -----
  675. **Bytes objects are immutable sequences of single bytes.**
  676. ### Encode
  677. ```python
  678. <Bytes> = b'<str>'
  679. <Bytes> = <str>.encode(encoding='utf-8')
  680. <Bytes> = <int>.to_bytes(<length>, byteorder='big|little', signed=False)
  681. <Bytes> = bytes.fromhex(<hex>)
  682. ```
  683. ### Decode
  684. ```python
  685. <str> = <Bytes>.decode('utf-8')
  686. <int> = int.from_bytes(<Bytes>, byteorder='big|little', signed=False)
  687. <hex> = <Bytes>.hex()
  688. ```
  689. ### Read Bytes from File
  690. ```python
  691. def read_bytes(filename):
  692. with open(filename, 'rb') as file:
  693. return file.read()
  694. ```
  695. ### Write Bytes to File
  696. ```python
  697. def write_bytes(filename, bytes):
  698. with open(filename, 'wb') as file:
  699. file.write(bytes)
  700. ```
  701. ```python
  702. <Bytes> = b''.join(<list_of_Bytes>)
  703. ```
  704. Struct
  705. ------
  706. **This module performs conversions between Python values and C struct represented as Python Bytes object.**
  707. ```python
  708. <Bytes> = struct.pack('<format>', <value_1> [, <value_2>, ...])
  709. <tuple> = struct.unpack('<format>', <Bytes>)
  710. ```
  711. ### Example
  712. ```python
  713. >>> from struct import pack, unpack, calcsize
  714. >>> pack('hhl', 1, 2, 3)
  715. b'\x00\x01\x00\x02\x00\x00\x00\x03'
  716. >>> unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
  717. (1, 2, 3)
  718. >>> calcsize('hhl')
  719. 8
  720. ```
  721. ### Format
  722. **Use capital leters for unsigned type.**
  723. * `'x'` - pad byte
  724. * `'c'` - char
  725. * `'h'` - short
  726. * `'i'` - int
  727. * `'l'` - long
  728. * `'q'` - long long
  729. * `'f'` - float
  730. * `'d'` - double
  731. Hashlib
  732. -------
  733. ```python
  734. >>> hashlib.md5(<str>.encode()).hexdigest()
  735. '33d0eba106da4d3ebca17fcd3f4c3d77'
  736. ```
  737. Threading
  738. ---------
  739. ```python
  740. from threading import Thread, RLock
  741. ```
  742. ### Thread
  743. ```python
  744. thread = Thread(target=<function>, args=(<first_arg>, ))
  745. thread.start()
  746. ...
  747. thread.join()
  748. ```
  749. ### Lock
  750. ```python
  751. lock = Rlock()
  752. lock.acquire()
  753. ...
  754. lock.release()
  755. ```
  756. Itertools
  757. ---------
  758. **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.**
  759. ```python
  760. from itertools import *
  761. ```
  762. ### Combinatoric iterators
  763. ```python
  764. >>> combinations('abc', 2)
  765. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  766. >>> combinations_with_replacement('abc', 2)
  767. [('a', 'a'), ('a', 'b'), ('a', 'c'),
  768. ('b', 'b'), ('b', 'c'), ('c', 'c')]
  769. >>> permutations('abc', 2)
  770. [('a', 'b'), ('a', 'c'),
  771. ('b', 'a'), ('b', 'c'),
  772. ('c', 'a'), ('c', 'b')]
  773. >>> product('ab', [1, 2])
  774. [('a', 1), ('a', 2),
  775. ('b', 1), ('b', 2)]
  776. >>> product([0, 1], repeat=3)
  777. [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
  778. (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
  779. ```
  780. ### Infinite iterators
  781. ```python
  782. >>> i = count(5, 2)
  783. >>> next(i), next(i), next(i)
  784. (5, 7, 9)
  785. >>> a = cycle('abc')
  786. >>> [next(a) for _ in range(10)]
  787. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  788. >>> repeat(10, 3)
  789. [10, 10, 10]
  790. ```
  791. ### Iterators
  792. ```python
  793. >>> chain([1, 2], range(3, 5))
  794. [1, 2, 3, 4]
  795. >>> compress('abc', [True, 0, 1])
  796. ['a', 'c']
  797. >>> islice([1, 2, 3], 1, None) # islice(<seq>, from_inclusive, to_exclusive)
  798. [2, 3]
  799. >>> people = [{'id': 1, 'name': 'bob'},
  800. {'id': 2, 'name': 'bob'},
  801. {'id': 3, 'name': 'peter'}]
  802. >>> {name: list(ppp) for name, ppp in groupby(people, key=lambda p: p['name'])}
  803. {'bob': [{'id': 1, 'name': 'bob'},
  804. {'id': 2, 'name': 'bob'}],
  805. 'peter': [{'id': 3, 'name': 'peter'}]}
  806. ```
  807. Introspection and Metaprograming
  808. --------------------------------
  809. **Inspecting code at runtime and code that generates code. You can:**
  810. * **Look at the attributes**
  811. * **Set new attributes**
  812. * **Create functions dynamically**
  813. * **Traverse the parent classes**
  814. * **Change values in the class**
  815. ### Variables
  816. ```python
  817. <list> = dir() # In-scope variables.
  818. <dict> = locals() # Local variables.
  819. <dict> = globals() # Global variables.
  820. ```
  821. ### Attributes
  822. ```python
  823. >>> class Z:
  824. ... def __init__(self):
  825. ... self.a = 'abcde'
  826. ... self.b = 12345
  827. >>> z = Z()
  828. ```
  829. ```python
  830. >>> vars(z)
  831. {'a': 'abcde', 'b': 12345}
  832. >>> getattr(z, 'a')
  833. 'abcde'
  834. >>> hasattr(z, 'c')
  835. False
  836. >>> setattr(z, 'c', 10)
  837. ```
  838. ### Parameters
  839. #### Getting the number of parameters of a function:
  840. ```python
  841. from inspect import signature
  842. sig = signature(<function>)
  843. no_of_params = len(sig.parameters)
  844. ```
  845. ### Type
  846. **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!):**
  847. ```python
  848. type(<class_name>, <parents_tuple>, <attributes_dict>)
  849. ```
  850. ```python
  851. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  852. >>> z = Z()
  853. ```
  854. ### MetaClass
  855. #### Class that creates class:
  856. ```python
  857. def my_meta_class(name, parents, attrs):
  858. ...
  859. return type(name, parents, attrs)
  860. ```
  861. #### Or:
  862. ```python
  863. class MyMetaClass(type):
  864. def __new__(klass, name, parents, attrs):
  865. ...
  866. return type.__new__(klass, name, parents, attrs)
  867. ```
  868. ### Metaclass Attribute
  869. **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:**
  870. ```python
  871. class BlaBla:
  872. __metaclass__ = Bla
  873. ```
  874. Operator
  875. --------
  876. ```python
  877. from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \
  878. eq, ne, lt, le, gt, ge, \
  879. not_, and_, or_, xor, \
  880. itemgetter
  881. ```
  882. ```python
  883. from enum import Enum
  884. from functools import reduce
  885. product_of_elems = reduce(mul, <list>)
  886. sorted_by_second = sorted(<list>, key=itemgetter(1))
  887. sorted_by_both = sorted(<list>, key=itemgetter(0, 1))
  888. LogicOp = Enum('LogicOp', {'AND': (and_, ),
  889. 'OR' : (or_, )})
  890. ```
  891. Eval
  892. ----
  893. ### Basic
  894. ```python
  895. >>> from ast import literal_eval
  896. >>> literal_eval('1 + 1')
  897. 2
  898. >>> literal_eval('[1, 2, 3]')
  899. [1, 2, 3]
  900. ```
  901. ### Detailed
  902. ```python
  903. from ast import parse, Num, BinOp, UnaryOp, \
  904. Add, Sub, Mult, Div, Pow, BitXor, USub
  905. import operator as op
  906. operators = {Add: op.add,
  907. Sub: op.sub,
  908. Mult: op.mul,
  909. Div: op.truediv,
  910. Pow: op.pow,
  911. BitXor: op.xor,
  912. USub: op.neg}
  913. def evaluate(expression):
  914. root = parse(expression, mode='eval')
  915. return eval_node(root.body)
  916. def eval_node(node):
  917. type_ = type(node)
  918. if type_ == Num:
  919. return node.n
  920. if type_ not in [BinOp, UnaryOp]:
  921. raise TypeError(node)
  922. operator = operators[type(node.op)]
  923. if type_ == BinOp:
  924. left, right = eval_node(node.left), eval_node(node.right)
  925. return operator(left, right)
  926. elif type_ == UnaryOp:
  927. operand = eval_node(node.operand)
  928. return operator(operand)
  929. ```
  930. ```python
  931. >>> evaluate('2^6')
  932. 4
  933. >>> evaluate('2**6')
  934. 64
  935. >>> evaluate('1 + 2*3**(4^5) / (6 + -7)')
  936. -5.0
  937. ```
  938. Coroutine
  939. ---------
  940. * **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().**
  941. * **Coroutines provide more powerful data routing possibilities than iterators.**
  942. * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.**
  943. ### Helper Decorator
  944. * **All coroutines must be "primed" by first calling next().**
  945. * **Remembering to call next() is easy to forget.**
  946. * **Solved by wrapping coroutines with a decorator:**
  947. ```python
  948. def coroutine(func):
  949. def out(*args, **kwargs):
  950. cr = func(*args, **kwargs)
  951. next(cr)
  952. return cr
  953. return out
  954. ```
  955. ### Pipeline Example
  956. ```python
  957. def reader(target):
  958. for i in range(10):
  959. target.send(i)
  960. target.close()
  961. @coroutine
  962. def adder(target):
  963. while True:
  964. item = (yield)
  965. target.send(item + 100)
  966. @coroutine
  967. def printer():
  968. while True:
  969. item = (yield)
  970. print(item)
  971. reader(adder(printer()))
  972. ```
  973. <br><br>
  974. Libraries
  975. =========
  976. Plot
  977. ----
  978. ```python
  979. # $ pip3 install matplotlib
  980. from matplotlib import pyplot
  981. pyplot.plot(<data_1> [, <data_2>, ...])
  982. pyplot.show()
  983. pyplot.savefig(<filename>, transparent=True)
  984. ```
  985. Table
  986. -----
  987. #### Prints CSV file as ASCII table:
  988. ```python
  989. # $ pip3 install tabulate
  990. import csv
  991. from tabulate import tabulate
  992. with open(<filename>, newline='') as csv_file:
  993. reader = csv.reader(csv_file, delimiter=';')
  994. headers = [a.title() for a in next(reader)]
  995. print(tabulate(reader, headers))
  996. ```
  997. Curses
  998. ------
  999. ```python
  1000. # $ pip3 install curses
  1001. from curses import wrapper
  1002. def main():
  1003. wrapper(draw)
  1004. def draw(screen):
  1005. screen.clear()
  1006. screen.addstr(0, 0, 'Press ESC to quit.')
  1007. while screen.getch() != 27:
  1008. pass
  1009. def get_border(screen):
  1010. from collections import namedtuple
  1011. P = namedtuple('P', 'x y')
  1012. height, width = screen.getmaxyx()
  1013. return P(width - 1, height - 1)
  1014. ```
  1015. Image
  1016. -----
  1017. #### Creates PNG image of greyscale gradient:
  1018. ```python
  1019. # $ pip3 install pillow
  1020. from PIL import Image
  1021. width, height = 100, 100
  1022. img = Image.new('L', (width, height), 'white')
  1023. img.putdata([255*a/(width*height) for a in range(width*height)])
  1024. img.save('out.png')
  1025. ```
  1026. ### Modes
  1027. * `'1'` - 1-bit pixels, black and white, stored with one pixel per byte.
  1028. * `'L'` - 8-bit pixels, greyscale.
  1029. * `'RGB'` - 3x8-bit pixels, true color.
  1030. * `'RGBA'` - 4x8-bit pixels, true color with transparency mask.
  1031. * `'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.
  1032. Audio
  1033. -----
  1034. #### Saves list of floats with values between 0 and 1 to a WAV file:
  1035. ```python
  1036. import wave, struct
  1037. frames = [struct.pack('h', int((a-0.5)*60000)) for a in <list>]
  1038. wf = wave.open(<filename>, 'wb')
  1039. wf.setnchannels(1)
  1040. wf.setsampwidth(4)
  1041. wf.setframerate(44100)
  1042. wf.writeframes(b''.join(frames))
  1043. wf.close()
  1044. ```
  1045. Url
  1046. ---
  1047. ```python
  1048. from urllib.parse import quote, quote_plus, unquote, unquote_plus
  1049. ```
  1050. ### Encode
  1051. ```python
  1052. >>> quote("Can't be in URL!")
  1053. 'Can%27t%20be%20in%20URL%21'
  1054. >>> quote_plus("Can't be in URL!")
  1055. 'Can%27t+be+in+URL%21'
  1056. ```
  1057. ### Decode
  1058. ```python
  1059. >>> unquote('Can%27t+be+in+URL%21')
  1060. "Can't+be+in+URL!"'
  1061. >>> unquote_plus('Can%27t+be+in+URL%21')
  1062. "Can't be in URL!"
  1063. ```
  1064. Web
  1065. ---
  1066. ```python
  1067. # $ pip3 install bottle
  1068. import bottle
  1069. from urllib.parse import unquote
  1070. ```
  1071. ### Run
  1072. ```python
  1073. bottle.run(host='localhost', port=8080)
  1074. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  1075. ```
  1076. ### Static request
  1077. ```python
  1078. @route('/img/<image>')
  1079. def send_image(image):
  1080. return static_file(image, 'images/', mimetype='image/png')
  1081. ```
  1082. ### Dynamic request
  1083. ```python
  1084. @route('/<sport>')
  1085. def send_page(sport):
  1086. sport = unquote(sport).lower()
  1087. page = read_file(sport)
  1088. return template(page)
  1089. ```
  1090. ### REST request
  1091. ```python
  1092. @post('/odds/<sport>')
  1093. def odds_handler(sport):
  1094. team = bottle.request.forms.get('team')
  1095. team = unquote(team).lower()
  1096. db = sqlite3.connect(<db_path>)
  1097. home_odds, away_odds = get_odds(db, sport, team)
  1098. db.close()
  1099. response.headers['Content-Type'] = 'application/json'
  1100. response.headers['Cache-Control'] = 'no-cache'
  1101. return json.dumps([home_odds, away_odds])
  1102. ```
  1103. Profile
  1104. -------
  1105. #### Basic:
  1106. ```python
  1107. from time import time
  1108. start_time = time()
  1109. ...
  1110. duration = time() - start_time
  1111. ```
  1112. #### Times execution of the passed code:
  1113. ```python
  1114. from timeit import timeit
  1115. timeit('"-".join(str(a) for a in range(100))',
  1116. number=10000, globals=globals())
  1117. ```
  1118. #### Generates a PNG image of call graph and highlights the bottlenecks:
  1119. ```python
  1120. # $ pip3 install pycallgraph
  1121. import pycallgraph
  1122. graph = pycallgraph.output.GraphvizOutput()
  1123. graph.output_file = get_filename()
  1124. with pycallgraph.PyCallGraph(output=graph):
  1125. <code_to_be_profiled>
  1126. ```
  1127. ```python
  1128. def get_filename():
  1129. from datetime import datetime
  1130. time_str = datetime.now().strftime('%Y%m%d%H%M%S')
  1131. return f'profile-{time_str}.png'
  1132. ```
  1133. #### Decorator for timing functions:
  1134. ```python
  1135. from timeit import default_timer
  1136. from datetime import timedelta
  1137. def stopwatch(func):
  1138. """Prints runtime of decorated function."""
  1139. def out(*args, **kwargs):
  1140. start = default_timer()
  1141. result = func(*args, **kwargs)
  1142. delta = timedelta(seconds=(default_timer() - start))
  1143. print(f'Function {func.__name__} finished in {delta}')
  1144. return result
  1145. return out
  1146. ```
  1147. #### Decorator for profiling functions:
  1148. ```python
  1149. from cProfile import Profile
  1150. from pstats import Stats
  1151. def profiler(func):
  1152. """Saves run call profile of the decorated function to file."""
  1153. def out(*args, **kwargs):
  1154. profile = Profile()
  1155. result = profile.runcall(func, *args, **kwargs)
  1156. filename = f'profile_{func.__name__}.txt'
  1157. with open(filename, 'w') as stream:
  1158. stats = Stats(profile, stream=stream)
  1159. stats.strip_dirs().sort_stats('tottime')
  1160. stats.print_stats(20)
  1161. print(f"Profile saved as '{filename}'")
  1162. return result
  1163. return out
  1164. ```
  1165. #### Decorator for function tracing:
  1166. ```python
  1167. def tracer(func):
  1168. """Prints arguments and output of a decorated function."""
  1169. def out(*args, **kwargs):
  1170. result = func(*args, **kwargs)
  1171. arg_list = [repr(x) for x in args]
  1172. arg_list += [f'{k}={v!r}' for k, v in kwargs.items()]
  1173. arg_str = ', '.join(arg_list)
  1174. print(f'{func.__name__}({arg_str}) = {result!r}')
  1175. return result
  1176. return out
  1177. ```
  1178. Progress Bar
  1179. ------------
  1180. ### Tqdm
  1181. ```python
  1182. # $ pip3 install tqdm
  1183. from tqdm import tqdm
  1184. from time import sleep
  1185. for i in tqdm(range(100)):
  1186. sleep(0.02)
  1187. for i in tqdm([1, 2, 3]):
  1188. sleep(0.2)
  1189. ```
  1190. ### Basic
  1191. ```python
  1192. import sys
  1193. class Bar():
  1194. @staticmethod
  1195. def range(*args):
  1196. bar = Bar(len(list(range(*args))))
  1197. for i in range(*args):
  1198. yield i
  1199. bar.tick()
  1200. @staticmethod
  1201. def foreach(elements):
  1202. bar = Bar(len(elements))
  1203. for el in elements:
  1204. yield el
  1205. bar.tick()
  1206. def __init__(s, steps, width=40):
  1207. s.st, s.wi, s.fl, s.i = steps, width, 0, 0
  1208. s.th = s.fl * s.st / s.wi
  1209. s.p(f"[{' ' * s.wi}]")
  1210. s.p('\b' * (s.wi + 1))
  1211. def tick(s):
  1212. s.i += 1
  1213. while s.i > s.th:
  1214. s.fl += 1
  1215. s.th = s.fl * s.st / s.wi
  1216. s.p('-')
  1217. if s.i == s.st:
  1218. s.p('\n')
  1219. def p(s, t):
  1220. sys.stdout.write(t)
  1221. sys.stdout.flush()
  1222. ```
  1223. #### Usage:
  1224. ```python
  1225. from time import sleep
  1226. for i in Bar.range(100):
  1227. sleep(0.02)
  1228. for el in Bar.foreach([1, 2, 3]):
  1229. sleep(0.2)
  1230. ```
  1231. Basic Script Template
  1232. ---------------------
  1233. ```python
  1234. #!/usr/bin/env python3
  1235. #
  1236. # Usage: .py
  1237. #
  1238. from collections import namedtuple
  1239. from enum import Enum
  1240. import re
  1241. import sys
  1242. def main():
  1243. pass
  1244. ###
  1245. ## UTIL
  1246. #
  1247. def read_file(filename):
  1248. with open(filename, encoding='utf-8') as file:
  1249. return file.readlines()
  1250. if __name__ == '__main__':
  1251. main()
  1252. ```