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.

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