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.

965 lines
18 KiB

6 years ago
7 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
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
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
7 years ago
6 years ago
7 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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. <list> = 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. dict(<list>) # Initiates a dict from list of key/value pairs.
  47. dict(zip(keys, values)) # Initiates a dict from two lists.
  48. {k: v for k, v in <dict>.items() if k in <list>} # Filters a dict by keys.
  49. ```
  50. ### Counter
  51. ```python
  52. >>> from collections import Counter
  53. >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  54. >>> Counter(z)
  55. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  56. ```
  57. Set
  58. ---
  59. ```python
  60. <set> = set()
  61. <set>.add(<el>)
  62. <set>.update(<set>)
  63. <set>.union(<set>)
  64. <set>.intersection(<set>)
  65. <set>.difference(<set>)
  66. <set>.issubset(<set>)
  67. <set>.issuperset(<set>)
  68. ```
  69. ### Frozenset
  70. #### Is hashable and can be used as a key in dictionary:
  71. ```python
  72. <frozenset> = frozenset()
  73. ```
  74. Range
  75. -----
  76. ```python
  77. range(to_exclusive)
  78. range(from_inclusive, to_exclusive)
  79. range(from_inclusive, to_exclusive, step_size)
  80. range(from_inclusive, to_exclusive, -step_size)
  81. ```
  82. Enumerate
  83. ---------
  84. ```python
  85. for i, <el> in enumerate(<collection> [, i_start])
  86. ```
  87. Named Tuple
  88. -----------
  89. ```python
  90. >>> Point = collections.namedtuple('Point', ['x', 'y'])
  91. >>> a = Point(1, y=2)
  92. Point(x=1, y=2)
  93. >>> a.x
  94. 1
  95. >>> getattr(a, 'y')
  96. 2
  97. ```
  98. Iterator
  99. --------
  100. #### Skips first element:
  101. ```python
  102. next(<iter>)
  103. for element in <iter>:
  104. ...
  105. ```
  106. #### Reads input until it reaches an empty line:
  107. ```python
  108. for line in iter(input, ''):
  109. ...
  110. ```
  111. #### Same, but prints a message every time:
  112. ```python
  113. from functools import partial
  114. for line in iter(partial(input, 'Please enter value'), ''):
  115. ...
  116. ```
  117. Generator
  118. ---------
  119. ```python
  120. def step(start, step):
  121. while True:
  122. yield start
  123. start += step
  124. ```
  125. ```python
  126. stepper = step(10, 2)
  127. next(stepper) # 10 (, 12, 14, ...)
  128. ```
  129. Type
  130. ----
  131. ```python
  132. type(<el>) # <class 'int'> / <class 'str'> / ...
  133. ```
  134. ```python
  135. import numbers
  136. isinstance(<el>, numbers.Number) # Integral, Real, Rational, Complex
  137. ```
  138. String
  139. ------
  140. ```python
  141. str.replace(text, old, new)
  142. <str>.split(sep=None, maxsplit=-1)
  143. <str>.strip()
  144. <str>.join(<list>)
  145. <str>.startswith(<str>) # Pass tuple of strings for multiple options.
  146. <str>.isnumeric() # True if str contains only numeric characters.
  147. ```
  148. ### Print
  149. ```python
  150. print(<el> [, <el>, end='', sep='', file=<file>]) # Use 'file=sys.stderr' for err.
  151. ```
  152. ### Regex
  153. ```python
  154. import re
  155. re.sub(<regex>, new, text, count=0)
  156. re.search(<regex>, text) # Searches for first occurrence of pattern.
  157. re.match(<regex>, text) # Searches only at the beginning of the string.
  158. re.findall(<regex>, text)
  159. re.split(<regex>, text, maxsplit=0) # Use brackets in regex to keep the matches.
  160. ```
  161. **'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.**
  162. **Parameter 'flags=re.IGNORECASE' can be used with all functions. Parameter 'flags=re.DOTALL' makes dot also accept newline.**
  163. **Use '\\\\1' or r'\1' for backreference.**
  164. #### Special Sequences:
  165. ```python
  166. # Use capital letter for negation.
  167. '\d' == '[0-9]' # Digit
  168. '\s' == '[ \t\n\r\f\v]' # Whitespace
  169. '\w' == '[a-zA-Z0-9_]' # Alphanumeric
  170. ```
  171. ### Format
  172. ```python
  173. '{}'.format(<el> [, <el>, ...])
  174. ```
  175. ```python
  176. {:min_width} # '<el> '
  177. {:>min_width} # ' <el>'
  178. {:^min_width} # ' <el> '
  179. {:_<min_width} # '<el>____'
  180. {:.max_width} # '<e>'
  181. {:max_width.min_width} # ' <e>'
  182. {:max_width.no_of_decimalsf} # ' 3.14'
  183. ```
  184. ```python
  185. >>> person = {'name': 'Jean-Luc', 'height': 187.1}
  186. >>> '{p[height]:.0f}'.format(p=person)
  187. '187'
  188. >>> f"{person['height']:.0f}"
  189. '187'
  190. ```
  191. #### Binary, at least 10 spaces wide, filled with zeros:
  192. ```python
  193. >>> f'{123:010b}'
  194. '0001111011'
  195. ```
  196. #### Integer presentation types:
  197. * 'b' - Binary
  198. * 'c' - Character
  199. * 'o' - Octal
  200. * 'x' - Hex
  201. * 'X' - HEX
  202. ### Text Wrap
  203. ```python
  204. import textwrap
  205. textwrap.wrap(text, width)
  206. ```
  207. Random
  208. ------
  209. ```python
  210. import random
  211. random.random()
  212. random.randint(from_inclusive, to_inclusive)
  213. random.shuffle(<list>)
  214. random.choice(<list>)
  215. ```
  216. Infinity
  217. --------
  218. ```python
  219. float('inf')
  220. ```
  221. Datetime
  222. --------
  223. ```python
  224. import datetime
  225. now = datetime.datetime.now()
  226. now.month # 3
  227. now.strftime('%Y%m%d') # 20180315
  228. now.strftime('%Y%m%d%H%M%S') # 20180315002834
  229. ```
  230. Arguments
  231. ---------
  232. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
  233. ```python
  234. args = (1, 2)
  235. kwargs = {'x': 3, 'y': 4, 'z': 5}
  236. func(*args, **kwargs)
  237. ```
  238. #### Is the same as:
  239. ```python
  240. func(1, 2, x=3, y=4, z=5)
  241. ```
  242. **Splat operator can also be used in function declarations:**
  243. ```python
  244. >>> def add(*a):
  245. ... return sum(a)
  246. >>> add(1, 2, 3)
  247. 6
  248. ```
  249. **And in some other places:**
  250. ```python
  251. >>> a = (1, 2, 3)
  252. >>> [*a]
  253. [1, 2, 3]
  254. ```
  255. ```python
  256. >>> head, *body, tail = [1, 2, 3, 4]
  257. >>> body
  258. [2, 3]
  259. ```
  260. Inline
  261. ------
  262. ### Lambda
  263. ```python
  264. lambda: <return_value>
  265. lambda <argument1>, <argument2>: <return_value>
  266. ```
  267. ### Comprehension
  268. ```python
  269. [i+1 for i in range(10)] # [1, 2, ..., 10]
  270. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  271. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  272. (x+5 for x in range(0, 10)) # (5, 6, ..., 14) -> Generator
  273. ```
  274. ```python
  275. [i+j for i in range(10) for j in range(10)]
  276. ```
  277. #### Is the same as:
  278. ```python
  279. out = []
  280. for i in range(10):
  281. for j in range(10):
  282. out.append(i+j)
  283. ```
  284. ### Map, Filter, Reduce
  285. ```python
  286. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  287. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  288. functools.reduce(lambda sum, x: sum+x, range(10)) # 45
  289. ```
  290. ### Any, All
  291. ```python
  292. any(el[1] for el in <collection>)
  293. ```
  294. ### If - Else
  295. ```python
  296. <expression_if_true> if <condition> else <expression_if_false>
  297. ```
  298. ```python
  299. >>> [a if a else 2 for a in [0,1,0,3]]
  300. [2, 1, 2, 3]
  301. ```
  302. ### Namedtuple, Enum, Class
  303. ```python
  304. from collections import namedtuple
  305. from enum import Enum
  306. Point = namedtuple('Point', list('xy'))
  307. Direction = Enum('Direction', list('nesw'))
  308. Creature = type('Creature', (), {'position': Point(0, 0), 'direction': Direction.n})
  309. ```
  310. Closure
  311. -------
  312. ```python
  313. def multiply_closure(x):
  314. def wrapped(y):
  315. return x * y
  316. return wrapped
  317. multiply_by_3 = multiply_closure(3)
  318. ```
  319. #### Or:
  320. ```python
  321. from functools import partial
  322. partial(<function>, <arg1> [, <arg2>, ...])
  323. ```
  324. Decorator
  325. ---------
  326. ```python
  327. @closure_name
  328. def function_that_gets_passed_to_closure():
  329. pass
  330. ```
  331. #### Debugger example:
  332. ```python
  333. from functools import wraps
  334. def debug(func):
  335. @wraps(func) # Needed for metadata copying (func name, ...).
  336. def wrapper(*args, **kwargs):
  337. print(func.__name__)
  338. return func(*args, **kwargs)
  339. return wrapper
  340. @debug
  341. def add(x, y):
  342. return x + y
  343. ```
  344. Class
  345. -----
  346. ```python
  347. class <name>:
  348. def __init__(self, a):
  349. self.a = a
  350. def __repr__(self):
  351. return str({'a': self.a})
  352. # Use f'{s.__dict__}' for all members.
  353. def __str__(self):
  354. return str(self.a)
  355. ```
  356. ### Enum
  357. ```python
  358. import enum
  359. class <enum_name>(enum.Enum):
  360. <name1> = <value1>
  361. <name2> = <value2>
  362. <name3> = enum.auto() # Can be used for automatic indexing.
  363. ...
  364. ```
  365. ```python
  366. <enum_name>.<name> # == <enum>
  367. <enum_name>['<name>'] # == <enum>
  368. <enum_name>(value) # == <enum>
  369. <enum>.name # == <name>
  370. <enum>.value # == <value>
  371. ```
  372. ```python
  373. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  374. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  375. random.choice(list(<enum_name>)) # == random <enum>
  376. ```
  377. ### Copy
  378. ```python
  379. import copy
  380. copy.copy(<object>)
  381. copy.deepcopy(<object>)
  382. ```
  383. System
  384. ------
  385. ### Arguments
  386. ```python
  387. import sys
  388. sys.argv
  389. ```
  390. ### Read File
  391. ```python
  392. def read_file(filename):
  393. with open(filename, encoding='utf-8') as file:
  394. return file.readlines()
  395. ```
  396. ### Write to File
  397. ```python
  398. def write_to_file(filename, text):
  399. with open(filename, 'w', encoding='utf-8') as file:
  400. file.write(text)
  401. ```
  402. ### Path
  403. ```python
  404. import os
  405. os.path.exists(<path>)
  406. os.path.isfile(<path>)
  407. os.path.isdir(<path>)
  408. os.listdir(<path>)
  409. ```
  410. ### Execute Command
  411. ```python
  412. import os
  413. os.popen(<command>).read()
  414. ```
  415. #### Or:
  416. ```python
  417. >>> import subprocess
  418. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  419. >>> a.stdout
  420. b'.\n..\nfile1.txt\nfile2.txt\n'
  421. >>> a.returncode
  422. 0
  423. ```
  424. ### Input
  425. ```python
  426. filename = input('Enter a file name: ')
  427. ```
  428. #### Prints lines until EOF:
  429. ```python
  430. while True:
  431. try:
  432. print(input())
  433. except EOFError:
  434. break
  435. ```
  436. JSON
  437. ----
  438. ```python
  439. import json
  440. ```
  441. ### Serialization
  442. ```python
  443. <str> = json.dumps(<object>, ensure_ascii=True, indent=None)
  444. <object> = json.loads(<str>)
  445. ```
  446. ### Read File
  447. ```python
  448. def read_json_file(filename):
  449. with open(filename, encoding='utf-8') as file:
  450. return json.load(file)
  451. ```
  452. ### Write to File
  453. ```python
  454. def write_to_json_file(filename, an_object):
  455. with open(filename, 'w', encoding='utf-8') as file:
  456. json.dump(an_object, file, ensure_ascii=False, indent=2)
  457. ```
  458. SQLite
  459. ------
  460. ```python
  461. import sqlite3
  462. db = sqlite3.connect(filename)
  463. ```
  464. ### Read
  465. ```python
  466. cursor = db.execute(<query>)
  467. if cursor:
  468. cursor.fetchall() # Or cursor.fetchone()
  469. db.close()
  470. ```
  471. ### Write
  472. ```python
  473. db.execute(<query>)
  474. db.commit()
  475. ```
  476. Exceptions
  477. ----------
  478. ```python
  479. while True:
  480. try:
  481. x = int(input("Please enter a number: "))
  482. except ValueError:
  483. print("Oops! That was no valid number. Try again...")
  484. else:
  485. print("Thank you.")
  486. break
  487. ```
  488. Threading
  489. ---------
  490. ```python
  491. import threading
  492. ```
  493. ### Thread
  494. ```python
  495. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  496. thread.start()
  497. thread.join()
  498. ```
  499. ### Lock
  500. ```python
  501. lock = threading.Rlock()
  502. lock.acquire()
  503. lock.release()
  504. ```
  505. Itertools
  506. ---------
  507. **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.**
  508. ```python
  509. from itertools import *
  510. ```
  511. ### Chain
  512. ```python
  513. >>> chain([1, 2], range(3, 5))
  514. [1, 2, 3, 4]
  515. ```
  516. ### Combinations
  517. ```python
  518. >>> combinations("abc", 2)
  519. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  520. ```
  521. ### Permutations
  522. ```python
  523. >>> permutations("abc", 2)
  524. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  525. ```
  526. ### Product
  527. ```python
  528. >>> list(product('ab', [1, 2]))
  529. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  530. ```
  531. ### Compress
  532. ```python
  533. >>> compress("abc", [True, 0, 23])
  534. ['a', 'c']
  535. ```
  536. ### Count
  537. ```python
  538. >>> a = count(5, 2)
  539. >>> next(a), next(a)
  540. (5, 7)
  541. ```
  542. ### Cycle
  543. ```python
  544. >>> a = cycle("abc")
  545. >>> [next(a) for _ in range(10)]
  546. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  547. ```
  548. ### Groupby
  549. ```python
  550. >>> a = [{"id": 1, "name": "bob"},
  551. {"id": 2, "name": "bob"},
  552. {"id": 3, "name": "peter"}]
  553. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  554. {'bob': [{'id': 1, 'name': 'bob'},
  555. {'id': 2, 'name': 'bob'}],
  556. 'peter': [{'id': 3, 'name': 'peter'}]}
  557. ```
  558. ### Islice
  559. ```python
  560. islice([1, 2, 3], 1, None)
  561. [2, 3]
  562. ```
  563. ### Ifilter, imap and izip
  564. #### Filter, map and zip functions that return generators instead of iterators.
  565. Introspection and Metaprograming
  566. --------------------------------
  567. **Inspecting code at runtime and code that generates code. You can:**
  568. * **Look at the attributes**
  569. * **Set new attributes**
  570. * **Create functions dynamically**
  571. * **Traverse the parent classes**
  572. * **Change values in the class**
  573. ```python
  574. >>> class Z:
  575. ... def __init__(self):
  576. ... self.a = 'abcde'
  577. ... self.b = 12345
  578. >>> z = Z()
  579. ```
  580. ### Getattr, Hasattr, Setattr
  581. ```python
  582. >>> getattr(z, 'a') # Same as Z.__getattribute__(z, 'a')
  583. 'abcde'
  584. >>> hasattr(z, 'c')
  585. False
  586. >>> setattr(z, 'c', 10)
  587. ```
  588. ### Type
  589. **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!):**
  590. ```python
  591. type(class_name, parents<tuple>, attributes<dict>)
  592. ```
  593. ```python
  594. >>> Z = type('Z', (), {'a': 'abcde', 'b': 12345})
  595. >>> z = Z()
  596. ```
  597. ### MetaClass
  598. #### Class that creates class:
  599. ```python
  600. def my_meta_class(name, parents, attrs):
  601. ...
  602. return type(name, parents, attrs)
  603. ```
  604. #### Or:
  605. ```python
  606. class MyMetaClass(type):
  607. def __new__(klass, name, parents, attrs):
  608. ...
  609. return type.__new__(klass, name, parents, attrs)
  610. ```
  611. ### Metaclass Attr
  612. **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:**
  613. ```python
  614. class BlaBla:
  615. __metaclass__ = Bla
  616. ```
  617. Eval
  618. ----
  619. ```python
  620. import ast
  621. import operator as op
  622. # Supported operators
  623. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  624. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  625. ast.USub: op.neg}
  626. def eval_expr(expr):
  627. return eval_(ast.parse(expr, mode='eval').body)
  628. def eval_(node):
  629. if isinstance(node, ast.Num): # <number>
  630. return node.n
  631. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  632. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  633. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  634. return operators[type(node.op)](eval_(node.operand))
  635. else:
  636. raise TypeError(node)
  637. ```
  638. ```python
  639. >>> eval_expr('2^6')
  640. 4
  641. >>> eval_expr('2**6')
  642. 64
  643. >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  644. -5.0
  645. ```
  646. <br><br>
  647. <hr>
  648. Libraries
  649. =========
  650. Plot
  651. ----
  652. ```python
  653. # pip3 install matplotlib
  654. from matplotlib import pyplot
  655. pyplot.plot(<data> [, <data>])
  656. pyplot.show()
  657. pyplot.savefig(filename)
  658. ```
  659. Web
  660. ---
  661. ```python
  662. # pip3 install bottle
  663. import bottle
  664. import urllib
  665. ```
  666. ### Run
  667. ```python
  668. bottle.run(host='localhost', port=8080)
  669. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  670. ```
  671. ### Static request
  672. ```python
  673. @route('/img/<image>')
  674. def send_image(image):
  675. return static_file(image, 'images/', mimetype='image/png')
  676. ```
  677. ### Dynamic request
  678. ```python
  679. @route('/<sport>')
  680. def send_page(sport):
  681. sport = urllib.parse.unquote(sport).lower()
  682. page = read_file(sport)
  683. return template(page)
  684. ```
  685. ### REST request
  686. ```python
  687. @post('/p/<sport>')
  688. def p_handler(sport):
  689. team = request.forms.get('team')
  690. team = urllib.parse.unquote(team).lower()
  691. db = sqlite3.connect(conf.DB_PATH)
  692. p_h, p_a = get_p(db, sport, team)
  693. db.close()
  694. response.headers['Content-Type'] = 'application/json'
  695. response.headers['Cache-Control'] = 'no-cache'
  696. return json.dumps([p_h, p_a])
  697. ```
  698. Curses
  699. ------
  700. ```python
  701. # pip3 install curses
  702. import curses
  703. def main():
  704. curses.wrapper(draw)
  705. def draw(screen):
  706. screen.clear()
  707. screen.addstr(0, 0, "Press ESC to quit.")
  708. while screen.getch() != 27:
  709. pass
  710. def get_border(screen):
  711. Coords = collections.namedtuple('Coords', ['x', 'y'])
  712. height, width = screen.getmaxyx()
  713. return Coords(width - 1, height - 1)
  714. ```
  715. #### Gets char from int:
  716. ```python
  717. <ch> = chr(<int>)
  718. <int> = ord(<ch>)
  719. ```
  720. Profile
  721. -------
  722. #### Basic:
  723. ```python
  724. from time import time
  725. start_time = time()
  726. <code>
  727. duration = time() - start_time
  728. ```
  729. #### Times execution of the passed code:
  730. ```python
  731. from timeit import timeit
  732. timeit('"-".join(str(n) for n in range(100))', number=1000000)
  733. ```
  734. #### Generates a PNG image of call graph and highlights the bottlenecks:
  735. ```python
  736. # pip3 install pycallgraph
  737. import pycallgraph
  738. graph = pycallgraph.output.GraphvizOutput()
  739. graph.output_file = get_filename()
  740. with pycallgraph.PyCallGraph(output=graph):
  741. <code_to_be_profiled>
  742. ```
  743. #### Utility code for unique PNG filenames:
  744. ```python
  745. def get_filename():
  746. return "{}-{}.png".format("profile", get_current_datetime_string())
  747. def get_current_datetime_string():
  748. now = datetime.datetime.now()
  749. return get_datetime_string(now)
  750. def get_datetime_string(a_datetime):
  751. return a_datetime.strftime('%Y%m%d%H%M%S')
  752. ```
  753. Audio
  754. -----
  755. #### Saves list of floats of size 0 to 1 to a WAV file:
  756. ```python
  757. import wave, struct
  758. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  759. wf = wave.open(filename, 'wb')
  760. wf.setnchannels(1)
  761. wf.setsampwidth(4)
  762. wf.setframerate(44100)
  763. wf.writeframes(b''.join(frames))
  764. wf.close()
  765. ```
  766. Progress Bar
  767. ------------
  768. #### Basic:
  769. ```python
  770. import sys
  771. class Bar():
  772. @staticmethod
  773. def range(*args):
  774. bar = Bar(len(list(range(*args))))
  775. for i in range(*args):
  776. yield i
  777. bar.tick()
  778. def __init__(s, steps, width=40):
  779. s.st, s.wi, s.fl, s.i = steps, width, 0, 0
  780. s.th = s.fl * s.st / s.wi
  781. s.p(f"[{' ' * s.wi}]")
  782. s.p('\b' * (s.wi + 1))
  783. def tick(s):
  784. s.i += 1
  785. while s.i > s.th:
  786. s.fl += 1
  787. s.th = s.fl * s.st / s.wi
  788. s.p('-')
  789. if s.i == s.st:
  790. s.p('\n')
  791. def p(s, t):
  792. sys.stdout.write(t)
  793. sys.stdout.flush()
  794. ```
  795. ```python
  796. from time import sleep
  797. for i in Bar.range(100):
  798. sleep(0.02)
  799. ```
  800. #### Progress:
  801. ```python
  802. # pip3 install progress
  803. from progress.bar import Bar
  804. from time import sleep
  805. STEPS = 100
  806. bar = Bar('Processing', max=STEPS)
  807. for i in range(STEPS):
  808. sleep(0.02)
  809. bar.next()
  810. bar.finish()
  811. ```