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.

1355 lines
27 KiB

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