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.

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