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.

1335 lines
27 KiB

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