diff --git a/README.md b/README.md index 4d9522b..f86d7e0 100644 --- a/README.md +++ b/README.md @@ -18,11 +18,7 @@ List .reverse() sum() sorted_by_second = sorted(, key=lambda tup: tup[1]) -``` - -#### Flatten List -```python -[item for sublist in for item in sublist] +[item for sublist in for item in sublist] # Flattens List ``` Dictionary @@ -33,16 +29,8 @@ Dictionary .setdefault(key, default) .update() collections.defaultdict() -``` - -#### Initiates dict from two lists -```python -dict(zip(keys, values)) -``` - -#### Filters by keys -```python -{k: v for k, v in .iteritems() if k in keys} +dict(zip(keys, values)) # Initiates a dict from two lists +{k: v for k, v in .iteritems() if k in } # Filters a dict by keys ``` #### Counter @@ -68,32 +56,31 @@ Set Range ----- ```python -range() -range(, ) -range(, , ) # Negative step for backward +range(to_exclusive) +range(from_inclusive, to_exclusive) +range(from_inclusive, to_exclusive, step_size) # Negative step for backward ``` Enumerate --------- ```python -for i, in enumerate(, [start]) +for i, in enumerate( [, i_start]) ``` -Named Tuples ------------- +Named Tuple +----------- ```python >>> TestResults = collections.namedtuple('TestResults', ['filed', 'attempted']) >>> TestResults(1, 2) TestResults(filed=1, attempted=2) ``` - Iterator -------- -#### Reads input until it reaches empty line. +#### Reads input until it reaches empty line ```python for line in iter(input, ''): - print(line) + pass ``` Use partial from functools if function needs arguments. @@ -101,13 +88,26 @@ Use partial from functools if function needs arguments. ```python next() for element in : - ... + pass +``` + +Generator +--------- +```python +def step(start, step): + while True: + yield start + start += step + +stepper = step(10, 2) +next(stepper) # -> 10 (, 12, 14, ...) ``` + Type ---- ```python -type() is int/str/set/list +type() # is int/str/set/list/... ``` ```python import numbers @@ -118,7 +118,7 @@ isinstance(, numbers.Number) String ------ ```python -str.replace(, , ) +str.replace(text, old, new) .isnumeric() .split() .strip() @@ -127,14 +127,14 @@ str.replace(, , ) ### Print ```python -print(, , end='', sep='', file=) +print( [, , end='', sep='', file=]) ``` ### Regex ```python import re -re.sub(, , ) -re.search(, ) +re.sub(, new, text) +re.search(, text) ``` ### Format @@ -143,13 +143,13 @@ re.search(, ) ``` ```python -{:} -> ' ' -{:>} -> ' ' -{:^} -> ' ' -{:_} -> '____' -{:.} -> '' -{:.} -> ' ' -{:.f} -> ' 3.14' +{:min_width} # -> ' ' +{:>min_width} # -> ' ' +{:^min_width} # -> ' ' +{:_min_width} # -> '____' +{:.max_width} # -> '' +{:max_widht.min_width} # -> ' ' +{:max_width.no_of_decimalsf} # -> ' 3.14' ``` ```python @@ -161,7 +161,7 @@ re.search(, ) ### Text Wrap ```python import textwrap -textwrap.wrap(, ) +textwrap.wrap(text, width) ``` @@ -170,7 +170,7 @@ Random ```python import random random.random() -random.randint(, ) +random.randint(from_inclusive, to_inclusive) random.shuffle() ``` @@ -194,35 +194,36 @@ Arguments ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} -func(*args, **kwargs) -# same as +func(*args, **kwargs) # Is same as func(1, 2, x=3, y=4, z=5) ``` -* is the "splat" operator: It takes a list as input, and expands it into actual positional arguments in the function call. - -So if uniqueCrossTabs was [ [ 1, 2 ], [ 3, 4 ] ], then itertools.chain(*uniqueCrossTabs) is the same as saying itertools.chain([ 1, 2 ], [ 3, 4 ]) +"*" is the "splat" operator, that takes a list as input, and expands it into +actual positional arguments in the function call. Inline ------ ### Lambda ```python -lambda , : +lambda , : lambda: ``` ### Comprehension ```python -[i+1 for i in range(10)] -[i for i in range(10) if i>5] -{i: i*2 for i in range(10)} - dictionary -(x+5 for x in range(0, 10)) - generator +[i+1 for i in range(10)] # 1, 2, ..., 10 +[i for i in range(10) if i>5] # 6, 7, ..., 9 +{i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} +(x+5 for x in range(0, 10)) # -> Generator ``` ```python [i+j for i in range(10) for j in range(10)] -# Same as: +``` +Is same as: +``` +out = [] for i in range(10): for j in range(10): out.append(i+j) @@ -230,14 +231,14 @@ for i in range(10): ### Map, Filter, Reduce ```python -map(lambda x: x+1, range(10)) -filter(lambda x: x>5, range(10)) +map(lambda x: x+1, range(10)) # 1, 2, ..., 10 +filter(lambda x: x>5, range(10)) # 6, 7, ..., 9 functools.reduce(combining_function, list_of_inputs) ``` ### Any, All ```python -any(a[1] for a in aaa) +any(el[1] for el in ) # -> Boolean ``` ### If - Else @@ -248,18 +249,18 @@ expression_if_true if condition else expression_if_false Closure ------- ```python -def mult_clos(x): - def wrapped(y): - return x * y +def multiply_closure(x): + def wrapped(y): + return x * y return wrapped -mul_by_3 = mult_clos(3) +multiply_by_3 = multiply_closure(3) ``` #### or ```python from functools import partial -partial(, ) +partial(, ) ``` Decorator @@ -267,7 +268,7 @@ Decorator ```python @closure_name def function_that_gets_passed_to_closure(): - ... + pass ``` #### Debugger example @@ -275,7 +276,7 @@ def function_that_gets_passed_to_closure(): from functools import wraps def debug(func): - @wraps(func) # Nedded for metadata copying (func name, etc) + @wraps(func) # Needed for metadata copying (func name, ...) def wrapper(*args, **kwargs): print(func.__name__) return func(*args, **kwargs) @@ -287,26 +288,12 @@ def add(x, y): ``` -Generator ---------- -```python -def step(start, step): - while True: - yield start - start += step - -stepper = step(10, 2) -next(stepper) -``` - - Class ----- -### Class ```python class : - def __init__(self, ): - self.a = + def __init__(self, a): + self.a = a def __repr__(self): return str({'a': self.a}) def __str__(self): @@ -316,17 +303,21 @@ class : ### Enum ```python import enum -class (enum.Enum): - = # or enum.auto() +class (enum.Enum): + = # Or enum.auto() for automatic indexing. +``` -. == -(value) == -.name == -.value == +```python +. # == +(value) # == +.name # == +.value # == +``` +```python Cutlery = Enum('Cutlery', ['knife', 'fork', 'spoon']) -list() == [, , ...] -random.choice(list()) == random +list() # == [, , ...] +random.choice(list()) # == random ``` ### Copy @@ -348,19 +339,19 @@ sys.argv ### Read File ```python -with open(, encoding='utf-8') as file: +with open(file_name, encoding='utf-8') as file: return file.readlines() ``` ```python def get_file_contents(file_name): - with open(file_name, encoding='utf-8') as f: - return f.readlines() + with open(file_name, encoding='utf-8') as file: + return file.readlines() ``` ### Write to File ```python -with open(, 'w', enconding='utf-8') as file: - file.write() +with open(file_name, 'w', enconding='utf-8') as file: + file.write(text) ``` ### Execute Command @@ -371,10 +362,10 @@ os.popen().read() ### Input ```python -filename = input('Enter a file name: ') +file_name = input('Enter a file name: ') ``` -Print lines until EOF +### Print lines until EOF ```python while True: try: @@ -391,13 +382,13 @@ import json ### Read File ```python -with open(, encoding='utf-8') as file: +with open(file_name, encoding='utf-8') as file: return json.load(file) ``` ### Write to File ```python -with open(, 'w', enconding='utf-8') as file: +with open(file_name, 'w', enconding='utf-8') as file: file.write(json.dumps()) ``` @@ -405,7 +396,7 @@ SQLite ------ ```python import sqlite3 -db = sqlite3.connect() +db = sqlite3.connect(file_name) ``` ### Read @@ -455,8 +446,8 @@ lock.release() Itertools --------- -Every function returns an generator and can accept any collection. -All examples should be passed to list() to get the output. +Every function returns a generator and can accept any collection. If you want to print an output of generator, as in examples, you need to pass it to list() +function. ```python from itertools import * @@ -464,7 +455,7 @@ from itertools import * ### Chain ```python ->>> chain([1,2], range(3,5)) +>>> chain([1, 2], range(3, 5)) [1, 2, 3, 4] ``` @@ -482,7 +473,7 @@ from itertools import * ### Product ```python ->>> list(product('ab', [1,2])) +>>> list(product('ab', [1, 2])) [('a', 1), ('a', 2), ('b', 1), ('b', 2)] ``` @@ -530,7 +521,13 @@ Filter, map and zip functions that return generators instead of iterators Introspection and Metaprograming -------------------------------- -#### Inspecting code at runtime and code that generates code. +#### Inspecting code at runtime and code that generates code. You can: +* Look at the attributes +* Set new attributes +* Create functions dynamically +* Traverse the parent classes +* Change values in the class + ```python >>> class B: @@ -540,70 +537,57 @@ Introspection and Metaprograming >>> b = B() ``` -### Getattr +#### Getattr ```python >>> getattr(b, 'a') 'sdfsd' ``` -same as +Is the same as + ```python B.__getattribute__(b, 'a') ``` -### Hasattr +#### Hasattr ```python >>> hasattr(b, 'c') False ``` -### Setattr +#### Setattr ```python >>> setattr(b, 'c', 10) ``` -Type ----- +### 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!). ```python -type(class_name, parents[tuple], attributes[dict]) +type(class_name, parents, attributes) ``` ```python -BB = type('B', (), {'a': 'sdfsd', 'b': 123324} -b = BB() +>>> BB = type('B', (), {'a': 'sdfsd', 'b': 123324} +>>> b = BB() ``` - -MetaClass ---------- -#### Classes that creates classes. +### MetaClass +#### Classes that create classes. ```python def my_meta_class(name, parents, attrs): - ... do stuff + # do stuff return type(name, parents, attrs) ``` or ```python class MyMetaClass(type): def __new__(klass, name, parents, attrs): - ... do stuff + # do stuff return type.__new__(klass, name, parents, attrs) ``` - -Do Stuff --------- -* Look at the attributes -* Set new attributes -* Create functions dynamically -* Traverse the parent classes -* Change values in the class - - -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. ```python class BlaBla: @@ -617,34 +601,35 @@ Eval import ast import operator as op -# supported operators +# Supported operators operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul, ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor, ast.USub: op.neg} def eval_expr(expr): - """ - >>> eval_expr('2^6') - 4 - >>> eval_expr('2**6') - 64 - >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)') - -5.0 - """ print(expr) return eval_(ast.parse(expr, mode='eval').body) def eval_(node): - if isinstance(node, ast.Num): # + if isinstance(node, ast.Num): # return node.n - elif isinstance(node, ast.BinOp): # + elif isinstance(node, ast.BinOp): # return operators[type(node.op)](eval_(node.left), eval_(node.right)) - elif isinstance(node, ast.UnaryOp): # e.g., -1 + elif isinstance(node, ast.UnaryOp): # e.g., -1 return operators[type(node.op)](eval_(node.operand)) else: raise TypeError(node) ``` +``` +>>> eval_expr('2^6') +4 +>>> eval_expr('2**6') +64 +>>> eval_expr('1 + 2*3**(4^5) / (6 + -7)') +-5.0 +``` + Libraries ========= @@ -653,9 +638,9 @@ Plot ---- ```python import matplotlib -matplotlib.pyplot.plot(, ...) +matplotlib.pyplot.plot( [, ]) matplotlib.pyplot.show() -matplotlib.pyplot.savefig() +matplotlib.pyplot.savefig(filename) ``` Web @@ -701,14 +686,18 @@ Profile import timeit timeit.timeit('"-".join(str(n) for n in range(100))', number=10000) ``` - +#### Generates a PNG image of call graph and highlights the bottlenecks. ```python import pycallgraph graph = pycallgraph.output.GraphvizOutput() -graph.output_file = "{}-{}.png".format("profile", - get_current_datetime_string()) +graph.output_file = get_file_name() with pycallgraph.PyCallGraph(output=graph): - + +``` +#### Utility code for unique PNG filenames. +```python +def get_file_name(): + return "{}-{}.png".format("profile", get_current_datetime_string()) def get_current_datetime_string(): now = datetime.datetime.now() @@ -722,10 +711,9 @@ Audio ----- #### Saves list of floats of size 0 to 1 to a WAV file. ```python -import wave -import struct +import wave, struct frames = [struct.pack("%dh"%(1), int((a-0.5)*60000)) for a in ] -wf = wave.open(, 'wb') +wf = wave.open(file_name, 'wb') wf.setnchannels(1) wf.setsampwidth(4) wf.setframerate(44100)