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.

713 lines
11 KiB

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