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.

800 lines
14 KiB

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