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.

783 lines
14 KiB

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