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.

477 lines
7.0 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
  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. ```
  27. Set
  28. ---
  29. ```python
  30. <set> = set()
  31. <set>.add(<el>)
  32. <set>.update(<set>)
  33. <set>.union(<set>)
  34. <set>.intersection(<set>)
  35. <set>.difference(<set>)
  36. ```
  37. Range
  38. -----
  39. ```python
  40. range(<to exclusive>)
  41. range(<from inclusive>, <to exclusive>)
  42. range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
  43. ```
  44. Enumerate
  45. ---------
  46. ```python
  47. for i, <el> in enumerate(<list>)
  48. ```
  49. Type
  50. ----
  51. ```python
  52. type(<el>) is int/str/set/list
  53. ```
  54. ```python
  55. import numbers
  56. isinstance(<el>, numbers.Number)
  57. ```
  58. String
  59. ------
  60. ```python
  61. str.replace(<text>, <old>, <new>)
  62. <str>.isnumeric()
  63. <str>.split()
  64. <str>.strip()
  65. '<str>'.join(<list>)
  66. ```
  67. ### Print
  68. ```python
  69. print(<el1>, <el2>, end='', sep='', file=<file>)
  70. ```
  71. ### Regex
  72. ```python
  73. import re
  74. re.sub(<regex>, <new>, <text>)
  75. re.search(<regex>, <text>)
  76. ```
  77. ### Format
  78. ```python
  79. '{}'.format(<el>)
  80. ```
  81. ```python
  82. {:<min width>} -> '<el> '
  83. {:><min width>} -> ' <el>'
  84. {:^<min width>} -> ' <el> '
  85. {:_<min width>} -> '<el>____'
  86. {:.<max width>} -> '<e>'
  87. {:<max widht>.<min width>} -> ' <e>'
  88. {:<max width>.<no of decimals>f} -> ' 3.14'
  89. ```
  90. ### Text Wrap
  91. ```python
  92. import textwrap
  93. textwrap.wrap(<text>, <width>)
  94. ```
  95. Random
  96. ------
  97. ```python
  98. import random
  99. random.random()
  100. random.randint(<from inclusive>, <to inclusive>)
  101. random.shuffle(<list>)
  102. ```
  103. Infinity
  104. --------
  105. ```python
  106. float("inf")
  107. ```
  108. Datetime
  109. --------
  110. ```python
  111. import datetime
  112. now = datetime.datetime.now()
  113. now.strftime('%Y%m%d')
  114. now.strftime('%Y%m%d%H%M%S')
  115. ```
  116. Inline
  117. ------
  118. ### Lambda
  119. ```python
  120. lambda <arg1>, <arg2>: <return value>
  121. lambda: <return value>
  122. ```
  123. ### Comprehension
  124. ```python
  125. [i+1 for i in range(10)]
  126. [i for i in range(10) if i>5]
  127. [i+j for i in range(10) for j in range(10)]
  128. {i: i*2 for i in range(10)}
  129. (x+5 for x in range(0, 10)) - generator!
  130. ```
  131. ### Map, Filter, Reduce
  132. ```python
  133. A. map(lambda x: x+1, range(10))
  134. B. filter(lambda x: x>5, range(10))
  135. functools.reduce(combining_function, list_of_inputs)
  136. ```
  137. Closure
  138. -------
  139. ```python
  140. def mult_clos(x):
  141. def wrapped(y):
  142. return x * y
  143. return wrapped
  144. mul_by_3 = mult_clos(3)
  145. ```
  146. Decorator
  147. ---------
  148. ```python
  149. @closure_name
  150. def function_that_gets_passed_to_closure():
  151. ...
  152. ```
  153. Generator
  154. ---------
  155. ```python
  156. def step(start, step):
  157. while True:
  158. yield start
  159. start += step
  160. stepper = step(10, 2)
  161. next(stepper)
  162. ```
  163. Class
  164. -----
  165. ### Class
  166. ```python
  167. class <name>:
  168. def __init__(self, <arg>):
  169. self.a = <arg>
  170. def __repr__(self):
  171. return str({'a': self.a})
  172. def __str__(self):
  173. return str(self.a)
  174. ```
  175. ### Enum
  176. ```python
  177. import enum
  178. class <name>(enum.Enum):
  179. <value> = <index>
  180. ```
  181. ### Copy
  182. ```python
  183. import copy
  184. copy.copy(<object>)
  185. copy.deepcopy(<object>)
  186. ```
  187. System
  188. ------
  189. ### Arguments
  190. ```python
  191. import sys
  192. sys.argv
  193. ```
  194. ### Read File
  195. ```python
  196. with open(<filename>, encoding='utf-8') as file:
  197. return file.readlines()
  198. ```
  199. ### Write to File
  200. ```python
  201. with open(<filename>, 'w', enconding='utf-8') as file:
  202. file.write(<text>)
  203. ```
  204. ### Execute Command
  205. ```python
  206. import os
  207. os.popen(<command>).read()
  208. ```
  209. ### Input
  210. ```python
  211. filename = input('Enter a file name: ')
  212. ```
  213. JSON
  214. ----
  215. ```python
  216. import json
  217. ```
  218. ### Read File
  219. ```python
  220. with open(<filename>, encoding='utf-8') as file:
  221. return json.load(file)
  222. ```
  223. ### Write to File
  224. ```python
  225. with open(<filename>, 'w', enconding='utf-8') as file:
  226. file.write(json.dumps(<object>))
  227. ```
  228. SQLite
  229. ------
  230. ```python
  231. import sqlite3
  232. db = sqlite3.connect(<filename>)
  233. ```
  234. ### Read
  235. ```python
  236. cursor = db.execute(<query>)
  237. if cursor:
  238. cursor.<fetchone/fetchall>()
  239. db.close()
  240. ```
  241. ### Write
  242. ```python
  243. db.execute(<query>)
  244. db.commit()
  245. ```
  246. Threading
  247. ---------
  248. ```python
  249. import threading
  250. ```
  251. ### Thread
  252. ```python
  253. thread = threading.Thread(target=<function>, args=(<first arg>, ))
  254. thread.start()
  255. thread.join()
  256. ```
  257. ### Lock
  258. ```python
  259. lock = threading.Rlock()
  260. lock.acquire()
  261. lock.release()
  262. ```
  263. Itertools
  264. ---------
  265. Every function returns an generator and can accept any collection.
  266. All examples should be passed to list() to get the output.
  267. ```python
  268. from itertools import *
  269. ```
  270. ### Chain
  271. ```python
  272. >>> chain([1,2], range(3,5))
  273. [1, 2, 3, 4]
  274. ```
  275. ### Combinations
  276. ```python
  277. >>> combinations("abc", 2)
  278. [('a', 'b'), ('a', 'c'), ('b', 'c')]
  279. ```
  280. ### Permutations
  281. ```python
  282. >>> permutations("abc", 2)
  283. [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
  284. ```
  285. ### Compress
  286. ```python
  287. >>> compress("abc", [True, 0, 23])
  288. ['a', 'c']
  289. ```
  290. ### Count
  291. ```python
  292. >>> a = count(5, 2)
  293. >>> next(a), next(a)
  294. (5, 7)
  295. ```
  296. ### Cycle
  297. ```python
  298. >>> a = cycle("abc")
  299. >>> [next(a) for _ in range(10)]
  300. ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
  301. ```
  302. ### Groupby
  303. ```python
  304. >>> {k: list(v) for k, v in groupby("aabbbc")}
  305. {'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']}
  306. ```
  307. ```python
  308. >>> a = [{"id": 1, "name": "bob"}, {"id": 2, "name": "bob"}, {"id": 3, "name": "peter"}]
  309. >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
  310. {'bob': [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'bob'}], 'peter': [{'id': 3, 'name': 'peter'}]}
  311. ```
  312. ### Product
  313. ```python
  314. >>> list(product('ab', [1,2]))
  315. [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
  316. ```
  317. ### ifilter/imap/izip
  318. Filter, map and zip functions that return generators instead of iterators
  319. Introspection and Metaprograming
  320. --------------------------------
  321. Inspecting code at runetime and code that generates code.
  322. ```python
  323. >>> class B:
  324. ... def __init__(self):
  325. ... self.a= 'sdfsd'
  326. ... self.b = 123324
  327. >>> b = B()
  328. ```
  329. ### Getattr
  330. ```python
  331. >>> getattr(b, 'a')
  332. 'sdfsd'
  333. ```
  334. ### Hasattr
  335. ```python
  336. >>> hasattr(b, 'c')
  337. False
  338. ```
  339. ### Setattr
  340. ```python
  341. >>> setattr(b, 'c', 10)
  342. ```
  343. Type
  344. ----
  345. Type is the root class. If only passed the object it returns it's type.
  346. Otherwise it creates new class (and not the instance!).
  347. ```python
  348. type(class_name, parents[tuple], attributes[dict])
  349. ```
  350. ```python
  351. BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
  352. b = BB()
  353. ```
  354. MetaClass
  355. ---------
  356. Classes that creates classes.
  357. ```python
  358. def my_meta_class(name, parents, attrs):
  359. ... do stuff
  360. return type(name, parents, attrs)
  361. ```
  362. or
  363. ```python
  364. class MyMetaClass(type):
  365. def __new__(klass, name, parents, attrs):
  366. ... do stuff
  367. return type.__new__(klass, name, parents, attrs)
  368. ```
  369. Do Stuff
  370. --------
  371. * Look at the attributes
  372. * Set new attributes
  373. * Create functions dynamically
  374. * Traverse the parent classes
  375. * Change values in the class
  376. Metaclass Attr
  377. --------------
  378. 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.
  379. ```python
  380. class BlaBla:
  381. __metaclass__ = Bla
  382. ```