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.

753 lines
13 KiB

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
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
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
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
7 years ago
  1. Comprehensive Python Cheatsheet
  2. ===============================
  3. Main
  4. ----
  5. ```javascript
  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. ```
  52. #### Frozenset — Is hashable and can be used as a key in dictionary.
  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
  190. actual positional arguments in the function call.
  191. Inline
  192. ------
  193. ### Lambda
  194. ```python
  195. lambda: <return_value>
  196. lambda <argument1>, <argument2>: <return_value>
  197. ```
  198. ### Comprehension
  199. ```python
  200. [i+1 for i in range(10)] # [1, 2, ..., 10]
  201. [i for i in range(10) if i>5] # [6, 7, ..., 9]
  202. {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18}
  203. (x+5 for x in range(0, 10)) # (5, 6, ..., 14)
  204. ```
  205. ##### Last one creates a generator.
  206. ```python
  207. [i+j for i in range(10) for j in range(10)]
  208. ```
  209. #### Is the same as
  210. ```python
  211. out = []
  212. for i in range(10):
  213. for j in range(10):
  214. out.append(i+j)
  215. ```
  216. ### Map, Filter, Reduce
  217. ```python
  218. map(lambda x: x+1, range(10)) # [1, 2, ..., 10]
  219. filter(lambda x: x>5, range(10)) # [6, 7, ..., 9]
  220. functools.reduce(combining_function, list_of_inputs)
  221. ```
  222. ### Any, All
  223. ```python
  224. any(el[1] for el in <collection>)
  225. ```
  226. ### If - Else
  227. ```python
  228. <expression_if_true> if <condition> else <expression_if_false>
  229. ```
  230. Closure
  231. -------
  232. ```python
  233. def multiply_closure(x):
  234. def wrapped(y):
  235. return x * y
  236. return wrapped
  237. ```
  238. ```python
  239. multiply_by_3 = multiply_closure(3)
  240. ```
  241. #### or
  242. ```python
  243. from functools import partial
  244. partial(<function>, <argument>)
  245. ```
  246. Decorator
  247. ---------
  248. ```python
  249. @closure_name
  250. def function_that_gets_passed_to_closure():
  251. pass
  252. ```
  253. #### Debugger example
  254. ```python
  255. from functools import wraps
  256. def debug(func):
  257. @wraps(func) # Needed for metadata copying (func name, ...).
  258. def wrapper(*args, **kwargs):
  259. print(func.__name__)
  260. return func(*args, **kwargs)
  261. return wrapper
  262. @debug
  263. def add(x, y):
  264. return x + y
  265. ```
  266. Class
  267. -----
  268. ```python
  269. class <name>:
  270. def __init__(self, a):
  271. self.a = a
  272. def __repr__(self):
  273. return str({'a': self.a})
  274. def __str__(self):
  275. return str(self.a)
  276. ```
  277. ### Enum
  278. ```python
  279. import enum
  280. class <enum_name>(enum.Enum):
  281. <name1> = <value1>
  282. <name2> = <value2>
  283. ...
  284. ```
  285. ##### Also "<name3> = enum.auto()" can be used for automatic indexing.
  286. ```python
  287. <enum_name>.<name> # == <enum>
  288. <enum_name>(value) # == <enum>
  289. <enum>.name # == <name>
  290. <enum>.value # == <value>
  291. ```
  292. ```python
  293. Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon'])
  294. list(<enum_name>) # == [<enum1>, <enum2>, ...]
  295. random.choice(list(<enum_name>)) # == random <enum>
  296. ```
  297. ### Copy
  298. ```python
  299. import copy
  300. copy.copy(<object>)
  301. copy.deepcopy(<object>)
  302. ```
  303. System
  304. ------
  305. ### Arguments
  306. ```python
  307. import sys
  308. sys.argv
  309. ```
  310. ### Read File
  311. ```python
  312. with open(file_name, encoding='utf-8') as file:
  313. return file.readlines()
  314. ```
  315. ```python
  316. def get_file_contents(file_name):
  317. with open(file_name, encoding='utf-8') as file:
  318. return file.readlines()
  319. ```
  320. ### Write to File
  321. ```python
  322. with open(file_name, 'w', enconding='utf-8') as file:
  323. file.write(text)
  324. ```
  325. ### Execute Command
  326. ```python
  327. import os
  328. os.popen(<command>).read()
  329. ```
  330. ### Input
  331. ```python
  332. file_name = input('Enter a file name: ')
  333. ```
  334. ### Print lines until EOF
  335. ```python
  336. while True:
  337. try:
  338. print(input())
  339. except EOFError:
  340. break
  341. ```
  342. JSON
  343. ----
  344. ```python
  345. import json
  346. ```
  347. ### Read File
  348. ```python
  349. with open(file_name, encoding='utf-8') as file:
  350. return json.load(file)
  351. ```
  352. ### Write to File
  353. ```python
  354. with open(file_name, 'w', enconding='utf-8') as file:
  355. file.write(json.dumps(<object>))
  356. ```
  357. SQLite
  358. ------
  359. ```python
  360. import sqlite3
  361. db = sqlite3.connect(file_name)
  362. ```
  363. ### Read
  364. ```python
  365. cursor = db.execute(<query>)
  366. if cursor:
  367. cursor.fetchall() # Or "cursor.fetchone()"
  368. db.close()
  369. ```
  370. ### Write
  371. ```python
  372. db.execute(<query>)
  373. db.commit()
  374. ```
  375. Exceptions
  376. ----------
  377. ```python
  378. while True:
  379. try:
  380. x = int(input("Please enter a number: "))
  381. break
  382. except ValueError:
  383. print("Oops! That was no valid number. Try again...")
  384. ```
  385. Threading
  386. ---------
  387. ```python
  388. import threading
  389. ```
  390. ### Thread
  391. ```python
  392. thread = threading.Thread(target=<function>, args=(<first_arg>, ))
  393. thread.start()
  394. thread.join()
  395. ```
  396. ### Lock
  397. ```python
  398. lock = threading.Rlock()
  399. lock.acquire()
  400. lock.release()
  401. ```
  402. Itertools
  403. ---------
  404. Every function returns a generator and can accept any collection. If you want to
  405. print an output of generator, as in examples, you need to pass it to _list()_
  406. function.
  407. ```python
  408. from itertools import *
  409. ```
  410. ### Chain
  411. ```python
  412. >>> chain([1, 2], range(3, 5))
  413. [1, 2, 3, 4]
  414. ```
  415. ### Combinations
  416. ```python
  417. >>> combinations("abc", 2)
  418. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  419. ```
  420. ### Permutations
  421. ```python
  422. >>> permutations("abc", 2)
  423. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  424. ```
  425. ### Product
  426. ```python
  427. >>> list(product('ab', [1, 2]))
  428. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  429. ```
  430. ### Compress
  431. ```python
  432. >>> compress("abc", [True, 0, 23])
  433. ['a', 'c']
  434. ```
  435. ### Count
  436. ```python
  437. >>> a = count(5, 2)
  438. >>> next(a), next(a)
  439. (5, 7)
  440. ```
  441. ### Cycle
  442. ```python
  443. >>> a = cycle("abc")
  444. >>> [next(a) for _ in range(10)]
  445. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  446. ```
  447. ### Groupby
  448. ```python
  449. >>> a = [{"id": 1, "name": "bob"},
  450. {"id": 2, "name": "bob"},
  451. {"id": 3, "name": "peter"}]
  452. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  453. {'bob': [{'id': 1, 'name': 'bob'},
  454. {'id': 2, 'name': 'bob'}],
  455. 'peter': [{'id': 3, 'name': 'peter'}]}
  456. ```
  457. ### Islice
  458. ```python
  459. islice([1, 2, 3], 1, None)
  460. [2, 3]
  461. ```
  462. ### Ifilter/imap/izip
  463. ##### Filter, map and zip functions that return generators instead of iterators.
  464. Introspection and Metaprograming
  465. --------------------------------
  466. #### Inspecting code at runtime and code that generates code. You can:
  467. * Look at the attributes
  468. * Set new attributes
  469. * Create functions dynamically
  470. * Traverse the parent classes
  471. * Change values in the class
  472. ```python
  473. >>> class B:
  474. ... def __init__(self):
  475. ... self.a= 'sdfsd'
  476. ... self.b = 123324
  477. >>> b = B()
  478. ```
  479. #### Getattr
  480. ```python
  481. >>> getattr(b, 'a')
  482. 'sdfsd'
  483. ```
  484. ##### Is the same as
  485. ```python
  486. B.__getattribute__(b, 'a')
  487. ```
  488. #### Hasattr
  489. ```python
  490. >>> hasattr(b, 'c')
  491. False
  492. ```
  493. #### Setattr
  494. ```python
  495. >>> setattr(b, 'c', 10)
  496. ```
  497. ### Type
  498. Type is the root class. If only passed the object it returns it's type.
  499. Otherwise it creates 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. #### Classes that create classes.
  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. ```
  571. ### Run
  572. ```python
  573. bottle.run(host='localhost', port=8080)
  574. bottle.run(host='0.0.0.0', port=80, server='cherypy')
  575. ```
  576. ### Static request
  577. ### Dynamic request
  578. ### REST request
  579. Curses
  580. ------
  581. ```python
  582. import curses
  583. def main():
  584. curses.wrapper(draw)
  585. def draw(screen):
  586. screen.clear()
  587. screen.addstr(0, 0, "Press ESC to quit.")
  588. while screen.getch() != 27:
  589. pass
  590. ```
  591. ##### Gets char from int
  592. ```python
  593. chr(<int>)
  594. ```
  595. Profile
  596. -------
  597. #### Times execution of the passed code.
  598. ```python
  599. import timeit
  600. timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
  601. ```
  602. #### Generates a PNG image of call graph and highlights the bottlenecks.
  603. ```python
  604. import pycallgraph
  605. graph = pycallgraph.output.GraphvizOutput()
  606. graph.output_file = get_file_name()
  607. with pycallgraph.PyCallGraph(output=graph):
  608. <code_to_be_profiled>
  609. ```
  610. ##### Utility code for unique PNG filenames
  611. ```python
  612. def get_file_name():
  613. return "{}-{}.png".format("profile", get_current_datetime_string())
  614. def get_current_datetime_string():
  615. now = datetime.datetime.now()
  616. return get_datetime_string(now)
  617. def get_datetime_string(a_datetime):
  618. return a_datetime.strftime('%Y%m%d%H%M%S')
  619. ```
  620. Audio
  621. -----
  622. #### Saves list of floats of size 0 to 1 to a WAV file.
  623. ```python
  624. import wave, struct
  625. frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in <list>]
  626. wf = wave.open(file_name, 'wb')
  627. wf.setnchannels(1)
  628. wf.setsampwidth(4)
  629. wf.setframerate(44100)
  630. wf.writeframes(b''.join(frames))
  631. wf.close()
  632. ```