Browse Source

Anotated code with python

pull/1/head
Jure Šorn 7 years ago
parent
commit
f74b1544b8
1 changed files with 59 additions and 59 deletions
  1. 118
      README.md

118
README.md

@ -3,7 +3,7 @@ Python and Libraries Cheatsheet
Main Main
---- ----
``` ```python
if __name__ == '__main__': if __name__ == '__main__':
main() main()
``` ```
@ -11,7 +11,7 @@ if __name__ == '__main__':
List List
---- ----
``` ```python
<list>[<inclusive from>:<exclusive to>:<step size>] <list>[<inclusive from>:<exclusive to>:<step size>]
<list>.extend(<list>) <list>.extend(<list>)
<list>.sort() <list>.sort()
@ -22,7 +22,7 @@ sorted_by_second = sorted(<list>, key=lambda tup: tup[1])
Dictionary Dictionary
---------- ----------
``` ```python
<dict>.items() <dict>.items()
<dict>.get(<key>, <default>) <dict>.get(<key>, <default>)
<dict>.setdefault(<key>, <default>) <dict>.setdefault(<key>, <default>)
@ -31,7 +31,7 @@ Dictionary
Set Set
--- ---
``` ```python
<set> = set() <set> = set()
<set>.add(<el>) <set>.add(<el>)
<set>.update(<set>) <set>.update(<set>)
@ -42,7 +42,7 @@ Set
Range Range
----- -----
``` ```python
range(<to exclusive>) range(<to exclusive>)
range(<from inclusive>, <to exclusive>) range(<from inclusive>, <to exclusive>)
range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backward
@ -50,17 +50,17 @@ range(<from inclusive>, <to exclusive>, <step size>) # Negative step for backwa
Enumerate Enumerate
--------- ---------
``` ```python
for i, <el> in enumerate(<list>) for i, <el> in enumerate(<list>)
``` ```
Type Type
---- ----
``` ```python
type(<el>) is int/str/set/list type(<el>) is int/str/set/list
``` ```
``` ```python
import numbers import numbers
isinstance(<el>, numbers.Number) isinstance(<el>, numbers.Number)
``` ```
@ -68,7 +68,7 @@ isinstance(<el>, numbers.Number)
String String
------ ------
``` ```python
str.replace(<text>, <old>, <new>) str.replace(<text>, <old>, <new>)
<str>.isnumeric() <str>.isnumeric()
<str>.split() <str>.split()
@ -77,23 +77,23 @@ str.replace(<text>, <old>, <new>)
``` ```
### Print ### Print
``` ```python
print(<el1>, <el2>, end='', sep='', file=<file>) print(<el1>, <el2>, end='', sep='', file=<file>)
``` ```
### Regex ### Regex
``` ```python
import re import re
re.sub(<regex>, <new>, <text>) re.sub(<regex>, <new>, <text>)
re.search(<regex>, <text>) re.search(<regex>, <text>)
``` ```
### Format ### Format
``` ```python
'{}'.format(<el>) '{}'.format(<el>)
``` ```
``` ```python
{:<min width>} -> '<el> ' {:<min width>} -> '<el> '
{:><min width>} -> ' <el>' {:><min width>} -> ' <el>'
{:^<min width>} -> ' <el> ' {:^<min width>} -> ' <el> '
@ -104,7 +104,7 @@ re.search(<regex>, <text>)
``` ```
### Text Wrap ### Text Wrap
``` ```python
import textwrap import textwrap
textwrap.wrap(<text>, <width>) textwrap.wrap(<text>, <width>)
``` ```
@ -112,7 +112,7 @@ textwrap.wrap(<text>, <width>)
Random Random
------ ------
``` ```python
import random import random
random.random() random.random()
random.randint(<from inclusive>, <to inclusive>) random.randint(<from inclusive>, <to inclusive>)
@ -121,13 +121,13 @@ random.shuffle(<list>)
Infinity Infinity
-------- --------
``` ```python
float("inf") float("inf")
``` ```
Datetime Datetime
-------- --------
``` ```python
import datetime import datetime
now = datetime.datetime.now() now = datetime.datetime.now()
now.strftime('%Y%m%d') now.strftime('%Y%m%d')
@ -138,13 +138,13 @@ now.strftime('%Y%m%d%H%M%S')
Inline Inline
------ ------
### Lambda ### Lambda
``` ```python
lambda <arg1>, <arg2>: <return value> lambda <arg1>, <arg2>: <return value>
lambda: <return value> lambda: <return value>
``` ```
### Comprehension ### Comprehension
``` ```python
[i+1 for i in range(10)] [i+1 for i in range(10)]
[i for i in range(10) if i>5] [i for i in range(10) if i>5]
[i+j for i in range(10) for j in range(10)] [i+j for i in range(10) for j in range(10)]
@ -153,7 +153,7 @@ lambda: <return value>
``` ```
### Map, Filter, Reduce ### Map, Filter, Reduce
``` ```python
A. map(lambda x: x+1, range(10)) A. map(lambda x: x+1, range(10))
B. filter(lambda x: x>5, range(10)) B. filter(lambda x: x>5, range(10))
functools.reduce(combining_function, list_of_inputs) functools.reduce(combining_function, list_of_inputs)
@ -162,7 +162,7 @@ functools.reduce(combining_function, list_of_inputs)
Closure Closure
------- -------
``` ```python
def mult_clos(x): def mult_clos(x):
def wrapped(y): def wrapped(y):
return x * y return x * y
@ -174,7 +174,7 @@ mul_by_3 = mult_clos(3)
Decorator Decorator
--------- ---------
``` ```python
@closure_name @closure_name
def function_that_gets_passed_to_closure(): def function_that_gets_passed_to_closure():
... ...
@ -183,7 +183,7 @@ def function_that_gets_passed_to_closure():
Generator Generator
--------- ---------
``` ```python
def step(start, step): def step(start, step):
while True: while True:
yield start yield start
@ -197,7 +197,7 @@ next(stepper)
Class Class
----- -----
### Class ### Class
``` ```python
class <name>: class <name>:
def __init__(self, <arg>): def __init__(self, <arg>):
self.a = <arg> self.a = <arg>
@ -208,14 +208,14 @@ class <name>:
``` ```
### Enum ### Enum
``` ```python
import enum import enum
class <name>(enum.Enum): class <name>(enum.Enum):
<value> = <index> <value> = <index>
``` ```
### Copy ### Copy
``` ```python
import copy import copy
copy.copy(<object>) copy.copy(<object>)
copy.deepcopy(<object>) copy.deepcopy(<object>)
@ -226,49 +226,49 @@ System
------ ------
### Arguments ### Arguments
``` ```python
import sys import sys
sys.argv sys.argv
``` ```
### Read File ### Read File
``` ```python
with open(<filename>, encoding='utf-8') as file: with open(<filename>, encoding='utf-8') as file:
return file.readlines() return file.readlines()
``` ```
### Write to File ### Write to File
``` ```python
with open(<filename>, 'w', enconding='utf-8') as file: with open(<filename>, 'w', enconding='utf-8') as file:
file.write(<text>) file.write(<text>)
``` ```
### Execute Command ### Execute Command
``` ```python
import os import os
os.popen(<command>).read() os.popen(<command>).read()
``` ```
### Input ### Input
``` ```python
filename = input('Enter a file name: ') filename = input('Enter a file name: ')
``` ```
JSON JSON
---- ----
``` ```python
import json import json
``` ```
### Read File ### Read File
``` ```python
with open(<filename>, encoding='utf-8') as file: with open(<filename>, encoding='utf-8') as file:
return json.load(file) return json.load(file)
``` ```
### Write to File ### Write to File
``` ```python
with open(<filename>, 'w', enconding='utf-8') as file: with open(<filename>, 'w', enconding='utf-8') as file:
file.write(json.dumps(<object>)) file.write(json.dumps(<object>))
``` ```
@ -277,13 +277,13 @@ with open(<filename>, 'w', enconding='utf-8') as file:
SQLite SQLite
------ ------
``` ```python
import sqlite3 import sqlite3
db = sqlite3.connect(<filename>) db = sqlite3.connect(<filename>)
``` ```
### Read ### Read
``` ```python
cursor = db.execute(<query>) cursor = db.execute(<query>)
if cursor: if cursor:
cursor.<fetchone/fetchall>() cursor.<fetchone/fetchall>()
@ -291,7 +291,7 @@ db.close()
``` ```
### Write ### Write
``` ```python
db.execute(<query>) db.execute(<query>)
db.commit() db.commit()
``` ```
@ -299,19 +299,19 @@ db.commit()
Threading Threading
--------- ---------
``` ```python
import threading import threading
``` ```
### Thread ### Thread
``` ```python
thread = threading.Thread(target=<function>, args=(<first arg>, )) thread = threading.Thread(target=<function>, args=(<first arg>, ))
thread.start() thread.start()
thread.join() thread.join()
``` ```
### Lock ### Lock
``` ```python
lock = threading.Rlock() lock = threading.Rlock()
lock.acquire() lock.acquire()
lock.release() lock.release()
@ -323,62 +323,62 @@ Itertools
Every function returns an generator and can accept any collection. Every function returns an generator and can accept any collection.
All examples should be passed to list() to get the output. All examples should be passed to list() to get the output.
``` ```python
from itertools import * from itertools import *
``` ```
### Chain ### Chain
``` ```python
>>> chain([1,2], range(3,5)) >>> chain([1,2], range(3,5))
[1, 2, 3, 4] [1, 2, 3, 4]
``` ```
### Combinations ### Combinations
``` ```python
>>> combinations("abc", 2) >>> combinations("abc", 2)
[('a', 'b'), ('a', 'c'), ('b', 'c')] [('a', 'b'), ('a', 'c'), ('b', 'c')]
``` ```
### Permutations ### Permutations
``` ```python
>>> permutations("abc", 2) >>> permutations("abc", 2)
[('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')]
``` ```
### Compress ### Compress
``` ```python
>>> compress("abc", [True, 0, 23]) >>> compress("abc", [True, 0, 23])
['a', 'c'] ['a', 'c']
``` ```
### Count ### Count
``` ```python
>>> a = count(5, 2) >>> a = count(5, 2)
>>> next(a), next(a) >>> next(a), next(a)
(5, 7) (5, 7)
``` ```
### Cycle ### Cycle
``` ```python
>>> a = cycle("abc") >>> a = cycle("abc")
>>> [next(a) for _ in range(10)] >>> [next(a) for _ in range(10)]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a'] ['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a']
``` ```
### Groupby ### Groupby
``` ```python
>>> {k: list(v) for k, v in groupby("aabbbc")} >>> {k: list(v) for k, v in groupby("aabbbc")}
{'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']} {'a': ['a', 'a'], 'b': ['b', 'b', 'b'], 'c': ['c']}
``` ```
``` ```python
>>> a = [{"id": 1, "name": "bob"}, {"id": 2, "name": "bob"}, {"id": 3, "name": "peter"}] >>> a = [{"id": 1, "name": "bob"}, {"id": 2, "name": "bob"}, {"id": 3, "name": "peter"}]
>>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])} >>> {k: list(v) for k, v in groupby(a, key=lambda x: x["name"])}
{'bob': [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'bob'}], 'peter': [{'id': 3, 'name': 'peter'}]} {'bob': [{'id': 1, 'name': 'bob'}, {'id': 2, 'name': 'bob'}], 'peter': [{'id': 3, 'name': 'peter'}]}
``` ```
### Product ### Product
``` ```python
>>> list(product('ab', [1,2])) >>> list(product('ab', [1,2]))
[('a', 1), ('a', 2), ('b', 1), ('b', 2)] [('a', 1), ('a', 2), ('b', 1), ('b', 2)]
``` ```
@ -391,7 +391,7 @@ Introspection and Metaprograming
-------------------------------- --------------------------------
Inspecting code at runetime and code that generates code. Inspecting code at runetime and code that generates code.
``` ```python
>>> class B: >>> class B:
... def __init__(self): ... def __init__(self):
... self.a= 'sdfsd' ... self.a= 'sdfsd'
@ -400,19 +400,19 @@ Inspecting code at runetime and code that generates code.
``` ```
### Getattr ### Getattr
``` ```python
>>> getattr(b, 'a') >>> getattr(b, 'a')
'sdfsd' 'sdfsd'
``` ```
### Hasattr ### Hasattr
``` ```python
>>> hasattr(b, 'c') >>> hasattr(b, 'c')
False False
``` ```
### Setattr ### Setattr
``` ```python
>>> setattr(b, 'c', 10) >>> setattr(b, 'c', 10)
``` ```
@ -420,11 +420,11 @@ Type
---- ----
Type is the root class. If only passed the object it returns it's type. Type is the root class. If only passed the object it returns it's type.
Otherwise it creates new class (and not the instance!). Otherwise it creates new class (and not the instance!).
``` ```python
type(class_name, parents[tuple], attributes[dict]) type(class_name, parents[tuple], attributes[dict])
``` ```
``` ```python
BB = type('B', (), {'a': 'sdfsd', 'b': 123324} BB = type('B', (), {'a': 'sdfsd', 'b': 123324}
b = BB() b = BB()
``` ```
@ -432,13 +432,13 @@ b = BB()
MetaClass MetaClass
--------- ---------
Classes that creates classes. Classes that creates classes.
``` ```python
def my_meta_class(name, parents, attrs): def my_meta_class(name, parents, attrs):
... do stuff ... do stuff
return type(name, parents, attrs) return type(name, parents, attrs)
``` ```
or or
``` ```python
class MyMetaClass(type): class MyMetaClass(type):
def __new__(klass, name, parents, attrs): def __new__(klass, name, parents, attrs):
... do stuff ... do stuff
@ -456,7 +456,7 @@ Do Stuff
Metaclass Attr Metaclass Attr
-------------- --------------
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. 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.
``` ```python
class BlaBla: class BlaBla:
__metaclass__ = Bla __metaclass__ = Bla
``` ```

|||||||
100:0
Loading…
Cancel
Save