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