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.

1146 lines
22 KiB

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