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.

802 lines
14 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
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
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
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. ```
  19. ```python
  20. sum(<list>)
  21. sorted_by_second = sorted(<list>, key=lambda tup: tup[1])
  22. flattened_list = [item for sublist in <list> for item in sublist]
  23. ```
  24. Dictionary
  25. ----------
  26. ```python
  27. <dict>.items()
  28. <dict>.get(key, default)
  29. <dict>.setdefault(key, default)
  30. <dict>.update(<dict>)
  31. ```
  32. ```python
  33. collections.defaultdict(<type>) # Creates a dictionary with default values.
  34. dict(zip(keys, values)) # Initiates a dict from two lists.
  35. {k: v for k, v in <dict>.iteritems() if k in <list>} # Filters a dict by keys.
  36. ```
  37. ### Counter
  38. ```python
  39. >>> from collections import Counter
  40. >>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
  41. >>> Counter(z)
  42. Counter({'blue': 3, 'red': 2, 'yellow': 1})
  43. ```
  44. Set
  45. ---
  46. ```python
  47. <set> = set()
  48. <set>.add(<el>)
  49. <set>.update(<set>)
  50. <set>.union(<set>)
  51. <set>.intersection(<set>)
  52. <set>.difference(<set>)
  53. ```
  54. ### Frozenset
  55. #### Is hashable and can be used as a key in dictionary:
  56. ```python
  57. <set> = frozenset()
  58. ```
  59. Range
  60. -----
  61. ```python
  62. range(to_exclusive)
  63. range(from_inclusive, to_exclusive)
  64. range(from_inclusive, to_exclusive, step_size)
  65. range(from_inclusive, to_exclusive, -step_size)
  66. ```
  67. Enumerate
  68. ---------
  69. ```python
  70. for i, <el> in enumerate(<collection> [, i_start])
  71. ```
  72. Named Tuple
  73. -----------
  74. ```python
  75. >>> TestResults = collections.namedtuple('TestResults', ['filed', 'attempted'])
  76. >>> a = TestResults(1, attempted=2)
  77. TestResults(filed=1, attempted=2)
  78. >>> a.filed
  79. 1
  80. >>> getattr(a, 'attempted')
  81. 2
  82. ```
  83. Iterator
  84. --------
  85. #### Skips first element:
  86. ```python
  87. next(<iter>)
  88. for element in <iter>:
  89. ...
  90. ```
  91. #### Reads input until it reaches an empty line:
  92. ```python
  93. for line in iter(input, ''):
  94. ...
  95. ```
  96. #### Same, but prints a message every time:
  97. ```python
  98. from functools import partial
  99. for line in iter(partial(input, 'Please enter value'), ''):
  100. ...
  101. ```
  102. Generator
  103. ---------
  104. ```python
  105. def step(start, step):
  106. while True:
  107. yield start
  108. start += step
  109. ```
  110. ```python
  111. stepper = step(10, 2)
  112. next(stepper) # 10 (, 12, 14, ...)
  113. ```
  114. Type
  115. ----
  116. ```python
  117. type(<el>) # <class 'int'>/<class 'str'>/...
  118. ```
  119. ```python
  120. import numbers
  121. isinstance(<el>, numbers.Number)
  122. ```
  123. String
  124. ------
  125. ```python
  126. str.replace(text, old, new)
  127. <str>.isnumeric()
  128. <str>.split()
  129. <str>.strip()
  130. <str>.join(<list>)
  131. ```
  132. ### Print
  133. ```python
  134. print(<el> [, <el>, end='', sep='', file=<file>])
  135. ```
  136. ### Regex
  137. ```python
  138. import re
  139. re.sub(<regex>, new, text)
  140. re.search(<regex>, text)
  141. ```
  142. ### Format
  143. ```python
  144. '{}'.format(<el> [, <el>, ...])
  145. ```
  146. ```python
  147. {:min_width} # '<el> '
  148. {:>min_width} # ' <el>'
  149. {:^min_width} # ' <el> '
  150. {:_min_width} # '<el>____'
  151. {:.max_width} # '<e>'
  152. ```
  153. ```python
  154. {:max_width.min_width} # ' <e>'
  155. {:max_width.no_of_decimalsf} # ' 3.14'
  156. ```
  157. ```python
  158. >>> person = {'name': 'Jean-Luc', 'height': 187.1}
  159. >>> '{p[height]:.0f}'.format(p=person)
  160. '187'
  161. ```
  162. #### Or:
  163. ```python
  164. >>> f"{person['height']:.0f}"
  165. '187'
  166. ```
  167. ### Text Wrap
  168. ```python
  169. import textwrap
  170. textwrap.wrap(text, width)
  171. ```
  172. Random
  173. ------
  174. ```python
  175. import random
  176. random.random()
  177. random.randint(from_inclusive, to_inclusive)
  178. random.shuffle(<list>)
  179. ```
  180. Infinity
  181. --------
  182. ```python
  183. float("inf")
  184. ```
  185. Datetime
  186. --------
  187. ```python
  188. import datetime
  189. now = datetime.datetime.now()
  190. now.month # 3
  191. now.strftime('%Y%m%d') # 20180315
  192. now.strftime('%Y%m%d%H%M%S') # 20180315002834
  193. ```
  194. Arguments
  195. ---------
  196. **"*" is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call:**
  197. ```python
  198. args = (1, 2)
  199. kwargs = {'x': 3, 'y': 4, 'z': 5}
  200. func(*args, **kwargs)
  201. ```
  202. #### Is the same as:
  203. ```python
  204. func(1, 2, x=3, y=4, z=5)
  205. ```
  206. Inline
  207. ------
  208. ### Lambda
  209. ```python
  210. lambda: <return_value>
  211. lambda <argument1>, <argument2>: <return_value>
  212. ```
  213. ### Comprehension
  214. ```python
  215. [i+1 for i in range(10)] # [1, 2, ..., 10]
  216. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  217. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  218. (x+5 for x in range(0, 10)) # (5, 6, ..., 14) -> Generator
  219. ```
  220. ```python
  221. [i+j for i in range(10) for j in range(10)]
  222. ```
  223. #### Is the same as:
  224. ```python
  225. out = []
  226. for i in range(10):
  227. for j in range(10):
  228. out.append(i+j)
  229. ```
  230. ### Map, Filter, Reduce
  231. ```python
  232. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  233. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  234. functools.reduce(combining_function, list_of_inputs)
  235. ```
  236. ### Any, All
  237. ```python
  238. any(el[1] for el in <collection>)
  239. ```
  240. ### If - Else
  241. ```python
  242. <expression_if_true> if <condition> else <expression_if_false>
  243. ```
  244. Closure
  245. -------
  246. ```python
  247. def multiply_closure(x):
  248. def wrapped(y):
  249. return x * y
  250. return wrapped
  251. multiply_by_3 = multiply_closure(3)
  252. ```
  253. #### Or:
  254. ```python
  255. from functools import partial
  256. partial(<function>, <argument>)
  257. ```
  258. Decorator
  259. ---------
  260. ```python
  261. @closure_name
  262. def function_that_gets_passed_to_closure():
  263. pass
  264. ```
  265. #### Debugger example:
  266. ```python
  267. from functools import wraps
  268. def debug(func):
  269. @wraps(func) # Needed for metadata copying (func name, ...).
  270. def wrapper(*args, **kwargs):
  271. print(func.__name__)
  272. return func(*args, **kwargs)
  273. return wrapper
  274. @debug
  275. def add(x, y):
  276. return x + y
  277. ```
  278. Class
  279. -----
  280. ```python
  281. class <name>:
  282. def __init__(self, a):
  283. self.a = a
  284. def __repr__(self):
  285. return str({'a': self.a})
  286. def __str__(self):
  287. return str(self.a)
  288. ```
  289. ### Enum
  290. ```python
  291. import enum
  292. class <enum_name>(enum.Enum):
  293. <name1> = <value1>
  294. <name2> = <value2>
  295. <name3> = enum.auto() # Can be used for automatic indexing.
  296. ...
  297. ```
  298. ```python
  299. <enum_name>.<name> # == <enum>
  300. <enum_name>(value) # == <enum>
  301. <enum>.name # == <name>
  302. <enum>.value # == <value>
  303. ```
  304. ```python
  305. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  306. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  307. random.choice(list(<enum_name>)) # == random <enum>
  308. ```
  309. ### Copy
  310. ```python
  311. import copy
  312. copy.copy(<object>)
  313. copy.deepcopy(<object>)
  314. ```
  315. System
  316. ------
  317. ### Arguments
  318. ```python
  319. import sys
  320. sys.argv
  321. ```
  322. ### Read File
  323. ```python
  324. def read_file(filename):
  325. with open(filename, encoding='utf-8') as file:
  326. return file.readlines()
  327. ```
  328. ### Write to File
  329. ```python
  330. def write_to_file(filename, text):
  331. with open(filename, 'w', enconding='utf-8') as file:
  332. file.write(text)
  333. ```
  334. ### Execute Command
  335. ```python
  336. import os
  337. os.popen(<command>).read()
  338. ```
  339. #### Or:
  340. ```python
  341. >>> import subprocess
  342. >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE)
  343. >>> a.stdout
  344. b'.\n..\nfile1.txt\nfile2.txt\n'
  345. >>> a.returncode
  346. 0
  347. ```
  348. ### Input
  349. ```python
  350. filename = input('Enter a file name: ')
  351. ```
  352. #### Prints lines until EOF:
  353. ```python
  354. while True:
  355. try:
  356. print(input())
  357. except EOFError:
  358. break
  359. ```
  360. JSON
  361. ----
  362. ```python
  363. import json
  364. ```
  365. ### Read File
  366. ```python
  367. with open(filename, encoding='utf-8') as file:
  368. return json.load(file)
  369. ```
  370. ### Write to File
  371. ```python
  372. with open(filename, 'w', encoding='utf-8') as file:
  373. json.dump(<object>, file) # Or: file.write(json.dumps(<object>))
  374. ```
  375. SQLite
  376. ------
  377. ```python
  378. import sqlite3
  379. db = sqlite3.connect(filename)
  380. ```
  381. ### Read
  382. ```python
  383. cursor = db.execute(<query>)
  384. if cursor:
  385. cursor.fetchall() # Or cursor.fetchone()
  386. db.close()
  387. ```
  388. ### Write
  389. ```python
  390. db.execute(<query>)
  391. db.commit()
  392. ```
  393. Exceptions
  394. ----------
  395. ```python
  396. while True:
  397. try:
  398. x = int(input("Please enter a number: "))
  399. break
  400. except ValueError:
  401. print("Oops! That was no valid number. Try again...")
  402. ```
  403. Threading
  404. ---------
  405. ```python
  406. import threading
  407. ```
  408. ### Thread
  409. ```python
  410. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  411. thread.start()
  412. thread.join()
  413. ```
  414. ### Lock
  415. ```python
  416. lock = threading.Rlock()
  417. lock.acquire()
  418. lock.release()
  419. ```
  420. Itertools
  421. ---------
  422. **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.**
  423. ```python
  424. from itertools import *
  425. ```
  426. ### Chain
  427. ```python
  428. >>> chain([1, 2], range(3, 5))
  429. [1, 2, 3, 4]
  430. ```
  431. ### Combinations
  432. ```python
  433. >>> combinations("abc", 2)
  434. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  435. ```
  436. ### Permutations
  437. ```python
  438. >>> permutations("abc", 2)
  439. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  440. ```
  441. ### Product
  442. ```python
  443. >>> list(product('ab', [1, 2]))
  444. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  445. ```
  446. ### Compress
  447. ```python
  448. >>> compress("abc", [True, 0, 23])
  449. ['a', 'c']
  450. ```
  451. ### Count
  452. ```python
  453. >>> a = count(5, 2)
  454. >>> next(a), next(a)
  455. (5, 7)
  456. ```
  457. ### Cycle
  458. ```python
  459. >>> a = cycle("abc")
  460. >>> [next(a) for _ in range(10)]
  461. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  462. ```
  463. ### Groupby
  464. ```python
  465. >>> a = [{"id": 1, "name": "bob"},
  466. {"id": 2, "name": "bob"},
  467. {"id": 3, "name": "peter"}]
  468. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  469. {'bob': [{'id': 1, 'name': 'bob'},
  470. {'id': 2, 'name': 'bob'}],
  471. 'peter': [{'id': 3, 'name': 'peter'}]}
  472. ```
  473. ### Islice
  474. ```python
  475. islice([1, 2, 3], 1, None)
  476. [2, 3]
  477. ```
  478. ### Ifilter, imap and izip
  479. #### Filter, map and zip functions that return generators instead of iterators.
  480. Introspection and Metaprograming
  481. --------------------------------
  482. **Inspecting code at runtime and code that generates code. You can:**
  483. * **Look at the attributes**
  484. * **Set new attributes**
  485. * **Create functions dynamically**
  486. * **Traverse the parent classes**
  487. * **Change values in the class**
  488. ```python
  489. >>> class B:
  490. ... def __init__(self):
  491. ... self.a= 'sdfsd'
  492. ... self.b = 123324
  493. >>> b = B()
  494. ```
  495. ### Getattr
  496. ```python
  497. >>> getattr(b, 'a')
  498. 'sdfsd'
  499. ```
  500. #### Is the same as:
  501. ```python
  502. B.__getattribute__(b, 'a')
  503. ```
  504. ### Hasattr
  505. ```python
  506. >>> hasattr(b, 'c')
  507. False
  508. ```
  509. ### Setattr
  510. ```python
  511. >>> setattr(b, 'c', 10)
  512. ```
  513. ### Type
  514. **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!):**
  515. ```python
  516. type(class_name, parents<tuple>, attributes<dict>)
  517. ```
  518. ```python
  519. >>> BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
  520. >>> b = BB()
  521. ```
  522. ### MetaClass
  523. #### Class that creates class:
  524. ```python
  525. def my_meta_class(name, parents, attrs):
  526. ...
  527. return type(name, parents, attrs)
  528. ```
  529. #### Or:
  530. ```python
  531. class MyMetaClass(type):
  532. def __new__(klass, name, parents, attrs):
  533. ...
  534. return type.__new__(klass, name, parents, attrs)
  535. ```
  536. ### Metaclass Attr
  537. **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:**
  538. ```python
  539. class BlaBla:
  540. __metaclass__ = Bla
  541. ```
  542. Eval
  543. ----
  544. ```python
  545. import ast
  546. import operator as op
  547. # Supported operators
  548. operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
  549. ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
  550. ast.USub: op.neg}
  551. def eval_expr(expr):
  552. return eval_(ast.parse(expr, mode='eval').body)
  553. def eval_(node):
  554. if isinstance(node, ast.Num): # <number>
  555. return node.n
  556. elif isinstance(node, ast.BinOp): # <left> <operator> <right>
  557. return operators[type(node.op)](eval_(node.left), eval_(node.right))
  558. elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
  559. return operators[type(node.op)](eval_(node.operand))
  560. else:
  561. raise TypeError(node)
  562. ```
  563. ```python
  564. >>> eval_expr('2^6')
  565. 4
  566. >>> eval_expr('2**6')
  567. 64
  568. >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
  569. -5.0
  570. ```
  571. Libraries
  572. =========
  573. Plot
  574. ----
  575. ```python
  576. import matplotlib
  577. matplotlib.pyplot.plot(<data> [, <data>])
  578. matplotlib.pyplot.show()
  579. matplotlib.pyplot.savefig(filename)
  580. ```
  581. Web
  582. ---
  583. ```python
  584. import bottle
  585. import urllib
  586. ```
  587. ### Run
  588. ```python
  589. bottle.run(host='localhost', port=8080)
  590. bottle.run(host='0.0.0.0', port=80, server='cherrypy')
  591. ```
  592. ### Static request
  593. ```python
  594. @route('/img/<image>')
  595. def send_image(image):
  596. return static_file(image, 'images/', mimetype='image/png')
  597. ```
  598. ### Dynamic request
  599. ```python
  600. @route('/<sport>')
  601. def send_page(sport):
  602. sport = urllib.parse.unquote(sport).lower()
  603. page = read_file(sport)
  604. return template(page)
  605. ```
  606. ### REST request
  607. ```python
  608. @post('/p/<sport>')
  609. def p_handler(sport):
  610. team = request.forms.get('team')
  611. team = urllib.parse.unquote(team).lower()
  612. db = sqlite3.connect(conf.DB_PATH)
  613. p_h, p_a = get_p(db, sport, team)
  614. db.close()
  615. response.headers['Content-Type'] = 'application/json'
  616. response.headers['Cache-Control'] = 'no-cache'
  617. return json.dumps([p_h, p_a])
  618. ```
  619. Curses
  620. ------
  621. ```python
  622. import curses
  623. def main():
  624. curses.wrapper(draw)
  625. def draw(screen):
  626. screen.clear()
  627. screen.addstr(0, 0, "Press ESC to quit.")
  628. while screen.getch() != 27:
  629. pass
  630. ```
  631. #### Gets char from int:
  632. ```python
  633. chr(<int>)
  634. ```
  635. Profile
  636. -------
  637. #### Times execution of the passed code:
  638. ```python
  639. import timeit
  640. timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
  641. ```
  642. #### Generates a PNG image of call graph and highlights the bottlenecks:
  643. ```python
  644. import pycallgraph
  645. graph = pycallgraph.output.GraphvizOutput()
  646. graph.output_file = get_filename()
  647. with pycallgraph.PyCallGraph(output=graph):
  648. <code_to_be_profiled>
  649. ```
  650. #### Utility code for unique PNG filenames:
  651. ```python
  652. def get_filename():
  653. return "{}-{}.png".format("profile", get_current_datetime_string())
  654. def get_current_datetime_string():
  655. now = datetime.datetime.now()
  656. return get_datetime_string(now)
  657. def get_datetime_string(a_datetime):
  658. return a_datetime.strftime('%Y%m%d%H%M%S')
  659. ```
  660. Audio
  661. -----
  662. #### Saves list of floats of size 0 to 1 to a WAV file:
  663. ```python
  664. import wave, struct
  665. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  666. wf = wave.open(filename, 'wb')
  667. wf.setnchannels(1)
  668. wf.setsampwidth(4)
  669. wf.setframerate(44100)
  670. wf.writeframes(b''.join(frames))
  671. wf.close()
  672. ```