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.

747 lines
13 KiB

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