From 68dd21b78b80ac9d67a1b2d3d1ab0d640bbe4e6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:24:55 +0100 Subject: [PATCH 0001/1913] A lot of small changes --- README.md | 153 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 79 insertions(+), 74 deletions(-) diff --git a/README.md b/README.md index 5f458ef80..580398aa0 100644 --- a/README.md +++ b/README.md @@ -41,16 +41,15 @@ elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) flattened_list = list(itertools.chain.from_iterable()) -list_of_chars = list() product_of_elems = functools.reduce(lambda out, x: out * x, ) -no_duplicates = list(dict.fromkeys()) +list_of_chars = list() ``` ```python index = .index() # Returns first index of item. .insert(index, ) # Inserts item at index and moves the rest to the right. = .pop([index]) # Removes and returns item at index or from the end. -.remove() # Removes first occurrence of item. +.remove() # Removes first occurrence of item or raises ValueError. .clear() # Removes all items. ``` @@ -64,17 +63,17 @@ Dictionary ``` ```python -value = .get(key, default) # Returns default if key does not exist. -value = .setdefault(key, default) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default=None) # Returns default if key does not exist. +value = .setdefault(key, default=None) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. - = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. +.update() # Or: dict_a = {**dict_a, **dict_b}. + = dict() # Initiates a dict from list of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two lists. + = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. ``` ```python @@ -88,8 +87,8 @@ value = .pop(key) # Removes item from dictionary. >>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] >>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) ->>> counter.most_common()[0][0] -'blue' +>>> counter.most_common()[0] +('blue', 3) ``` @@ -121,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable and can be used as a key in dictionary. +#### Is hashable so it can be used as a key in dictionary. ```python = frozenset() ``` @@ -130,10 +129,10 @@ Set Range ----- ```python -range(to_exclusive) -range(from_inclusive, to_exclusive) -range(from_inclusive, to_exclusive, step_size) -range(from_inclusive, to_exclusive, -step_size) + = range(to_exclusive) + = range(from_inclusive, to_exclusive) + = range(from_inclusive, to_exclusive, step_size) + = range(from_inclusive, to_exclusive, -step_size) ``` ```python @@ -153,7 +152,8 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- ```python ->>> Point = collections.namedtuple('Point', 'x y') +>>> from collections import namedtuple +>>> Point = namedtuple('Point', 'x y') >>> p = Point(1, y=2) Point(x=1, y=2) >>> p[0] @@ -188,7 +188,7 @@ for line in iter(partial(input, 'Please enter value: '), ''): ``` ### Next -**Returns next item. If there are no more items it raises exception or returns default if specified.** +**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.** ```python = next( [, default]) ``` @@ -252,7 +252,7 @@ String = .replace(old_str, new_str) = .startswith() # Pass tuple of strings for multiple options. = .endswith() # Pass tuple of strings for multiple options. - = .index() # Returns first index of a substring. + = .index() # Returns start index of first match. = .isnumeric() # True if str contains only numeric characters. = textwrap.wrap(, width) # Nicely breaks string into lines. ``` @@ -288,7 +288,7 @@ import re * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** * **Use `r'\1'` or `'\\\\1'` for backreference.** -* **Use `'?'` to make operators non-greedy.** +* **Use `'?'` to make operator non-greedy.** ### Match Object ```python @@ -300,7 +300,7 @@ import re ``` ### Special Sequences -**Use capital letter for negation.** +**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -318,10 +318,10 @@ Format ```python >>> Person = namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) ->>> f'{person.height:10}' -' 187' ->>> '{p.height:10}'.format(p=person) -' 187' +>>> f'{person.height}' +'187' +>>> '{p.height}'.format(p=person) +'187' ``` ### General Options @@ -581,7 +581,7 @@ from functools import partial ``` ### Nonlocal -**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as global or nonlocal.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as 'global' or 'nonlocal'.** ```python def get_counter(): @@ -668,7 +668,7 @@ class : def __init__(self, a): self.a = a def __repr__(self): - class_name = type(self).__name__ + class_name = self.__class__.__name__ return f'{class_name}({self.a!r})' def __str__(self): return str(self.a) @@ -870,13 +870,6 @@ KeyboardInterrupt System ------ -### Command Line Arguments -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - ### Print Function ```python print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) @@ -974,7 +967,9 @@ b'.\n..\nfile1.txt\nfile2.txt\n' >>> sys.setrecursionlimit(5000) ``` -### Path + +Path +---- ```python from os import path, listdir = path.exists('') @@ -989,9 +984,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` - -Pathlib -------- +### Pathlib **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** ```python @@ -1023,6 +1016,36 @@ pwd = Path() ``` +Command Line Arguments +---------------------- +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser +desc = 'calculate X to the power of Y' +parser = ArgumentParser(description=desc) +group = parser.add_mutually_exclusive_group() +group.add_argument('-v', '--verbose', action='store_true') +group.add_argument('-q', '--quiet', action='store_true') +parser.add_argument('x', type=int, help='the base') +parser.add_argument('y', type=int, help='the exponent') +args = parser.parse_args() +answer = args.x ** args.y + +if args.quiet: + print(answer) +elif args.verbose: + print(f'{args.x} to the power {args.y} equals {answer}') +else: + print(f'{args.x}^{args.y} == {answer}') +``` + + JSON ---- ```python @@ -1037,14 +1060,14 @@ from collections import OrderedDict = json.loads(, object_pairs_hook=OrderedDict) ``` -### Read File +### Read Object from JSON File ```python def read_json_file(filename): with open(filename, encoding='utf-8') as file: return json.load(file) ``` -### Write to File +### Write Object to JSON File ```python def write_to_json_file(filename, an_object): with open(filename, 'w', encoding='utf-8') as file: @@ -1079,7 +1102,7 @@ SQLite ------ ```python import sqlite3 -db = sqlite3.connect() +db = sqlite3.connect('') ... db.close() ``` @@ -1114,7 +1137,7 @@ Bytes ```python = .encode(encoding='utf-8') = .to_bytes(length, byteorder='big|little', signed=False) - = bytes.fromhex() + = bytes.fromhex('') ``` ### Decode @@ -1166,7 +1189,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' * **`'<'` - little-endian** * **`'>'` - big-endian** -#### Use capital letter for unsigned type. Standard size in brackets: +#### Use capital letter for unsigned type. Standard sizes are in brackets: * **`'x'` - pad byte** * **`'c'` - char (1)** * **`'h'` - short (2)** @@ -1183,7 +1206,7 @@ Array ```python from array import array - = array( [, ]) + = array('' [, ]) ``` @@ -1208,8 +1231,8 @@ from collections import deque ```python .appendleft() -.extendleft() # Collection gets reversed. = .popleft() +.extendleft() # Collection gets reversed. .rotate(n=1) # Rotates elements to the right. ``` @@ -1304,7 +1327,10 @@ from itertools import * >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) [2, 3] +``` +### Group by +```python >>> people = [{'id': 1, 'name': 'Bob'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Peter'}] @@ -1367,7 +1393,7 @@ param_names = list(sig.parameters.keys()) **Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).** ```python -type(, , ) + = type(, , ) ``` ```python @@ -1482,7 +1508,7 @@ def eval_node(node): Coroutine --------- -* **Similar to Generator, but Generator pulls data through the pipe with iteration, while Coroutine pushes data into the pipeline with send().** +* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** * **Coroutines provide more powerful data routing possibilities than iterators.** * **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** @@ -1551,29 +1577,6 @@ pyplot.show() ``` -Argparse --------- -```python -from argparse import ArgumentParser -desc = 'calculate X to the power of Y' -parser = ArgumentParser(description=desc) -group = parser.add_mutually_exclusive_group() -group.add_argument('-v', '--verbose', action='store_true') -group.add_argument('-q', '--quiet', action='store_true') -parser.add_argument('x', type=int, help='the base') -parser.add_argument('y', type=int, help='the exponent') -args = parser.parse_args() -answer = args.x ** args.y - -if args.quiet: - print(answer) -elif args.verbose: - print(f'{args.x} to the power {args.y} equals {answer}') -else: - print(f'{args.x}^{args.y} == {answer}') -``` - - Table ----- #### Prints CSV file as ASCII table: @@ -1641,12 +1644,14 @@ Audio #### Saves a list of floats with values between -1 and 1 to a WAV file: ```python import wave, struct -samples = [struct.pack('] +samples_f = [struct.pack('] +samples_b = b''.join(samples_f) + wf = wave.open('test.wav', 'wb') wf.setnchannels(1) wf.setsampwidth(2) wf.setframerate(44100) -wf.writeframes(b''.join(samples)) +wf.writeframes(samples_b) wf.close() ``` From 93f8deeb25dc10895a85f6c7ec6227eaf84a250d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:30:46 +0100 Subject: [PATCH 0002/1913] Pathlib --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 580398aa0..bb8edb19b 100644 --- a/README.md +++ b/README.md @@ -970,6 +970,7 @@ b'.\n..\nfile1.txt\nfile2.txt\n' Path ---- +### Basic ```python from os import path, listdir = path.exists('') @@ -1018,6 +1019,7 @@ pwd = Path() Command Line Arguments ---------------------- +### Basic ```python import sys script_name = sys.argv[0] From 69a3275a4b0a6914302a2067945fe31569261f5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 22 Feb 2019 19:32:59 +0100 Subject: [PATCH 0003/1913] Pathlib --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bb8edb19b..b056fbcec 100644 --- a/README.md +++ b/README.md @@ -1111,7 +1111,7 @@ db.close() ### Read ```python -cursor = db.execute() +cursor = db.execute('') if cursor: = cursor.fetchone() # First row. = cursor.fetchall() # Remaining rows. @@ -1119,7 +1119,7 @@ if cursor: ### Write ```python -db.execute() +db.execute('') db.commit() ``` From ee6eeb6fbdba5536e4574fbe96eeac312b7cb8cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 18:00:37 +0100 Subject: [PATCH 0004/1913] Argparse --- README.md | 87 +++++++++++++++++++------------------------------------ 1 file changed, 29 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index b056fbcec..33f857ed8 100644 --- a/README.md +++ b/README.md @@ -40,7 +40,7 @@ sum_of_elements = sum() elementwise_sum = [sum(pair) for pair in zip(list_a, list_b)] sorted_by_second = sorted(, key=lambda el: el[1]) sorted_by_both = sorted(, key=lambda el: (el[1], el[0])) -flattened_list = list(itertools.chain.from_iterable()) +flatter_list = list(itertools.chain.from_iterable()) product_of_elems = functools.reduce(lambda out, x: out * x, ) list_of_chars = list() ``` @@ -968,6 +968,31 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` +Command Line Arguments +---------------------- +### Basic +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType + = ArgumentParser(description=) +.add_argument('-', '--', action='store_true') # Flag +.add_argument('-', '--', type=) # Option +.add_argument('', type=, nargs=1) # First argument +.add_argument('', type=, nargs='+') # Ramaining arguments + = .parse_args() +value = . +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + Path ---- ### Basic @@ -990,7 +1015,7 @@ from os import path, listdir ```python from pathlib import Path -pwd = Path() +cwd = Path() = Path('' [, '', , ...]) = / '' / '' ``` @@ -1017,37 +1042,6 @@ pwd = Path() ``` -Command Line Arguments ----------------------- -### Basic -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser -desc = 'calculate X to the power of Y' -parser = ArgumentParser(description=desc) -group = parser.add_mutually_exclusive_group() -group.add_argument('-v', '--verbose', action='store_true') -group.add_argument('-q', '--quiet', action='store_true') -parser.add_argument('x', type=int, help='the base') -parser.add_argument('y', type=int, help='the exponent') -args = parser.parse_args() -answer = args.x ** args.y - -if args.quiet: - print(answer) -elif args.verbose: - print(f'{args.x} to the power {args.y} equals {answer}') -else: - print(f'{args.x}^{args.y} == {answer}') -``` - - JSON ---- ```python @@ -1646,8 +1640,8 @@ Audio #### Saves a list of floats with values between -1 and 1 to a WAV file: ```python import wave, struct -samples_f = [struct.pack('] -samples_b = b''.join(samples_f) +samples_l = [struct.pack('] +samples_b = b''.join(samples_l) wf = wave.open('test.wav', 'wb') wf.setnchannels(1) @@ -1677,29 +1671,6 @@ simpleaudio.play_buffer(samples_b, 1, 2, F) ``` -Url ---- -```python -from urllib.parse import quote, quote_plus, unquote, unquote_plus -``` - -### Encode -```python ->>> quote("Can't be in URL!") -'Can%27t%20be%20in%20URL%21' ->>> quote_plus("Can't be in URL!") -'Can%27t+be+in+URL%21' -``` - -### Decode -```python ->>> unquote('Can%27t+be+in+URL%21') -"Can't+be+in+URL!" ->>> unquote_plus('Can%27t+be+in+URL%21') -"Can't be in URL!" -``` - - Scraping -------- ```python From d789a92ff007db3fb939565f73180ba89a8f92ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 19:25:41 +0100 Subject: [PATCH 0005/1913] Splat --- README.md | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 33f857ed8..5cf949549 100644 --- a/README.md +++ b/README.md @@ -434,9 +434,10 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' ``` -Arguments ---------- -**`'*'` is the splat operator, that takes a list as input, and expands it into actual positional arguments in the function call.** +Splat Operator +-------------- +### Inside Function Call +**`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** ```python args = (1, 2) @@ -449,7 +450,8 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -#### Splat operator can also be used in function declarations: +### Inside Function Declaration +#### Example: ```python def add(*a): return sum(a) @@ -460,7 +462,27 @@ def add(*a): 6 ``` -#### And in few other places: +#### Legal uses: +```python +def f(*args): pass # f(1, 2, 3) +def f(x, *args): pass # f(1, 2, 3) +def f(*args, z): pass # f(1, 2, z=3) +def f(x, *args, z): pass # f(1, 2, z=3) +``` + +```python +def f(**kwargs): pass # f(x=1, y=2, z=3) +def f(x, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +``` + +```python +def f(*args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) +def f(x, *args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) +def f(*args, y, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +def f(x, *args, z, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) +``` + +### Other Uses ```python >>> a = (1, 2, 3) >>> [*a] From b06d454682455622b7403ef5dd5450bdcbcc18b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:03:01 +0100 Subject: [PATCH 0006/1913] Partial --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5cf949549..25c4a1b4f 100644 --- a/README.md +++ b/README.md @@ -590,7 +590,7 @@ def get_multiplier(a): * **If multiple nested functions within enclosing function reference the same value, that value gets shared.** * **To dynamically access function's first free variable use `'.__closure__[0].cell_contents'`.** -#### Or: +### Partial ```python from functools import partial = partial(, [, , ...]) @@ -1072,7 +1072,7 @@ import json = json.loads() ``` -#### To preserve order: +#### To preserve order use: ```python from collections import OrderedDict = json.loads(, object_pairs_hook=OrderedDict) From 636415fb40ccef022dfe8f3a8251bcaa6198e7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:42:03 +0100 Subject: [PATCH 0007/1913] Test of external link --- README.md | 3 ++- web/external_link.png | Bin 0 -> 3370 bytes 2 files changed, 2 insertions(+), 1 deletion(-) create mode 100644 web/external_link.png diff --git a/README.md b/README.md index 25c4a1b4f..6be9e4627 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,8 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic +### Basic External link + ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') diff --git a/web/external_link.png b/web/external_link.png new file mode 100644 index 0000000000000000000000000000000000000000..4d5ee4077282f068e1a9fba02ab07c861518d242 GIT binary patch literal 3370 zcmbtX3se(V8pdH1M@4F9RRp(S?FL(|fH6D@m{_fk?eMA;L9IkFi3d_eQ9+@MgBIFT z1$umt00uao3ThC9iUI;bELsIpj}SzJ#I=Bu1W+IdadP)gu<7a9)9tpKb7#K$&;OkN z|L@$JuY&^C+D>zrW@Tk%yMEp3PpqsEI7O_cT0^Km_s(qyNkK%&M-W%9=KYTYK@c08 zDO0D~Oqw(aD$bt$H+cWUpS86$ilVb-y)hvP=O}7DVPV16)K>VEweORF4OWv7YjpAy zo2l5e=`&{9eVFwxzS<0 z!(=|seNoozgwonLmlN%r$40V_Q+9S`!#lR`W?!hZ1KoS~22}2fuI~t}6tZ25JKGX3 zhcya<+xxY;p^xXB(#ziJz1#gFaq09svg+FF*RF*%3s$z5jjH9L7d>OcgA6*lwY$4J z3i5?M@>e+tKgM5`(lH|2Y9vo7>$uGw$z4u0U{p=eK9|<;QUi@b0 zR&-t8-ss5q2^or#byErzm&!Q+}2dszF*uZI=MgF_F*Rww0PO-=!atH<&< zeJiReY7XfV_mpqxEQ-kH5rmIiV;|ld&{TJM+IK83P zPZOVdC+$hO1Mc;G2QXwj`Fr07Y5vg6&a2?_dUc#15)lI_Z_}CATzsLSf)rA1+bTH>Rkvvbg(w` z77Szy zTDW*2$qE8Qo=M81*?)ntUqE_y4y8#II+Ii}_!q9Eaj+P-?*!_!j>w~!?i_exu-}Fl zpMgTZH4;VII9HfHi&au!N`JtxFM#?{hTR7=47+)pI}GgIsOk|?Q&Ugy<7lVy0XN+1 zGsEcDx+hh8J-t5{dqsD^APJ4Qcg9p*F80XV`c0zzvo zsSJ-FCW62jUzfq#(mYeu!2nG#yAC|9&Fw|sa>rZ9jY`Znp7me@fRZnXlCvg1m%*>3 z{6IP(K=YVgCmSElQPhi){YD17sZ=HE)2EI_(j}Oor4|}kf$Pqb&_Lp^1`1%8L-`X1 zZeLcPH?^S|EuhDo_WO_IDBvQ-feFs9#0~Ca*PSm0XD^*M%#?{)USqwr!EGT4Hh~;G z$20^Aqc2n+amm7D8l&1gFOXuge;Hpthw~jKc3)Q1faYCca)A^auRQnACq7xK`MRgp zY%+mem`@s!YJTho#~7KHS47DLRlw7%yHSRjM)!f!X2+x1W+T_s;ucP8R~;=h z+v)doWTK6!Z8t|@Y?3Gjk6|;Ee*$={42*#7`3HJAa1V6GZ==g7g1@7I0fuT2nt>(y z1^Dp|Xo`sVU1*jt{&pZz9?NZ6Bm)c;$u`3Y3%uTze-|eFnS-#GS|YnV&m7>77WnPn z{GZf>KXVYr8h?pQ@!%K}pyFo>{82t9{Fzg*W+EX>mc-^P@%LKbzvTt;G-iJj30YXS z)IU!iqsqcg&Tihsrb=&wN3()Ly`r1YJJUpP&4xdgbMQrrbFK&x!Ixz!;{O)5)Z%qX z{sbsCE?Y2=lG@g(7nW62J06HAZENiMG!hZ$g{oCRweT9K7+D98KD_X=bmlUu)Whfs zqxLsMG^2MmHBQUog&zrDk1vXLT^xl7ngjy)<`r@|c9N5MibIw5l$NrBR9iw-P`G)T zgctr~6fH_M{W`ui3B2LvcaN#UifScnP1RS}_iMZ@Cp6}u_Uj3a>4MU^{Wjt0KP4nH z@ma6H$QBz0r^35 bGHAQWp^^C=#u-ZHkI4Fu0#;x8ke~c-V6Ak^ literal 0 HcmV?d00001 From 1cc529ad1036713b90cad7f53bd0bdcfe832642c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:43:30 +0100 Subject: [PATCH 0008/1913] Undo --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 6be9e4627..94cd212e2 100644 --- a/README.md +++ b/README.md @@ -1467,8 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic External link - +### Basic ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 95195c8d339550c38cbf7c356004cf2db93b8375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:46:31 +0100 Subject: [PATCH 0009/1913] Test with link character --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 94cd212e2..0a7865d99 100644 --- a/README.md +++ b/README.md @@ -1465,9 +1465,9 @@ last_el = op.methodcaller('pop')() ``` -Eval +Eval ---- -### Basic +### Basic [🔗](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From a50775bec8bd4cd6e7375167a29cf9966cdca152 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:01 +0100 Subject: [PATCH 0010/1913] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0a7865d99..0c7003068 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [🔗](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 93399d01b48819f8b8ca5d2d04455f56dd4153a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:28 +0100 Subject: [PATCH 0011/1913] Test with link character --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0c7003068..e054240b6 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,8 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +### Basic +[⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From e34b4ac3fab07923eb461e4abfdc13c3300e4b4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:49:50 +0100 Subject: [PATCH 0012/1913] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e054240b6..9485321b8 100644 --- a/README.md +++ b/README.md @@ -1468,7 +1468,7 @@ last_el = op.methodcaller('pop')() Eval ---- ### Basic -[⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From e28c5b6c6b0b3c3e41fd025396ab93069b1ab3ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:50:16 +0100 Subject: [PATCH 0013/1913] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9485321b8..a53f5f4cc 100644 --- a/README.md +++ b/README.md @@ -1468,7 +1468,7 @@ last_el = op.methodcaller('pop')() Eval ---- ### Basic -[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval +[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 2863a6a4b769f4147efeb2b6b888b1dc87e0e966 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:50:45 +0100 Subject: [PATCH 0014/1913] Test with link character --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index a53f5f4cc..14ced7ac2 100644 --- a/README.md +++ b/README.md @@ -1467,8 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic -[doc](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 868b42ca77147251bafa2bc175f931caca838c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:51:43 +0100 Subject: [PATCH 0015/1913] Test with link character --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 14ced7ac2..5a82b05eb 100644 --- a/README.md +++ b/README.md @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬀](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic [⬈](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') From 079e3e4d97d36bed16701a78a5e074c452b78553 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 21:57:11 +0100 Subject: [PATCH 0016/1913] Test with links to docs --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5a82b05eb..bdeceacec 100644 --- a/README.md +++ b/README.md @@ -1446,7 +1446,7 @@ class MyClass(metaclass=MyMetaClass): ``` -Operator +Operator [⬈](https://docs.python.org/3/library/operator.html) -------- ```python from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ @@ -1478,7 +1478,7 @@ Eval ValueError: malformed node or string ``` -### Using Abstract Syntax Trees +### Using Abstract Syntax Trees [⬈](https://docs.python.org/3/library/ast.html#ast.parse) ```python import ast from ast import Num, BinOp, UnaryOp From ccb1699551cfc3e7306cb5bb2d2ed1c9cd7540f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 23 Feb 2019 22:06:29 +0100 Subject: [PATCH 0017/1913] Removed links to docs --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index bdeceacec..39aeb5a51 100644 --- a/README.md +++ b/README.md @@ -1446,7 +1446,7 @@ class MyClass(metaclass=MyMetaClass): ``` -Operator [⬈](https://docs.python.org/3/library/operator.html) +Operator -------- ```python from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ @@ -1467,7 +1467,7 @@ last_el = op.methodcaller('pop')() Eval ---- -### Basic [⬈](https://docs.python.org/3/library/ast.html?highlight=literal_eval#ast.literal_eval) +### Basic ```python >>> from ast import literal_eval >>> literal_eval('1 + 2') @@ -1478,7 +1478,7 @@ Eval ValueError: malformed node or string ``` -### Using Abstract Syntax Trees [⬈](https://docs.python.org/3/library/ast.html#ast.parse) +### Using Abstract Syntax Trees ```python import ast from ast import Num, BinOp, UnaryOp From a549bb2bc292c4812cab5a95fe3510c0d9cb57e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:02:43 +0100 Subject: [PATCH 0018/1913] Splat --- README.md | 45 +++++++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 39aeb5a51..f91bd7ff4 100644 --- a/README.md +++ b/README.md @@ -434,9 +434,23 @@ now.strftime('%Y%m%d%H%M%S') # '20180315002834' ``` -Splat Operator --------------- +Arguments +--------- ### Inside Function Call +```python +() # f(0, 0) +() # f(x=0, y=0) +(, ) # f(0, y=0) +``` + +### Inside Function Definition +```python +def f() # def f(x, y) +def f() # def f(x=0, y=0) +def f(, ) # def f(x, y=0) +``` + +### Splat operator **`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** ```python @@ -450,8 +464,7 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -### Inside Function Declaration -#### Example: +#### Splat example: ```python def add(*a): return sum(a) @@ -462,24 +475,24 @@ def add(*a): 6 ``` -#### Legal uses: +### Legal Argument Definitions and Calls ```python -def f(*args): pass # f(1, 2, 3) -def f(x, *args): pass # f(1, 2, 3) -def f(*args, z): pass # f(1, 2, z=3) -def f(x, *args, z): pass # f(1, 2, z=3) +def f(*args) # f(1, 2, 3) +def f(x, *args) # f(1, 2, 3) +def f(*args, z) # f(1, 2, z=3) +def f(x, *args, z) # f(1, 2, z=3) ``` ```python -def f(**kwargs): pass # f(x=1, y=2, z=3) -def f(x, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) +def f(**kwargs) # f(x=1, y=2, z=3) +def f(x, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) ``` ```python -def f(*args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) -def f(x, *args, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) or f(1, 2, 3) -def f(*args, y, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) -def f(x, *args, z, **kwargs): pass # f(x=1, y=2, z=3) or f(1, y=2, z=3) or f(1, 2, z=3) +def f(*args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(x, *args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(*args, y, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(x, *args, z, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) ``` ### Other Uses @@ -1006,7 +1019,7 @@ from argparse import ArgumentParser, FileType .add_argument('-', '--', action='store_true') # Flag .add_argument('-', '--', type=) # Option .add_argument('', type=, nargs=1) # First argument -.add_argument('', type=, nargs='+') # Ramaining arguments +.add_argument('', type=, nargs='+') # Remaining arguments = .parse_args() value = . ``` From 1e920ac66621580a01ac9c79cf2bd75f4e28fd16 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:55:21 +0100 Subject: [PATCH 0019/1913] Splat --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index f91bd7ff4..b1fa623e2 100644 --- a/README.md +++ b/README.md @@ -450,9 +450,9 @@ def f() # def f(x=0, y=0) def f(, ) # def f(x, y=0) ``` -### Splat operator -**`'*'` is the splat operator, that takes a collection as input, and expands it into actual positional arguments in the function call.** - +Splat Operator +-------------- +### Inside Function Call ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -464,7 +464,8 @@ func(*args, **kwargs) func(1, 2, x=3, y=4, z=5) ``` -#### Splat example: +### Inside Function Definition +**It combines zero or more positional arguments into tuple.** ```python def add(*a): return sum(a) @@ -475,7 +476,7 @@ def add(*a): 6 ``` -### Legal Argument Definitions and Calls +#### Legal argument combinations and calls: ```python def f(*args) # f(1, 2, 3) def f(x, *args) # f(1, 2, 3) From 2c84fede119aeaf4f83675ff3b1c55420d787e66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 01:55:44 +0100 Subject: [PATCH 0020/1913] Splat --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b1fa623e2..3ec797d5a 100644 --- a/README.md +++ b/README.md @@ -450,6 +450,7 @@ def f() # def f(x=0, y=0) def f(, ) # def f(x, y=0) ``` + Splat Operator -------------- ### Inside Function Call From 6386f62aa8710a92c38c60267b495ee67c6f05ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 02:21:59 +0100 Subject: [PATCH 0021/1913] Splat --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3ec797d5a..8701be02c 100644 --- a/README.md +++ b/README.md @@ -454,6 +454,7 @@ def f(, ) # def f(x, y=0) Splat Operator -------------- ### Inside Function Call +**Splat expands collection into positional arguments, while splatty-splat expands dictionary into keyword arguments.** ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -466,7 +467,7 @@ func(1, 2, x=3, y=4, z=5) ``` ### Inside Function Definition -**It combines zero or more positional arguments into tuple.** +**Splat combines zero or more positional arguments into tuple, while splatty-splat combines zero or more keyword arguments into dictionary.** ```python def add(*a): return sum(a) From 9ba01b6b80a96c17967560338352516b5aafff28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 03:47:28 +0100 Subject: [PATCH 0022/1913] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 8701be02c..3124c0ed4 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,9 @@ value = .setdefault(key, default=None) # Same, but also adds default to ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from list of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two lists. - = dict.fromkeys(keys [, value]) # Initiates a dict from list of keys. + = dict() # Initiates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two collections. + = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. ``` ```python From 77e5e86e3d1cf357a669e9e379873cd1a4065bf5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 03:56:18 +0100 Subject: [PATCH 0023/1913] Counter, frozenset --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3124c0ed4..e75020141 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ value = .pop(key) # Removes item from dictionary. ### Counter ```python >>> from collections import Counter ->>> colors = ['blue', 'red', 'blue', 'yellow', 'blue', 'red'] +>>> colors = ['red', 'blue', 'yellow', 'blue', 'red', 'blue'] >>> counter = Counter(colors) Counter({'blue': 3, 'red': 2, 'yellow': 1}) >>> counter.most_common()[0] @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable so it can be used as a key in dictionary. +#### Is hashable, meaning it can be used as a key in dictionary. ```python = frozenset() ``` From 1f6f76b2954cbd7cf14e53e0bd14fac7d0fb378e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 04:46:07 +0100 Subject: [PATCH 0024/1913] Numbers --- README.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e75020141..e2d08bbc2 100644 --- a/README.md +++ b/README.md @@ -377,8 +377,8 @@ Format * **`'X'` - HEX** -Numbers -------- +Math +---- ### Basic Functions ```python = pow(, ) # Or: ** @@ -412,7 +412,9 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` -### Random + +Random +------ ```python from random import random, randint, choice, shuffle = random() @@ -478,7 +480,7 @@ def add(*a): 6 ``` -#### Legal argument combinations and calls: +#### Legal argument combinations with calls: ```python def f(*args) # f(1, 2, 3) def f(x, *args) # f(1, 2, 3) @@ -1424,7 +1426,7 @@ param_names = list(sig.parameters.keys()) ``` ### Type -**Type is the root class. If only passed the object it returns it's type. Otherwise it creates a new class (and not the instance!).** +**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** ```python = type(, , ) From dd64ffdf9a500987538d0ffdce7f77612e518c1a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 05:15:52 +0100 Subject: [PATCH 0025/1913] Numbers --- README.md | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e2d08bbc2..0c9b2c225 100644 --- a/README.md +++ b/README.md @@ -377,8 +377,8 @@ Format * **`'X'` - HEX** -Math ----- +Numbers +------- ### Basic Functions ```python = pow(, ) # Or: ** @@ -412,9 +412,7 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` - -Random ------- +### Random ```python from random import random, randint, choice, shuffle = random() From d3e2e93712e3a3a9da459973afd3eda76ffa948e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 05:38:04 +0100 Subject: [PATCH 0026/1913] Command line arguments --- README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 0c9b2c225..da94875b7 100644 --- a/README.md +++ b/README.md @@ -1018,13 +1018,13 @@ arguments = sys.argv[1:] ### Argparse ```python from argparse import ArgumentParser, FileType - = ArgumentParser(description=) -.add_argument('-', '--', action='store_true') # Flag -.add_argument('-', '--', type=) # Option -.add_argument('', type=, nargs=1) # First argument -.add_argument('', type=, nargs='+') # Remaining arguments - = .parse_args() -value = . +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. ``` * **Use `'help='` for argument description.** From 32b2b63c9b6bd70e10cc09ef8e622f0798304a50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 06:04:00 +0100 Subject: [PATCH 0027/1913] System --- README.md | 132 +++++++++++++++++++++++++++++------------------------- 1 file changed, 70 insertions(+), 62 deletions(-) diff --git a/README.md b/README.md index da94875b7..da44b286a 100644 --- a/README.md +++ b/README.md @@ -888,7 +888,7 @@ while True: break ``` -#### Raising exception: +### Raising Exception ```python raise ValueError('A very specific message!') ``` @@ -906,16 +906,15 @@ KeyboardInterrupt ``` -System ------- -### Print Function +Print +----- ```python print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) ``` * **Use `'file=sys.stderr'` for errors.** -#### Pretty print: +### Pretty Print ```python >>> from pprint import pprint >>> pprint(dir()) @@ -924,7 +923,9 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) '__doc__', ...] ``` -### Input Function + +Input +----- * **Reads a line from user input or pipe if present.** * **The trailing newline gets stripped.** * **The prompt string is printed to standard output before reading input.** @@ -942,14 +943,16 @@ while True: break ``` -### Open Function + +Open +---- **Opens file and returns a corresponding file object.** ```python = open('', mode='r', encoding=None) ``` -#### Modes: +### Modes * **`'r'` - Read (default).** * **`'w'` - Write (truncate).** * **`'x'` - Write or fail if the file already exists.** @@ -960,80 +963,30 @@ while True: * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** -#### Seek: +### Seek ```python .seek(0) # Move to start of the file. .seek(offset) # Move 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. ``` -#### Read Text from File: +### Read Text from File ```python def read_file(filename): with open(filename, encoding='utf-8') as file: return file.readlines() ``` -#### Write Text to File: +### Write Text to File ```python def write_to_file(filename, text): with open(filename, 'w', encoding='utf-8') as file: file.write(text) ``` -### Command Execution -```python -import os - = os.popen().read() -``` - -#### Or: -```python ->>> import subprocess ->>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) ->>> a.stdout -b'.\n..\nfile1.txt\nfile2.txt\n' ->>> a.returncode -0 -``` - -### Recursion Limit -```python ->>> import sys ->>> sys.getrecursionlimit() -1000 ->>> sys.setrecursionlimit(5000) -``` - - -Command Line Arguments ----------------------- -### Basic -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser, FileType -p = ArgumentParser(description=) -p.add_argument('-', '--', action='store_true') # Flag -p.add_argument('-', '--', type=) # Option -p.add_argument('', type=, nargs=1) # Argument -p.add_argument('', type=, nargs='+') # Arguments -args = p.parse_args() -value = args. -``` - -* **Use `'help='` for argument description.** -* **Use `'type=FileType()'` for files.** - Path ---- -### Basic ```python from os import path, listdir = path.exists('') @@ -1048,7 +1001,9 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` -### Pathlib + +Pathlib +------- **This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** ```python @@ -1080,6 +1035,59 @@ cwd = Path() ``` +Command Line Arguments +---------------------- +### Basic +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + +Command Execution +----------------- +```python +import os + = os.popen().read() +``` + +#### Or: +```python +>>> import subprocess +>>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) +>>> a.stdout +b'.\n..\nfile1.txt\nfile2.txt\n' +>>> a.returncode +0 +``` + + +Recursion Limit +--------------- +```python +>>> import sys +>>> sys.getrecursionlimit() +1000 +>>> sys.setrecursionlimit(5000) +``` + + JSON ---- ```python From 15c65ea368e42df26d095d0bdb30fa85d06c0bd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 17:48:39 +0100 Subject: [PATCH 0028/1913] Lambda, Closure --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index da44b286a..dcfcb48fb 100644 --- a/README.md +++ b/README.md @@ -300,7 +300,7 @@ import re ``` ### Special Sequences -**Expressions below hold true only for strings that contain only ASCII characters. Use capital letter for negation.** +**Expressions below hold true for strings that contain only ASCII characters. Use capital letter for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -516,8 +516,8 @@ Inline ------ ### Lambda ```python -lambda: -lambda , : + = lambda: + = lambda , : ``` ### Comprehension @@ -609,7 +609,7 @@ def get_multiplier(a): ### Partial ```python from functools import partial - = partial(, [, , ...]) + = partial( [, , , ...]) ``` ```python @@ -619,7 +619,7 @@ from functools import partial ``` ### Nonlocal -**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as 'global' or 'nonlocal'.** +**If variable is being assigned to anywhere in the scope, it is regarded as a local variable, unless it is declared as a 'global' or 'nonlocal'.** ```python def get_counter(): From 603a0964cdb59d23565caf45af62ac11306f10be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 24 Feb 2019 20:57:23 +0100 Subject: [PATCH 0029/1913] Small fixes --- README.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index dcfcb48fb..15cb66eaf 100644 --- a/README.md +++ b/README.md @@ -676,7 +676,7 @@ from functools import lru_cache @lru_cache(maxsize=None) def fib(n): - return n if n < 2 else fib(n-1) + fib(n-2) + return n if n < 2 else fib(n-2) + fib(n-1) ``` ### Parametrized Decorator @@ -927,8 +927,8 @@ print(, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Input ----- * **Reads a line from user input or pipe if present.** -* **The trailing newline gets stripped.** -* **The prompt string is printed to standard output before reading input.** +* **Trailing newline gets stripped.** +* **Prompt string is printed to the standard output before reading input.** ```python = input(prompt=None) @@ -958,14 +958,14 @@ Open * **`'x'` - Write or fail if the file already exists.** * **`'a'` - Append.** * **`'w+'` - Read and write (truncate).** -* **`'r+'` - Read and write from the beginning.** +* **`'r+'` - Read and write from the start.** * **`'a+'` - Read and write from the end.** * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** ### Seek ```python -.seek(0) # Move to start of the file. +.seek(0) # Move to the start of the file. .seek(offset) # Move 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. ``` @@ -1274,6 +1274,9 @@ from collections import deque ```python .appendleft() = .popleft() +``` + +```python .extendleft() # Collection gets reversed. .rotate(n=1) # Rotates elements to the right. ``` From f8bea86412e0e6c8b2c31e0805b51c5d95108d15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 15:09:31 +0100 Subject: [PATCH 0030/1913] Small fixes --- README.md | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 15cb66eaf..d92f3c03b 100644 --- a/README.md +++ b/README.md @@ -1166,7 +1166,7 @@ db.commit() Bytes ----- -**Bytes object is immutable sequence of single bytes. Mutable version is called bytearray.** +**Bytes object is immutable sequence of single bytes. Mutable version is called 'bytearray'.** ```python = b'' @@ -1178,7 +1178,7 @@ Bytes ### Encode ```python = .encode(encoding='utf-8') - = .to_bytes(length, byteorder='big|little', signed=False) + = .to_bytes(, byteorder='big|little', signed=False) = bytes.fromhex('') ``` @@ -1244,7 +1244,7 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03' Array ----- -**List that can only hold elements of predefined type. Available types are listed above.** +**List that can hold only elements of predefined type. Available types are listed above.** ```python from array import array @@ -1264,7 +1264,7 @@ Memory View Deque ----- -**A thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** +**Thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** ```python from collections import deque @@ -1349,8 +1349,8 @@ from itertools import * ### Infinite iterators ```python ->>> i = count(5, 2) ->>> next(i), next(i), next(i) +>>> a = count(5, 2) +>>> next(a), next(a), next(a) (5, 7, 9) >>> a = cycle('abc') @@ -1662,7 +1662,7 @@ def get_border(screen): Image ----- -#### Creates PNG image of greyscale gradient: +#### Creates PNG image of rainbow gradient: ```python # $ pip3 install pillow from PIL import Image @@ -1671,9 +1671,10 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img = Image.new('L', (width, height), 'white') -img.putdata(pixels) -img.save('test.png') +img_hsv = Image.new('HSV', (width, height), 'white') +img_hsv.putdata([(int(a), 255, 255) for a in pixels]) +img_rgb = img_hsv.convert(mode='RGB') +img_rgb.save('test.png') ``` ### Modes From 8706d140c3b6e84aa038af4630f300849451293f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 18:43:13 +0100 Subject: [PATCH 0031/1913] Statistics, CSV --- README.md | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index d92f3c03b..8efdb6d64 100644 --- a/README.md +++ b/README.md @@ -412,6 +412,11 @@ from math import inf, nan, isinf, isnan float('inf'), float('nan') ``` +### Statistics +```python +from statistics import mean, median, variance, pvariance, pstdev +``` + ### Random ```python from random import random, randint, choice, shuffle @@ -1088,6 +1093,28 @@ Recursion Limit ``` +CSV +--- +```python +import csv +``` + +### Read Rows from CSV File +```python +def read_csv_file(filename): + with open(filename, encoding='utf-8') as file: + return csv.reader(file, delimiter=';') +``` + +### Write Rows to CSV File +```python +def write_to_csv_file(filename, rows): + with open(filename, 'w', encoding='utf-8') as file: + writer = csv.writer(file, delimiter=';') + writer.writerows(rows) +``` + + JSON ---- ```python @@ -1366,8 +1393,8 @@ from itertools import * >>> chain([1, 2], range(3, 5)) [1, 2, 3, 4] ->>> compress('abc', [True, 0, 1]) -['a', 'c'] +>>> compress([1, 2, 3, 4], [True, False, 1, 0]) +[1, 3] >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3], 1, None) @@ -1468,8 +1495,7 @@ class MyMetaClass(type): ```python class MyClass(metaclass=MyMetaClass): - def __init__(self): - self.b = 12345 + b = 12345 ``` From 26d28ad47544a81cf873e621e6e925eff1b421b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:18:52 +0100 Subject: [PATCH 0032/1913] Pathlib --- README.md | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 8efdb6d64..f3c566205 100644 --- a/README.md +++ b/README.md @@ -1006,11 +1006,7 @@ from os import path, listdir ['1.gif', 'card.gif'] ``` - -Pathlib -------- -**This module offers classes representing filesystem paths with semantics appropriate for different operating systems.** - +### Pathlib ```python from pathlib import Path cwd = Path() @@ -1042,7 +1038,6 @@ cwd = Path() Command Line Arguments ---------------------- -### Basic ```python import sys script_name = sys.argv[0] @@ -1072,7 +1067,7 @@ import os = os.popen().read() ``` -#### Or: +### Subprocess ```python >>> import subprocess >>> a = subprocess.run(['ls', '-a'], stdout=subprocess.PIPE) From 6bf7d6ee9d60fe6466f5619c9bfdbfd141601114 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:23:18 +0100 Subject: [PATCH 0033/1913] Deck --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f3c566205..d3afffb2a 100644 --- a/README.md +++ b/README.md @@ -1286,7 +1286,7 @@ Memory View Deque ----- -**Thread-safe list with efficient appends and pops from either side. Pronounced “deck”.** +**Thread-safe list with efficient appends and pops from either side. Pronounced "deck".** ```python from collections import deque From 45b80ceaae56819e73bbda357234cac34f46ffce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 20:26:55 +0100 Subject: [PATCH 0034/1913] Iterators --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index d3afffb2a..2bf27cae3 100644 --- a/README.md +++ b/README.md @@ -1385,15 +1385,15 @@ from itertools import * ### Iterators ```python ->>> chain([1, 2], range(3, 5)) +>>> chain([1, 2], [3, 4]) [1, 2, 3, 4] >>> compress([1, 2, 3, 4], [True, False, 1, 0]) [1, 3] >>> # islice(, from_inclusive, to_exclusive) ->>> islice([1, 2, 3], 1, None) -[2, 3] +>>> islice([1, 2, 3, 4], 2, None) +[3, 4] ``` ### Group by From afab176f97fe241ae004fc89cca74dc2ceb7ad27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 25 Feb 2019 21:30:35 +0100 Subject: [PATCH 0035/1913] Arguments --- README.md | 48 ++++++++++++++++++++++++------------------------ 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 2bf27cae3..b5af873c6 100644 --- a/README.md +++ b/README.md @@ -949,6 +949,30 @@ while True: ``` +Command Line Arguments +---------------------- +```python +import sys +script_name = sys.argv[0] +arguments = sys.argv[1:] +``` + +### Argparse +```python +from argparse import ArgumentParser, FileType +p = ArgumentParser(description=) +p.add_argument('-', '--', action='store_true') # Flag +p.add_argument('-', '--', type=) # Option +p.add_argument('', type=, nargs=1) # Argument +p.add_argument('', type=, nargs='+') # Arguments +args = p.parse_args() +value = args. +``` + +* **Use `'help='` for argument description.** +* **Use `'type=FileType()'` for files.** + + Open ---- **Opens file and returns a corresponding file object.** @@ -1036,30 +1060,6 @@ cwd = Path() ``` -Command Line Arguments ----------------------- -```python -import sys -script_name = sys.argv[0] -arguments = sys.argv[1:] -``` - -### Argparse -```python -from argparse import ArgumentParser, FileType -p = ArgumentParser(description=) -p.add_argument('-', '--', action='store_true') # Flag -p.add_argument('-', '--', type=) # Option -p.add_argument('', type=, nargs=1) # Argument -p.add_argument('', type=, nargs='+') # Arguments -args = p.parse_args() -value = args. -``` - -* **Use `'help='` for argument description.** -* **Use `'type=FileType()'` for files.** - - Command Execution ----------------- ```python From 25cd360d2129e300ee8a1222bffbfad33e07d6df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:20:48 +0100 Subject: [PATCH 0036/1913] Image --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b5af873c6..1eb967505 100644 --- a/README.md +++ b/README.md @@ -1692,12 +1692,22 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img_hsv = Image.new('HSV', (width, height), 'white') +img_hsv = Image.new('HSV', (width, height)) img_hsv.putdata([(int(a), 255, 255) for a in pixels]) img_rgb = img_hsv.convert(mode='RGB') img_rgb.save('test.png') ``` +#### Adds noise to image: +```python +from random import randint +add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) +img = Image.open('test.png').convert(mode='HSV') +pixels = [(add_noise(h), s, v) for h, s, v in img.getdata()] +img.putdata(pixels) +img.convert(mode='RGB').save('test.png') +``` + ### Modes * **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.** * **`'L'` - 8-bit pixels, greyscale.** From 87835a6b1268f94dcf5b53e2c88d5da7c7e5f533 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:22:10 +0100 Subject: [PATCH 0037/1913] Image --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 1eb967505..743a1b8d9 100644 --- a/README.md +++ b/README.md @@ -1683,10 +1683,13 @@ def get_border(screen): Image ----- -#### Creates PNG image of rainbow gradient: ```python # $ pip3 install pillow from PIL import Image +``` + +#### Creates PNG image of rainbow gradient: +```python width = 100 height = 100 size = width * height From 15b70c58526b28bfea238d4ab9d3e89515a0de71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:23:02 +0100 Subject: [PATCH 0038/1913] Table --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 743a1b8d9..d833a5272 100644 --- a/README.md +++ b/README.md @@ -1648,8 +1648,8 @@ Table #### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate -import csv from tabulate import tabulate +import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') headers = [header.title() for header in next(lines)] From 0fe8be3c6677a45300ef172bf4f138e6f22ffdad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:31:08 +0100 Subject: [PATCH 0039/1913] Libraries --- README.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index d833a5272..75c908086 100644 --- a/README.md +++ b/README.md @@ -1624,6 +1624,9 @@ Progress Bar ```python # $ pip3 install tqdm from tqdm import tqdm +``` + +```python from time import sleep for i in tqdm([1, 2, 3]): sleep(0.2) @@ -1637,6 +1640,9 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot +``` + +```python pyplot.plot( [, , ...]) pyplot.savefig(, transparent=True) pyplot.show() @@ -1645,10 +1651,13 @@ pyplot.show() Table ----- -#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from tabulate import tabulate +``` + +#### Prints CSV file as ASCII table: +```python import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') @@ -1663,7 +1672,9 @@ Curses ```python # $ pip3 install curses from curses import wrapper +``` +```python def main(): wrapper(draw) @@ -1695,19 +1706,17 @@ height = 100 size = width * height pixels = [255 * i/size for i in range(size)] -img_hsv = Image.new('HSV', (width, height)) -img_hsv.putdata([(int(a), 255, 255) for a in pixels]) -img_rgb = img_hsv.convert(mode='RGB') -img_rgb.save('test.png') +img = Image.new('HSV', (width, height)) +img.putdata([(int(a), 255, 255) for a in pixels]) +img.convert(mode='RGB').save('test.png') ``` -#### Adds noise to image: +#### Adds noise to an image: ```python from random import randint add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) -img = Image.open('test.png').convert(mode='HSV') -pixels = [(add_noise(h), s, v) for h, s, v in img.getdata()] -img.putdata(pixels) +img = Image.open('test.png').convert(mode='HSV') +img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()]) img.convert(mode='RGB').save('test.png') ``` From b1408481b79880df2810f2ad9a6ef2e74fd2b83c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 00:34:41 +0100 Subject: [PATCH 0040/1913] Libraries --- README.md | 13 +------------ 1 file changed, 1 insertion(+), 12 deletions(-) diff --git a/README.md b/README.md index 75c908086..5bf11b84e 100644 --- a/README.md +++ b/README.md @@ -1624,9 +1624,6 @@ Progress Bar ```python # $ pip3 install tqdm from tqdm import tqdm -``` - -```python from time import sleep for i in tqdm([1, 2, 3]): sleep(0.2) @@ -1640,9 +1637,6 @@ Plot ```python # $ pip3 install matplotlib from matplotlib import pyplot -``` - -```python pyplot.plot( [, , ...]) pyplot.savefig(, transparent=True) pyplot.show() @@ -1651,13 +1645,10 @@ pyplot.show() Table ----- +#### Prints CSV file as ASCII table: ```python # $ pip3 install tabulate from tabulate import tabulate -``` - -#### Prints CSV file as ASCII table: -```python import csv with open(, encoding='utf-8') as file: lines = csv.reader(file, delimiter=';') @@ -1672,9 +1663,7 @@ Curses ```python # $ pip3 install curses from curses import wrapper -``` -```python def main(): wrapper(draw) From 71edb44bc2dcf9bd1b8a22806ebfc86095d5eb71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 02:34:08 +0100 Subject: [PATCH 0041/1913] Audio --- README.md | 63 +++++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 5bf11b84e..0e28b7647 100644 --- a/README.md +++ b/README.md @@ -1195,6 +1195,7 @@ Bytes = [] = [] = b''.join() + = list() ``` ### Encode @@ -1232,9 +1233,10 @@ Struct * **Machine’s native type sizes and byte order are used by default.** ```python -from struct import pack, unpack, calcsize +from struct import pack, unpack, iter_unpack, calcsize = pack('', [, , ...]) = unpack('', ) + = iter_unpack('', ) ``` ### Example @@ -1700,7 +1702,7 @@ img.putdata([(int(a), 255, 255) for a in pixels]) img.convert(mode='RGB').save('test.png') ``` -#### Adds noise to an image: +#### Adds noise to PNG image: ```python from random import randint add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) @@ -1719,21 +1721,50 @@ img.convert(mode='RGB').save('test.png') Audio ----- -#### Saves a list of floats with values between -1 and 1 to a WAV file: ```python -import wave, struct -samples_l = [struct.pack('] -samples_b = b''.join(samples_l) +import wave +from struct import pack, iter_unpack +``` + +### Read Frames from WAV File +```python +def read_wav_file(filename): + with wave.open(filename, 'rb') as wf: + frames = wf.readframes(wf.getnframes()) + return [a[0] for a in iter_unpack(' 2 else 0.125) get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) -samples_f = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) -samples_b = b''.join(struct.pack(' Date: Tue, 26 Feb 2019 02:46:05 +0100 Subject: [PATCH 0042/1913] Libraries --- README.md | 202 +++++++++++++++++++++++++++--------------------------- 1 file changed, 101 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 0e28b7647..0afd11919 100644 --- a/README.md +++ b/README.md @@ -1683,107 +1683,6 @@ def get_border(screen): ``` -Image ------ -```python -# $ pip3 install pillow -from PIL import Image -``` - -#### Creates PNG image of rainbow gradient: -```python -width = 100 -height = 100 -size = width * height -pixels = [255 * i/size for i in range(size)] - -img = Image.new('HSV', (width, height)) -img.putdata([(int(a), 255, 255) for a in pixels]) -img.convert(mode='RGB').save('test.png') -``` - -#### Adds noise to PNG image: -```python -from random import randint -add_noise = lambda value: max(0, min(255, value + randint(-20, 20))) -img = Image.open('test.png').convert(mode='HSV') -img.putdata([(add_noise(h), s, v) for h, s, v in img.getdata()]) -img.convert(mode='RGB').save('test.png') -``` - -### Modes -* **`'1'` - 1-bit pixels, black and white, stored with one pixel per byte.** -* **`'L'` - 8-bit pixels, greyscale.** -* **`'RGB'` - 3x8-bit pixels, true color.** -* **`'RGBA'` - 4x8-bit pixels, true color with transparency mask.** -* **`'HSV'` - 3x8-bit pixels, Hue, Saturation, Value color space.** - - -Audio ------ -```python -import wave -from struct import pack, iter_unpack -``` - -### Read Frames from WAV File -```python -def read_wav_file(filename): - with wave.open(filename, 'rb') as wf: - frames = wf.readframes(wf.getnframes()) - return [a[0] for a in iter_unpack(' 2 else 0.125) -get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) -frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) -frames_b = b''.join(struct.pack(' 2 else 0.125) +get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) +frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) +frames_b = b''.join(struct.pack(' Date: Tue, 26 Feb 2019 02:52:19 +0100 Subject: [PATCH 0043/1913] Image --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0afd11919..2095606f0 100644 --- a/README.md +++ b/README.md @@ -1982,7 +1982,7 @@ def write_to_wav_file(filename, frames_int): ```python from math import pi, sin sin_f = lambda i: sin(i * 2 * pi * 440 / 44100) -frames_f = (sin_f(a) for a in range(100000)) +frames_f = (sin_f(i) for i in range(100000)) frames_i = (int(a * 30000) for a in frames_f) write_to_wav_file('test.wav', frames_i) ``` From 4c81ed7c51a3e382e4cc5f4bca0a8664f830fd9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 02:56:32 +0100 Subject: [PATCH 0044/1913] Audio --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 2095606f0..c9ace2872 100644 --- a/README.md +++ b/README.md @@ -1981,8 +1981,7 @@ def write_to_wav_file(filename, frames_int): #### Saves a sine wave to a WAV file: ```python from math import pi, sin -sin_f = lambda i: sin(i * 2 * pi * 440 / 44100) -frames_f = (sin_f(i) for i in range(100000)) +frames_f = (sin(i * 2 * pi * 440 / 44100) for i in range(100000)) frames_i = (int(a * 30000) for a in frames_f) write_to_wav_file('test.wav', frames_i) ``` From d979cae986d253c256150d6647a378e81648d782 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:00:11 +0100 Subject: [PATCH 0045/1913] Audio --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index c9ace2872..7b0919f5b 100644 --- a/README.md +++ b/README.md @@ -1990,8 +1990,7 @@ write_to_wav_file('test.wav', frames_i) ```python from random import randint add_noise = lambda value: max(-32768, min(32768, value + randint(-500, 500))) -frames_i = read_wav_file('test.wav') -frames_i = (add_noise(a) for a in frames_i) +frames_i = (add_noise(a) for a in read_wav_file('test.wav')) write_to_wav_file('test.wav', frames_i) ``` From 8858d6c589be76466b0ca27a974c1ac59195b987 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:22:08 +0100 Subject: [PATCH 0046/1913] Splat --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7b0919f5b..6d17de8ee 100644 --- a/README.md +++ b/README.md @@ -485,8 +485,8 @@ def add(*a): #### Legal argument combinations with calls: ```python -def f(*args) # f(1, 2, 3) -def f(x, *args) # f(1, 2, 3) +def f(*args): # f(1, 2, 3) +def f(x, *args): # f(1, 2, 3) def f(*args, z) # f(1, 2, z=3) def f(x, *args, z) # f(1, 2, z=3) ``` From 00581d8f431fa8c0b6c095d807cf778ea4559691 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 03:23:23 +0100 Subject: [PATCH 0047/1913] Arguments --- README.md | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 6d17de8ee..b18b464e7 100644 --- a/README.md +++ b/README.md @@ -450,9 +450,9 @@ Arguments ### Inside Function Definition ```python -def f() # def f(x, y) -def f() # def f(x=0, y=0) -def f(, ) # def f(x, y=0) +def f(): # def f(x, y) +def f(): # def f(x=0, y=0) +def f(, ): # def f(x, y=0) ``` @@ -485,22 +485,22 @@ def add(*a): #### Legal argument combinations with calls: ```python -def f(*args): # f(1, 2, 3) -def f(x, *args): # f(1, 2, 3) -def f(*args, z) # f(1, 2, z=3) -def f(x, *args, z) # f(1, 2, z=3) +def f(*args): # f(1, 2, 3) +def f(x, *args): # f(1, 2, 3) +def f(*args, z): # f(1, 2, z=3) +def f(x, *args, z): # f(1, 2, z=3) ``` ```python -def f(**kwargs) # f(x=1, y=2, z=3) -def f(x, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(**kwargs): # f(x=1, y=2, z=3) +def f(x, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) ``` ```python -def f(*args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) -def f(x, *args, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) -def f(*args, y, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) -def f(x, *args, z, **kwargs) # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) +def f(*args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(x, *args, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) | f(1, 2, 3) +def f(*args, y, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) +def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3) ``` ### Other Uses From 63c547a4880df69b02f09c301b5519e2ffcbfcd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 26 Feb 2019 12:01:23 +0100 Subject: [PATCH 0048/1913] Audio --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index b18b464e7..be84d18b7 100644 --- a/README.md +++ b/README.md @@ -1968,17 +1968,17 @@ def read_wav_file(filename): ### Write Frames to WAV File ```python -def write_to_wav_file(filename, frames_int): +def write_to_wav_file(filename, frames_int, mono=True): frames_short = (pack(' Date: Tue, 26 Feb 2019 12:20:12 +0100 Subject: [PATCH 0049/1913] Itertools --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index be84d18b7..3421d127e 100644 --- a/README.md +++ b/README.md @@ -1390,12 +1390,12 @@ from itertools import * >>> chain([1, 2], [3, 4]) [1, 2, 3, 4] ->>> compress([1, 2, 3, 4], [True, False, 1, 0]) -[1, 3] - >>> # islice(, from_inclusive, to_exclusive) >>> islice([1, 2, 3, 4], 2, None) [3, 4] + +>>> compress([1, 2, 3, 4], [True, False, 1, 0]) +[1, 3] ``` ### Group by From d0feeee432ab307304de1bc5b928948b314dbcc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:04:03 +0100 Subject: [PATCH 0050/1913] Itertools split --- README.md | 141 +++++++++++++++++++++++++----------------------------- 1 file changed, 64 insertions(+), 77 deletions(-) diff --git a/README.md b/README.md index 3421d127e..0dcb93280 100644 --- a/README.md +++ b/README.md @@ -206,19 +206,46 @@ Generator **Convenient way to implement the iterator protocol.** ```python -def step(start, step_size): +def count(start, step): while True: yield start - start += step_size + start += step ``` ```python ->>> stepper = step(10, 2) ->>> next(stepper), next(stepper), next(stepper) +>>> counter = count(10, 2) +>>> next(counter), next(counter), next(counter) (10, 12, 14) ``` +Itertools +--------- +* **Every function returns an iterator and can accept any collection and/or iterator.** +* **If you want to print the iterator, you need to pass it to the list() function!** + +```python +from itertools import islice, count, repeat, cycle, chain +``` + +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) +``` + +```python + = count(start=0, step=1) # Counter. + = repeat( [, times]) # Returns element endlesly or times times. + = cycle() # Repeats the sequence indefinately. +``` + +```python + = chain(, [, ...]) # Empties sequences in order. + = chain.from_iterable() # Empties sequences inside a sequence in order. +``` + + Type ---- ```python @@ -427,6 +454,39 @@ shuffle() ``` +Combinatorics +------------- +* **Every function returns an iterator.** +* **If you want to print the iterator, you need to pass it to the list() function!** + +```python +from itertools import combinations, combinations_with_replacement, permutations, product +``` + +```python +>>> combinations('abc', 2) +[('a', 'b'), ('a', 'c'), ('b', 'c')] + +>>> combinations_with_replacement('abc', 2) +[('a', 'a'), ('a', 'b'), ('a', 'c'), + ('b', 'b'), ('b', 'c'), + ('c', 'c')] + +>>> permutations('abc', 2) +[('a', 'b'), ('a', 'c'), + ('b', 'a'), ('b', 'c'), + ('c', 'a'), ('c', 'b')] + +>>> product('ab', '12') +[('a', '1'), ('a', '2'), + ('b', '1'), ('b', '2')] + +>>> product([0, 1], repeat=3) +[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] +``` + + Datetime -------- ```python @@ -1338,79 +1398,6 @@ Hashlib ``` -Itertools ---------- -* **Every function returns an iterator and can accept any collection and/or iterator.** -* **If you want to print the iterator, you need to pass it to the list() function!** - -```python -from itertools import * -``` - -### Combinatoric iterators -```python ->>> combinations('abc', 2) -[('a', 'b'), ('a', 'c'), ('b', 'c')] - ->>> combinations_with_replacement('abc', 2) -[('a', 'a'), ('a', 'b'), ('a', 'c'), - ('b', 'b'), ('b', 'c'), - ('c', 'c')] - ->>> permutations('abc', 2) -[('a', 'b'), ('a', 'c'), - ('b', 'a'), ('b', 'c'), - ('c', 'a'), ('c', 'b')] - ->>> product('ab', '12') -[('a', '1'), ('a', '2'), - ('b', '1'), ('b', '2')] - ->>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), - (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] -``` - -### Infinite iterators -```python ->>> a = count(5, 2) ->>> next(a), next(a), next(a) -(5, 7, 9) - ->>> a = cycle('abc') ->>> [next(a) for _ in range(10)] -['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c', 'a'] - ->>> repeat(10, 3) -[10, 10, 10] -``` - -### Iterators -```python ->>> chain([1, 2], [3, 4]) -[1, 2, 3, 4] - ->>> # islice(, from_inclusive, to_exclusive) ->>> islice([1, 2, 3, 4], 2, None) -[3, 4] - ->>> compress([1, 2, 3, 4], [True, False, 1, 0]) -[1, 3] -``` - -### Group by -```python ->>> people = [{'id': 1, 'name': 'Bob'}, - {'id': 2, 'name': 'Bob'}, - {'id': 3, 'name': 'Peter'}] ->>> groups = groupby(people, key=lambda a: a['name']) ->>> {name: list(group) for name, group in groups} -{'Bob': [{'id': 1, 'name': 'Bob'}, - {'id': 2, 'name': 'Bob'}], - 'Peter': [{'id': 3, 'name': 'Peter'}]} -``` - - Introspection and Metaprograming -------------------------------- **Inspecting code at runtime and code that generates code. You can:** From 03cfac325353882804ac1cbdcb34fe355c996008 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:07:14 +0100 Subject: [PATCH 0051/1913] Itertools --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0dcb93280..ba9887566 100644 --- a/README.md +++ b/README.md @@ -235,14 +235,14 @@ from itertools import islice, count, repeat, cycle, chain ``` ```python - = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlesly or times times. - = cycle() # Repeats the sequence indefinately. + = count(start=0, step=1) # Counter. + = repeat( [, times]) # Returns element endlesly or times times. + = cycle() # Repeats the sequence indefinately. ``` ```python - = chain(, [, ...]) # Empties sequences in order. - = chain.from_iterable() # Empties sequences inside a sequence in order. + = chain(, ) # Empties sequences in order. + = chain.from_iterable() # Empties sequences inside a sequence in order. ``` From c0d91706bd274e05c425d2f17384cb2e779a767f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 13:09:09 +0100 Subject: [PATCH 0052/1913] Itertools --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ba9887566..f3de31fee 100644 --- a/README.md +++ b/README.md @@ -236,8 +236,8 @@ from itertools import islice, count, repeat, cycle, chain ```python = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlesly or times times. - = cycle() # Repeats the sequence indefinately. + = repeat( [, times]) # Returns element endlessly or times times. + = cycle() # Repeats the sequence indefinitely. ``` ```python From e31ad08fba6beb7cac899898bd4232ae421d56b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:36:49 +0100 Subject: [PATCH 0053/1913] Iterator --- README.md | 61 ++++++++++++++++++++++++------------------------------- 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index f3de31fee..fc4824370 100644 --- a/README.md +++ b/README.md @@ -169,11 +169,37 @@ Point(x=1, y=2) Iterator -------- +* **If you want to print the iterator, you need to pass it to the list() function.** +* **In this cheatsheet `''` can also mean an iterator.** + +```python +from itertools import islice, count, repeat, cycle, chain +``` + ```python = iter() - = iter(, to_exclusive) + = iter(, to_exclusive) # Sequence of return values until 'to_exclusive'. + = next( [, default]) # Raises StopIteration or returns 'default' on end. +``` + +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) ``` +```python + = count(start=0, step=1) # Returns incremented integer endlessly. + = repeat( [, times]) # Returns element endlessly or 'times' times. + = cycle() # Repeats the sequence indefinitely. +``` + +```python + = chain(, ) # Empties collections in order. + = chain.from_iterable() # Empties collections inside a collection in order. +``` + +### Examples #### Reads input until it reaches an empty line: ```python for line in iter(input, ''): @@ -187,12 +213,6 @@ for line in iter(partial(input, 'Please enter value: '), ''): ... ``` -### Next -**Returns next item. If there are no more items it raises StopIteration exception or returns default if specified.** -```python - = next( [, default]) -``` - #### Skips first item: ```python next() @@ -219,33 +239,6 @@ def count(start, step): ``` -Itertools ---------- -* **Every function returns an iterator and can accept any collection and/or iterator.** -* **If you want to print the iterator, you need to pass it to the list() function!** - -```python -from itertools import islice, count, repeat, cycle, chain -``` - -```python - = islice(, to_exclusive) - = islice(, from_inclusive, to_exclusive) - = islice(, from_inclusive, to_exclusive, step_size) -``` - -```python - = count(start=0, step=1) # Counter. - = repeat( [, times]) # Returns element endlessly or times times. - = cycle() # Repeats the sequence indefinitely. -``` - -```python - = chain(, ) # Empties sequences in order. - = chain.from_iterable() # Empties sequences inside a sequence in order. -``` - - Type ---- ```python From 06488408b93d666e1e31594c18aa6a444ec890b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:39:45 +0100 Subject: [PATCH 0054/1913] Iterator --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index fc4824370..86734a25a 100644 --- a/README.md +++ b/README.md @@ -182,12 +182,6 @@ from itertools import islice, count, repeat, cycle, chain = next( [, default]) # Raises StopIteration or returns 'default' on end. ``` -```python - = islice(, to_exclusive) - = islice(, from_inclusive, to_exclusive) - = islice(, from_inclusive, to_exclusive, step_size) -``` - ```python = count(start=0, step=1) # Returns incremented integer endlessly. = repeat( [, times]) # Returns element endlessly or 'times' times. @@ -199,6 +193,12 @@ from itertools import islice, count, repeat, cycle, chain = chain.from_iterable() # Empties collections inside a collection in order. ``` +```python + = islice(, to_exclusive) + = islice(, from_inclusive, to_exclusive) + = islice(, from_inclusive, to_exclusive, step_size) +``` + ### Examples #### Reads input until it reaches an empty line: ```python From 22b3590082466889e6754c63efa5b6a67b5b4213 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:43:34 +0100 Subject: [PATCH 0055/1913] Iterator --- README.md | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/README.md b/README.md index 86734a25a..355c11ed3 100644 --- a/README.md +++ b/README.md @@ -199,27 +199,6 @@ from itertools import islice, count, repeat, cycle, chain = islice(, from_inclusive, to_exclusive, step_size) ``` -### Examples -#### Reads input until it reaches an empty line: -```python -for line in iter(input, ''): - ... -``` - -#### Same, but prints a message every time: -```python -from functools import partial -for line in iter(partial(input, 'Please enter value: '), ''): - ... -``` - -#### Skips first item: -```python -next() -for element in : - ... -``` - Generator --------- From d9f36c4a55d8c1431d24a10696726abf48b19918 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 15:48:48 +0100 Subject: [PATCH 0056/1913] Combinatorics --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 355c11ed3..8289fb395 100644 --- a/README.md +++ b/README.md @@ -436,6 +436,14 @@ from itertools import combinations, combinations_with_replacement, permutations, ``` ```python +>>> product([0, 1], repeat=3) +[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), + (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] + +>>> product('ab', '12') +[('a', '1'), ('a', '2'), + ('b', '1'), ('b', '2')] + >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] @@ -448,14 +456,6 @@ from itertools import combinations, combinations_with_replacement, permutations, [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] - ->>> product('ab', '12') -[('a', '1'), ('a', '2'), - ('b', '1'), ('b', '2')] - ->>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), - (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` From 5d8e110a7d9725b5a7d118734f546f4b8d8edf8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:15:35 +0100 Subject: [PATCH 0057/1913] Named tuple --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 8289fb395..c40404278 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,9 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- +* **Tuple is an immutable and hashable list.** +* **Named tuple is a subclass of tuple with named elements.** + ```python >>> from collections import namedtuple >>> Point = namedtuple('Point', 'x y') From b95e902be0975d5b78ab3d2b6abedd473c089fe4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:20:41 +0100 Subject: [PATCH 0058/1913] Set --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c40404278..83a8237c4 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable, meaning it can be used as a key in dictionary. +#### Is hashable, meaning it can be used as a key in dictionary or element in set. ```python = frozenset() ``` From 52cc2c2b428f4fef3efe6a25dd15857f403d05c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:23:37 +0100 Subject: [PATCH 0059/1913] Set --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 83a8237c4..b24ff9a2f 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Set ``` ### Frozenset -#### Is hashable, meaning it can be used as a key in dictionary or element in set. +#### Is hashable, meaning it can be used as a key in dictionary or as an element in set. ```python = frozenset() ``` From 430ec62d7752fdbd2710d22b1b79e46684433d1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:26:34 +0100 Subject: [PATCH 0060/1913] Named tuple --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b24ff9a2f..4db6f3547 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- * **Tuple is an immutable and hashable list.** -* **Named tuple is a subclass of tuple with named elements.** +* **Named tuple is its subclass with named elements.** ```python >>> from collections import namedtuple From b82cd724cf9c3fd67b65008b015e0d6eda80d5e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:29:00 +0100 Subject: [PATCH 0061/1913] Dictionary --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4db6f3547..3909388d3 100644 --- a/README.md +++ b/README.md @@ -63,17 +63,17 @@ Dictionary ``` ```python -value = .get(key, default=None) # Returns default if key does not exist. -value = .setdefault(key, default=None) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. +value = .get(key, default=None) # Returns default if key does not exist. +value = .setdefault(key, default=None) # Same, but also adds default to dict. + = collections.defaultdict() # Creates a dictionary with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. ``` ```python -.update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two collections. - = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. +.update() # Or: dict_a = {**dict_a, **dict_b}. + = dict() # Initiates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Initiates a dict from two collections. + = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. ``` ```python From a51363ab5f3e881df1781bfdb4bde0d102172d99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:35:48 +0100 Subject: [PATCH 0062/1913] Dict --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 3909388d3..5f58833bd 100644 --- a/README.md +++ b/README.md @@ -65,15 +65,15 @@ Dictionary ```python value = .get(key, default=None) # Returns default if key does not exist. value = .setdefault(key, default=None) # Same, but also adds default to dict. - = collections.defaultdict() # Creates a dictionary with default value of type. - = collections.defaultdict(lambda: 1) # Creates a dictionary with default value 1. + = collections.defaultdict() # Creates a dict with default value of type. + = collections.defaultdict(lambda: 1) # Creates a dict with default value 1. ``` ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Initiates a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Initiates a dict from two collections. - = dict.fromkeys(keys [, value]) # Initiates a dict from collection of keys. + = dict() # Inits a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Inits a dict from two collections. + = dict.fromkeys(keys [, value]) # Inits a dict from collection of keys. ``` ```python From 902fa3735b4d14a733e65086c7974ce3e0a9962d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:37:48 +0100 Subject: [PATCH 0063/1913] Dict --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5f58833bd..41d4313b2 100644 --- a/README.md +++ b/README.md @@ -71,9 +71,9 @@ value = .setdefault(key, default=None) # Same, but also adds default to ```python .update() # Or: dict_a = {**dict_a, **dict_b}. - = dict() # Inits a dict from coll. of key-value pairs. - = dict(zip(keys, values)) # Inits a dict from two collections. - = dict.fromkeys(keys [, value]) # Inits a dict from collection of keys. + = dict() # Creates a dict from coll. of key-value pairs. + = dict(zip(keys, values)) # Creates a dict from two collections. + = dict.fromkeys(keys [, value]) # Creates a dict from collection of keys. ``` ```python From b66c38f12d53c8d494bccb221e43cd49bf3a2476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:42:20 +0100 Subject: [PATCH 0064/1913] Iterator --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 41d4313b2..94acf6230 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ from itertools import islice, count, repeat, cycle, chain ``` ```python - = count(start=0, step=1) # Returns incremented integer endlessly. + = count(start=0, step=1) # Returns incremented value endlessly. = repeat( [, times]) # Returns element endlessly or 'times' times. = cycle() # Repeats the sequence indefinitely. ``` From d19dcb7b4bd520f1d5c24907038f5bfe95a42a84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:46:56 +0100 Subject: [PATCH 0065/1913] Combinatorics --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 94acf6230..689b2abf0 100644 --- a/README.md +++ b/README.md @@ -435,7 +435,7 @@ Combinatorics * **If you want to print the iterator, you need to pass it to the list() function!** ```python -from itertools import combinations, combinations_with_replacement, permutations, product +from itertools import product, combinations, combinations_with_replacement, permutations ``` ```python From f87dbfecc97a9a8ad6bc7af3c4db523a2b643f55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:49:15 +0100 Subject: [PATCH 0066/1913] Partial --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 689b2abf0..975f2003e 100644 --- a/README.md +++ b/README.md @@ -649,7 +649,7 @@ def get_multiplier(a): ### Partial ```python from functools import partial - = partial( [, , , ...]) + = partial( [, , , ...]) ``` ```python From fac6b3a090683181f55cc62d9e4b3a5c97a7201b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:56:24 +0100 Subject: [PATCH 0067/1913] Bytes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 975f2003e..6dfb4518d 100644 --- a/README.md +++ b/README.md @@ -1229,8 +1229,8 @@ Bytes = b'' = [] = [] - = b''.join() = list() + = b''.join() ``` ### Encode From 83a6ee2b38a0d26e4f837eec21b034742ad37325 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 16:58:19 +0100 Subject: [PATCH 0068/1913] Struct --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6dfb4518d..f8826260c 100644 --- a/README.md +++ b/README.md @@ -1269,9 +1269,9 @@ Struct ```python from struct import pack, unpack, iter_unpack, calcsize - = pack('', [, , ...]) - = unpack('', ) - = iter_unpack('', ) + = pack('', [, , ...]) + = unpack('', ) + = iter_unpack('', ) ``` ### Example From e40d97c53852415c8c28a0d9c0463f1ee48f3e64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:05:57 +0100 Subject: [PATCH 0069/1913] Attributes --- README.md | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index f8826260c..319f830dd 100644 --- a/README.md +++ b/README.md @@ -1391,25 +1391,10 @@ Introspection and Metaprograming ### Attributes ```python -class Z: - def __init__(self): - self.a = 'abcde' - self.b = 12345 -``` - -```python ->>> z = Z() - ->>> vars(z) -{'a': 'abcde', 'b': 12345} - ->>> getattr(z, 'a') -'abcde' - ->>> hasattr(z, 'c') -False - ->>> setattr(z, 'c', 10) + = vars() + = hasattr(, '') +value = getattr(, '') +setattr(, '', value) ``` ### Parameters From 1a95bf50a6d35f6647eb8f3dbc6bac62a754c3b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:15:42 +0100 Subject: [PATCH 0070/1913] Metaclass --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 319f830dd..e84aa071f 100644 --- a/README.md +++ b/README.md @@ -1442,6 +1442,11 @@ class MyClass(metaclass=MyMetaClass): b = 12345 ``` +```python +>>> MyClass.a, MyClass.b +('abcde', 12345) +``` + Operator -------- From 40c4567c038c2c400a0562572f0bb798bb414a87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:19:39 +0100 Subject: [PATCH 0071/1913] Introspection --- README.md | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e84aa071f..97186bb30 100644 --- a/README.md +++ b/README.md @@ -1373,15 +1373,8 @@ Hashlib ``` -Introspection and Metaprograming --------------------------------- -**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** - +Introspection +------------- ### Variables ```python = dir() # Names of in-scope variables. @@ -1405,6 +1398,9 @@ no_of_params = len(sig.parameters) param_names = list(sig.parameters.keys()) ``` + +Metaprograming +-------------- ### Type **Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** From 36e8dcfcb2f071bf52a43e2fc3e2864918980f78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:21:11 +0100 Subject: [PATCH 0072/1913] Metaprograming --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 97186bb30..629cf1cce 100644 --- a/README.md +++ b/README.md @@ -1401,6 +1401,8 @@ param_names = list(sig.parameters.keys()) Metaprograming -------------- +**Code that generates code.** + ### Type **Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** From af62638851cf524b4cc348bcae34fd0f0855f4a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 17:22:43 +0100 Subject: [PATCH 0073/1913] Introspection --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 629cf1cce..ebaaab8e7 100644 --- a/README.md +++ b/README.md @@ -1375,6 +1375,8 @@ Hashlib Introspection ------------- +**Inspecting code at runtime.** + ### Variables ```python = dir() # Names of in-scope variables. From b96348a8e5b03682d234e59b424be66037cf2c89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 18:44:37 +0100 Subject: [PATCH 0074/1913] Format --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ebaaab8e7..a77dffd3e 100644 --- a/README.md +++ b/README.md @@ -318,7 +318,7 @@ Format ``` ```python ->>> Person = namedtuple('Person', 'name height') +>>> Person = collections.namedtuple('Person', 'name height') >>> person = Person('Jean-Luc', 187) >>> f'{person.height}' '187' From 00c3cc90396edf62335d7e17cc8faf18e3e14f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 18:58:13 +0100 Subject: [PATCH 0075/1913] Map --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a77dffd3e..5c9596b6a 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ for i in range(10): ``` ### Map, Filter, Reduce -```python +```python3 from functools import reduce = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) From e7c6560e7875bdf29b5d6b9ef029b47ac8b4b996 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Wed, 27 Feb 2019 19:00:42 +0100 Subject: [PATCH 0076/1913] Map --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5c9596b6a..a77dffd3e 100644 --- a/README.md +++ b/README.md @@ -581,7 +581,7 @@ for i in range(10): ``` ### Map, Filter, Reduce -```python3 +```python from functools import reduce = map(lambda x: x + 1, range(10)) # (1, 2, ..., 10) = filter(lambda x: x > 5, range(10)) # (6, 7, 8, 9) From d27d675784c4c86a009211865ac29fcf9fcb3ce1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 1 Mar 2019 04:03:42 +0100 Subject: [PATCH 0077/1913] String --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a77dffd3e..af08aa877 100644 --- a/README.md +++ b/README.md @@ -240,8 +240,8 @@ from numbers import Number, Integral, Real, Rational, Complex String ------ ```python - = .strip() # Strips all whitespace characters from both ends. - = .strip('') # Strips all passed characters from both ends. + = .strip() # Strips all whitespace characters from both ends. + = .strip('') # Strips all passed characters from both ends. ``` ```python @@ -251,12 +251,15 @@ String ``` ```python - = .replace(old_str, new_str) - = .startswith() # Pass tuple of strings for multiple options. - = .endswith() # Pass tuple of strings for multiple options. - = .index() # Returns start index of first match. - = .isnumeric() # True if str contains only numeric characters. - = textwrap.wrap(, width) # Nicely breaks string into lines. + = .replace(old, new [, count]) # Replaces 'old' with 'new' at most 'count' times. + = .startswith() # Pass tuple of strings for multiple options. + = .endswith() # Pass tuple of strings for multiple options. + = .index() # Returns start index of first match. +``` + +```python + = .isnumeric() # True if str contains only numeric characters. + = textwrap.wrap(, width) # Nicely breaks string into lines. ``` ### Char From fad0ada17c3819ae5508697067ddf2fa23f0f78f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Mar 2019 02:50:59 +0100 Subject: [PATCH 0078/1913] Minor fixes --- README.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index af08aa877..e455dd559 100644 --- a/README.md +++ b/README.md @@ -131,8 +131,7 @@ Range ```python = range(to_exclusive) = range(from_inclusive, to_exclusive) - = range(from_inclusive, to_exclusive, step_size) - = range(from_inclusive, to_exclusive, -step_size) + = range(from_inclusive, to_exclusive, ±step_size) ``` ```python @@ -172,11 +171,10 @@ Point(x=1, y=2) Iterator -------- -* **If you want to print the iterator, you need to pass it to the list() function.** -* **In this cheatsheet `''` can also mean an iterator.** +**In this cheatsheet `''` can also mean an iterator.** ```python -from itertools import islice, count, repeat, cycle, chain +from itertools import count, repeat, cycle, chain, islice ``` ```python @@ -228,7 +226,7 @@ Type ``` ```python -from numbers import Number, Integral, Real, Rational, Complex +from numbers import Integral, Rational, Real, Complex, Number = isinstance(, Number) ``` @@ -388,7 +386,8 @@ Numbers ```python = pow(, ) # Or: ** = abs() - = round( [, ndigits]) + = round() + = round(, ±ndigits) ``` ### Constants From 6d4aa978a811228ce19704bf5584d252bedff49f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 2 Mar 2019 23:57:15 +0100 Subject: [PATCH 0079/1913] Small updates --- README.md | 75 +++++++++++++++++++++---------------------------------- 1 file changed, 28 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index e455dd559..c49d27a20 100644 --- a/README.md +++ b/README.md @@ -390,32 +390,14 @@ Numbers = round(, ±ndigits) ``` -### Constants +### Math ```python from math import e, pi -``` - -### Trigonometry -```python from math import cos, acos, sin, asin, tan, atan, degrees, radians -``` - -### Logarithm -```python from math import log, log10, log2 - = log( [, base]) # Base e, if not specified. -``` - -### Infinity, nan -```python from math import inf, nan, isinf, isnan ``` -#### Or: -```python -float('inf'), float('nan') -``` - ### Statistics ```python from statistics import mean, median, variance, pvariance, pstdev @@ -444,19 +426,27 @@ from itertools import product, combinations, combinations_with_replacement, perm >>> product([0, 1], repeat=3) [(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] +``` +```python >>> product('ab', '12') [('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')] +``` +```python >>> combinations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'c')] +``` +```python >>> combinations_with_replacement('abc', 2) [('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'b'), ('b', 'c'), ('c', 'c')] +``` +```python >>> permutations('abc', 2) [('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'c'), @@ -469,9 +459,9 @@ Datetime ```python from datetime import datetime now = datetime.now() -now.month # 3 -now.strftime('%Y%m%d') # '20180315' -now.strftime('%Y%m%d%H%M%S') # '20180315002834' +now.month # 3 +now.strftime('%Y%m%d') # '20180315' +now.strftime('%Y%m%d%H%M%S') # '20180315002834' = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') ``` @@ -520,7 +510,7 @@ def add(*a): 6 ``` -#### Legal argument combinations with calls: +#### Legal argument combinations: ```python def f(*args): # f(1, 2, 3) def f(x, *args): # f(1, 2, 3) @@ -542,15 +532,14 @@ def f(x, *args, z, **kwargs): # f(x=1, y=2, z=3) | f(1, y=2, z=3) | f(1, 2, z=3 ### Other Uses ```python ->>> a = (1, 2, 3) ->>> [*a] -[1, 2, 3] + = [* [, ...]] + = {* [, ...]} + = (*, [...]) + = {** [, ...]} ``` ```python ->>> head, *body, tail = [1, 2, 3, 4] ->>> body -[2, 3] +head, *body, tail = ``` @@ -566,8 +555,8 @@ Inline ```python = [i+1 for i in range(10)] # [1, 2, ..., 10] = {i for i in range(10) if i > 5} # {6, 7, 8, 9} - = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} = (i+5 for i in range(10)) # (5, 6, ..., 14) + = {i: i*2 for i in range(10)} # {0: 0, 1: 2, ..., 9: 18} ``` ```python @@ -665,11 +654,11 @@ from functools import partial ```python def get_counter(): - a = 0 + i = 0 def out(): - nonlocal a - a += 1 - return a + nonlocal i + i += 1 + return i return out ``` @@ -721,6 +710,8 @@ def fib(n): return n if n < 2 else fib(n-2) + fib(n-1) ``` +* **Recursion depth is limited to 1000 by default. To increase it use `'sys.setrecursionlimit()'`.** + ### Parametrized Decorator ```python from functools import wraps @@ -839,8 +830,8 @@ class Counter: ``` ```python ->>> c = Counter() ->>> c(), c(), c() +>>> counter = Counter() +>>> counter(), counter(), counter() (1, 2, 3) ``` @@ -1115,16 +1106,6 @@ b'.\n..\nfile1.txt\nfile2.txt\n' ``` -Recursion Limit ---------------- -```python ->>> import sys ->>> sys.getrecursionlimit() -1000 ->>> sys.setrecursionlimit(5000) -``` - - CSV --- ```python @@ -1633,7 +1614,7 @@ def get_border(screen): from collections import namedtuple P = namedtuple('P', 'x y') height, width = screen.getmaxyx() - return P(width - 1, height - 1) + return P(width-1, height-1) ``` From 4c3cb26fc78e9f92030fd5e2f67240b8f1b6aa01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 3 Mar 2019 12:43:51 +0100 Subject: [PATCH 0080/1913] Few changes --- README.md | 57 +++++++++++++++++++++++-------------------------------- 1 file changed, 24 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index c49d27a20..a8817f61d 100644 --- a/README.md +++ b/README.md @@ -1347,15 +1347,6 @@ lock.release() ``` -Hashlib -------- -```python ->>> import hashlib ->>> hashlib.md5(.encode()).hexdigest() -'33d0eba106da4d3ebca17fcd3f4c3d77' -``` - - Introspection ------------- **Inspecting code at runtime.** @@ -1389,7 +1380,7 @@ Metaprograming **Code that generates code.** ### Type -**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class (and not an instance!).** +**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class.** ```python = type(, , ) @@ -1434,17 +1425,17 @@ class MyClass(metaclass=MyMetaClass): Operator -------- ```python -from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs, \ - eq, ne, lt, le, gt, ge, \ - not_, and_, or_, \ - itemgetter, attrgetter, methodcaller +from operator import add, sub, mul, truediv, floordiv, mod, pow, neg, abs +from operator import eq, ne, lt, le, gt, ge +from operator import not_, and_, or_ +from operator import itemgetter, attrgetter, methodcaller ``` ```python import operator as op -product_of_elems = functools.reduce(op.mul, ) -sorted_by_second = sorted(, key=op.itemgetter(1)) -sorted_by_both = sorted(, key=op.itemgetter(1, 0)) +product_of_elems = functools.reduce(op.mul, ) +sorted_by_second = sorted(, key=op.itemgetter(1)) +sorted_by_both = sorted(, key=op.itemgetter(1, 0)) LogicOp = enum.Enum('LogicOp', {'AND': op.and_, 'OR' : op.or_}) last_el = op.methodcaller('pop')() ``` @@ -1459,7 +1450,7 @@ Eval 3 >>> literal_eval('[1, 2, 3]') [1, 2, 3] ->>> ast.literal_eval('abs(1)') +>>> literal_eval('abs(1)') ValueError: malformed node or string ``` @@ -1469,13 +1460,13 @@ import ast from ast import Num, BinOp, UnaryOp import operator as op -LEGAL_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} +LEGAL_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 evaluate(expression): root = ast.parse(expression, mode='eval') @@ -1679,7 +1670,7 @@ def odds_handler(sport): ```python # $ pip3 install requests >>> import requests ->>> url = 'http://localhost:8080/odds/football' +>>> url = 'http://localhost:8080/odds/football' >>> data = {'team': 'arsenal f.c.'} >>> response = requests.post(url, data=data) >>> response.json() @@ -1771,12 +1762,12 @@ import numpy as np ``` ```python - = .sum() -indexes = .argmin() + = .sum(axis=None) +indexes = .argmin(axis=None) ``` * **Shape is a tuple of dimension sizes.** -* **Axis is an index of dimension that gets collapsed.** +* **Axis is an index of dimension that gets collapsed. Leftmost dimension has index 0.** ### Indexing ```bash @@ -1806,7 +1797,7 @@ left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [ 0.1 , 0.6 , 0.8 ] # Shape: (3) ``` -#### 1. If array shapes differ, left-pad the smaller shape with ones: +#### 1. If array shapes differ in length, left-pad the smaller shape with ones: ```python left = [[0.1], [0.6], [0.8]] # Shape: (3, 1) right = [[0.1 , 0.6 , 0.8]] # Shape: (1, 3) <- ! @@ -1931,7 +1922,7 @@ write_to_wav_file('test.wav', frames_i) #### Plays Popcorn: ```python -# pip3 install simpleaudio +# $ pip3 install simpleaudio import simpleaudio, math, struct from itertools import chain, repeat F = 44100 @@ -1940,8 +1931,8 @@ P2 = '71♪,73,,74♪,73,,74,,71,,73♪,71,,73,,69,,71♪,69,,71,,67,,71♪,,,' get_pause = lambda seconds: repeat(0, int(seconds * F)) sin_f = lambda i, hz: math.sin(i * 2 * math.pi * hz / F) get_wave = lambda hz, seconds: (sin_f(i, hz) for i in range(int(seconds * F))) -get_hz = lambda n: 8.176 * 2 ** (int(n) / 12) -parse_n = lambda note: (get_hz(note[:2]), 0.25 if len(note) > 2 else 0.125) +get_hz = lambda key: 8.176 * 2 ** (int(key) / 12) +parse_n = lambda note: (get_hz(note[:2]), 0.25 if '♪' in note else 0.125) get_note = lambda note: get_wave(*parse_n(note)) if note else get_pause(0.125) frames_i = chain.from_iterable(get_note(n) for n in f'{P1}{P1}{P2}'.split(',')) frames_b = b''.join(struct.pack(' Date: Tue, 5 Mar 2019 19:36:34 +0100 Subject: [PATCH 0081/1913] Json, Numpy --- README.md | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a8817f61d..98d33fb3c 100644 --- a/README.md +++ b/README.md @@ -1136,12 +1136,6 @@ import json = json.loads() ``` -#### To preserve order use: -```python -from collections import OrderedDict - = json.loads(, object_pairs_hook=OrderedDict) -``` - ### Read Object from JSON File ```python def read_json_file(filename): @@ -1762,8 +1756,8 @@ import numpy as np ``` ```python - = .sum(axis=None) -indexes = .argmin(axis=None) + = .sum(axis) +indexes = .argmin(axis) ``` * **Shape is a tuple of dimension sizes.** From 8e1629550499b9c1c48ef5ab50b83a59748eb45e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Mar 2019 00:15:59 +0100 Subject: [PATCH 0082/1913] Minor fixes --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 98d33fb3c..d9371fcce 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- * **Tuple is an immutable and hashable list.** -* **Named tuple is its subclass with named elements.** +* **Named tuple is it's subclass with named elements.** ```python >>> from collections import namedtuple @@ -1744,7 +1744,7 @@ import numpy as np ```python = np.array() - = np.arange(from_inclusive, to_exclusive, step_size) + = np.arange(from_inclusive, to_exclusive, ±step_size) = np.ones() = np.random.randint(from_inclusive, to_exclusive, ) ``` From 5be679ae82d210af13087c4f224d101556f0ec11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Mar 2019 01:13:02 +0100 Subject: [PATCH 0083/1913] Grammar --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d9371fcce..4b739b8ad 100644 --- a/README.md +++ b/README.md @@ -151,7 +151,7 @@ for i, el in enumerate( [, i_start]): Named Tuple ----------- * **Tuple is an immutable and hashable list.** -* **Named tuple is it's subclass with named elements.** +* **Named tuple is its subclass with named elements.** ```python >>> from collections import namedtuple @@ -290,7 +290,7 @@ import re * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** * **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** -* **Use `r'\1'` or `'\\\\1'` for backreference.** +* **Use `r'\1'` or `'\\1'` for backreference.** * **Use `'?'` to make operator non-greedy.** ### Match Object @@ -303,7 +303,7 @@ import re ``` ### Special Sequences -**Expressions below hold true for strings that contain only ASCII characters. Use capital letter for negation.** +**Expressions below hold true for strings that contain only ASCII characters. Use capital letters for negation.** ```python '\d' == '[0-9]' # Digit '\s' == '[ \t\n\r\f\v]' # Whitespace @@ -486,7 +486,7 @@ def f(, ): # def f(x, y=0) Splat Operator -------------- ### Inside Function Call -**Splat expands collection into positional arguments, while splatty-splat expands dictionary into keyword arguments.** +**Splat expands a collection into positional arguments, while splatty-splat expands a dictionary into keyword arguments.** ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} @@ -499,7 +499,7 @@ func(1, 2, x=3, y=4, z=5) ``` ### Inside Function Definition -**Splat combines zero or more positional arguments into tuple, while splatty-splat combines zero or more keyword arguments into dictionary.** +**Splat combines zero or more positional arguments into a tuple, while splatty-splat combines zero or more keyword arguments into a dictionary.** ```python def add(*a): return sum(a) @@ -784,7 +784,7 @@ class MyComparable: ``` ### Hashable -* **Hashable object needs both hash() and eq() methods and it's hash value should never change.** +* **Hashable object needs both hash() and eq() methods and its hash value should never change.** * **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.** * **That is why Python automatically makes classes unhashable if you only implement eq().** @@ -1200,7 +1200,7 @@ db.commit() Bytes ----- -**Bytes object is immutable sequence of single bytes. Mutable version is called 'bytearray'.** +**Bytes object is an immutable sequence of single bytes. Mutable version is called 'bytearray'.** ```python = b'' @@ -1374,7 +1374,7 @@ Metaprograming **Code that generates code.** ### Type -**Type is the root class. If only passed the object it returns it's type (class). Otherwise it creates a new class.** +**Type is the root class. If only passed the object it returns its type (class). Otherwise it creates a new class.** ```python = type(, , ) From e36fecff3fbbc6f8fba39be215c202772a36f54c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Mar 2019 23:22:41 +0100 Subject: [PATCH 0084/1913] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b739b8ad..48e00c382 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ String ```python = .split() # Splits on any whitespace character. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .join() # Joins elements using string as separator. + = .join() # Joins string elements using str as separator. ``` ```python From cfe6b41b336f4469c50508f568facdad8035e735 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Mar 2019 23:27:50 +0100 Subject: [PATCH 0085/1913] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 48e00c382..4b739b8ad 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ String ```python = .split() # Splits on any whitespace character. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .join() # Joins string elements using str as separator. + = .join() # Joins elements using string as separator. ``` ```python From 72fbd93be86ff3468c28d5f3658524a6bfb4aa48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Thu, 7 Mar 2019 23:29:33 +0100 Subject: [PATCH 0086/1913] String --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4b739b8ad..a061b3e8d 100644 --- a/README.md +++ b/README.md @@ -245,7 +245,7 @@ String ```python = .split() # Splits on any whitespace character. = .split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times. - = .join() # Joins elements using string as separator. + = .join() # Joins elements using string as separator. ``` ```python From 6638c9e9422f372052859f035a2058e8df77b3db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 8 Mar 2019 13:01:59 +0100 Subject: [PATCH 0087/1913] Curses --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index a061b3e8d..c8f65397c 100644 --- a/README.md +++ b/README.md @@ -1583,7 +1583,6 @@ with open(, encoding='utf-8') as file: Curses ------ ```python -# $ pip3 install curses from curses import wrapper def main(): From d4d979eebb4110d06674e4ab1f0704cb1afb763c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 00:53:02 +0100 Subject: [PATCH 0088/1913] Datetime overhaul --- README.md | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index c8f65397c..1b11e6e5b 100644 --- a/README.md +++ b/README.md @@ -456,13 +456,76 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- +* **Module Datetime provides Date (`''`), Time (`''`) and Datetime (`'
'`) classes.** +* **Time and Datetime can be 'aware' (`''`), meaning they have defined timezone, or 'naive' (`''`), meaning they don't. + ```python -from datetime import datetime -now = datetime.now() -now.month # 3 -now.strftime('%Y%m%d') # '20180315' -now.strftime('%Y%m%d%H%M%S') # '20180315002834' - = datetime.strptime('2015-05-12 00:39', '%Y-%m-%d %H:%M') +$ pip3 install pytz +from datetime import date, time, datetime, timedelta +import pytz +``` + +### Constructors +```python + = date(year, month, day) + = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) +
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) + = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) +``` +* **`'fold=1'` means second pass in case of time jumping back for one hour.** +* **Use `'.weekday()'` to get day of the week (Mon == 0). + +### Now +```python + = date.today() # Current local date. + = datetime.today() # Naive datetime from current local time. + = datetime.utcnow() # Naive datetime from current UTC time. + = datetime.now() # Aware datetime from current time. +``` + +### Encode +```python + = D/T/DT.fromisoformat() # From 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. +
= DT.strptime(, '') # Datetime from string according to 'format'. + = D/DT.fromordinal() # Date or datetime from days since Christ. + = D/DT.fromtimestamp() # Date or datetime from seconds since Epoch in local time. + = DT.utcfromtimestamp() # Naive datetime from seconds since Epoch in UTC time. + = DT.fromtimestamp(, ) # Aware datetime from seconds since Epoch in time. +``` +* **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** + +### Decode +```python + = .isoformat() # 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. + = .strftime('') # Returns customized string representation. + = .toordinal() # Returns days since Christ ignoring time and timezone. + =
.timestamp() # Returns seconds since Epoch in local time or if set. +``` + +### Format +```python +>>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') +``` + +#### Rest of the options: +* **`'y'` - Year, 2 digits** +* **`'b'` - Month, abbreviated name** +* **`'B'` - Month, full name** +* **`'a'` - Weekday, abbreviated name** +* **`'A'` - Weekday, full name** +* **`'I'` - Hours, 2 digits, 12 hours** +* **`'p'` - AM/PM** +* **`'f'` - Microseconds, 6 digits** +* **`'z'` - Timezone offset, ± and 4 digits** +* **`'Z'` - Timezone name** + +### Timezone +```python + = pytz.timezone('/') # Use 'pytz.utc' for UTC. + =
.astimezone() # Converts datetime to passed timezone. + = .replace(tzinfo=) # Changes timezone without conversion. + = .utcoffset() # Returns timezone's current offset from UTC. + = .dst() # Returns daylight saving time offset. ``` From 6bed9731b35058b1c789f61d996733415c0c6d83 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 00:54:38 +0100 Subject: [PATCH 0089/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1b11e6e5b..ebc577adb 100644 --- a/README.md +++ b/README.md @@ -457,7 +457,7 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- * **Module Datetime provides Date (`''`), Time (`''`) and Datetime (`'
'`) classes.** -* **Time and Datetime can be 'aware' (`''`), meaning they have defined timezone, or 'naive' (`''`), meaning they don't. +* **Time and Datetime can be 'aware' (`''`), meaning they have defined timezone, or 'naive' (`''`), meaning they don't.** ```python $ pip3 install pytz @@ -473,7 +473,7 @@ import pytz = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` * **`'fold=1'` means second pass in case of time jumping back for one hour.** -* **Use `'.weekday()'` to get day of the week (Mon == 0). +* **Use `'.weekday()'` to get day of the week (Mon == 0).** ### Now ```python From a3252b4ca052aa1b463868f923305c61e50b18a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 00:55:35 +0100 Subject: [PATCH 0090/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index ebc577adb..b97a8165c 100644 --- a/README.md +++ b/README.md @@ -456,8 +456,8 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- -* **Module Datetime provides Date (`''`), Time (`''`) and Datetime (`'
'`) classes.** -* **Time and Datetime can be 'aware' (`''`), meaning they have defined timezone, or 'naive' (`''`), meaning they don't.** +* **Module Datetime provides Date (``), Time (``) and Datetime (`
`) classes.** +* **Time and Datetime can be 'aware' (``), meaning they have defined timezone, or 'naive' (``), meaning they don't.** ```python $ pip3 install pytz From f3621eb743c8fc29b97a709b1894618adb21d8a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 00:56:01 +0100 Subject: [PATCH 0091/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b97a8165c..e41a42faa 100644 --- a/README.md +++ b/README.md @@ -460,7 +460,7 @@ Datetime * **Time and Datetime can be 'aware' (``), meaning they have defined timezone, or 'naive' (``), meaning they don't.** ```python -$ pip3 install pytz +# $ pip3 install pytz from datetime import date, time, datetime, timedelta import pytz ``` From b88dbb30fe26fae3b029a62c15e33c2257045d71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 00:58:22 +0100 Subject: [PATCH 0092/1913] Datetime fix --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e41a42faa..e07aca041 100644 --- a/README.md +++ b/README.md @@ -467,10 +467,10 @@ import pytz ### Constructors ```python - = date(year, month, day) - = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) -
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) - = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) + = date(year, month, day) +
`) classes.** -* **Time and Datetime can be 'aware' (``), meaning they have defined timezone, or 'naive' (``), meaning they don't.** +* **Module Datetime provides 'date' ``, 'time' `` and 'datetime' `
` classes.** +* **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** ```python # $ pip3 install pytz @@ -467,10 +467,10 @@ import pytz ### Constructors ```python - = date(year, month, day) -
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) + = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` * **`'fold=1'` means second pass in case of time jumping back for one hour.** * **Use `'.weekday()'` to get day of the week (Mon == 0).** From 83fad477231327df6d048c70b4296e4e279e4d76 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:01:56 +0100 Subject: [PATCH 0094/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2e05949b9..c0866d65b 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,7 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- -* **Module Datetime provides 'date' ``, 'time' `` and 'datetime' `
` classes.** +* **Module 'datetime' provides 'date' ``, 'time' `` and 'datetime' `
` classes.** * **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** ```python From 2f31a96a2742001a3e4e94c23e8d2870ff118206 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:04:08 +0100 Subject: [PATCH 0095/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c0866d65b..32eef4540 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,7 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- -* **Module 'datetime' provides 'date' ``, 'time' `` and 'datetime' `
` classes.** +* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes.** * **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** ```python From 180ab874731db52d7a5e1bd5e34e4e9f023f1547 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:08:12 +0100 Subject: [PATCH 0096/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 32eef4540..cb888511c 100644 --- a/README.md +++ b/README.md @@ -472,8 +472,8 @@ import pytz
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` -* **`'fold=1'` means second pass in case of time jumping back for one hour.** * **Use `'.weekday()'` to get day of the week (Mon == 0).** +* **`'fold=1'` means second pass in case of time jumping back for one hour.** ### Now ```python @@ -486,7 +486,7 @@ import pytz ### Encode ```python = D/T/DT.fromisoformat() # From 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. -
= DT.strptime(, '') # Datetime from string according to 'format'. +
= DT.strptime(, '') # Datetime from string according to . = D/DT.fromordinal() # Date or datetime from days since Christ. = D/DT.fromtimestamp() # Date or datetime from seconds since Epoch in local time. = DT.utcfromtimestamp() # Naive datetime from seconds since Epoch in UTC time. From 6ce839b90a8d4bc028bd88807b3b41a4d1626581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:11:48 +0100 Subject: [PATCH 0097/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cb888511c..633f3e77f 100644 --- a/README.md +++ b/README.md @@ -484,7 +484,7 @@ import pytz ``` ### Encode -```python +```python = D/T/DT.fromisoformat() # From 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both.
= DT.strptime(, '') # Datetime from string according to . = D/DT.fromordinal() # Date or datetime from days since Christ. From a51055ef866a1214a310f6e1371ab6af78325576 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:17:06 +0100 Subject: [PATCH 0098/1913] Datetime fix --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 633f3e77f..5bce24d1e 100644 --- a/README.md +++ b/README.md @@ -465,14 +465,13 @@ from datetime import date, time, datetime, timedelta import pytz ``` -### Constructors ```python = date(year, month, day) = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0)
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` -* **Use `'.weekday()'` to get day of the week (Mon == 0).** +* **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means second pass in case of time jumping back for one hour.** ### Now From ddc89607c29cabd19b1770a1722a47fb6c904f04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:19:45 +0100 Subject: [PATCH 0099/1913] Datetime fix --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5bce24d1e..2a9888d7e 100644 --- a/README.md +++ b/README.md @@ -476,10 +476,10 @@ import pytz ### Now ```python - = date.today() # Current local date. - = datetime.today() # Naive datetime from current local time. - = datetime.utcnow() # Naive datetime from current UTC time. - = datetime.now() # Aware datetime from current time. + = D.today() # Current local date. + = DT.today() # Naive datetime from current local time. + = DT.utcnow() # Naive datetime from current UTC time. + = DT.now() # Aware datetime from current time. ``` ### Encode From f253fd1c8989f8bfe99561efb02b8ff87767552a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:20:37 +0100 Subject: [PATCH 0100/1913] Datetime fix --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 2a9888d7e..bb02761fd 100644 --- a/README.md +++ b/README.md @@ -465,6 +465,7 @@ from datetime import date, time, datetime, timedelta import pytz ``` +### Constructors ```python = date(year, month, day) = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) From 335e35a2174a0cc9eff3e45bf27cc669f14038c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:25:45 +0100 Subject: [PATCH 0101/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bb02761fd..3d30cc294 100644 --- a/README.md +++ b/README.md @@ -499,7 +499,7 @@ import pytz = .isoformat() # 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. = .strftime('') # Returns customized string representation. = .toordinal() # Returns days since Christ ignoring time and timezone. - =
.timestamp() # Returns seconds since Epoch in local time or if set. + =
.timestamp() # Returns seconds since Epoch in local time or tz if set. ``` ### Format From d66e682f8a11bae67f78bbfafb002ee3620790f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:27:03 +0100 Subject: [PATCH 0102/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3d30cc294..8e3b58ff5 100644 --- a/README.md +++ b/README.md @@ -507,7 +507,7 @@ import pytz >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ``` -#### Rest of the options: +#### Rest of the codes: * **`'y'` - Year, 2 digits** * **`'b'` - Month, abbreviated name** * **`'B'` - Month, full name** From 29fd381689826de065884d1cd7e16ab50557b50e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:29:49 +0100 Subject: [PATCH 0103/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e3b58ff5..0cd944364 100644 --- a/README.md +++ b/README.md @@ -523,7 +523,7 @@ import pytz ```python = pytz.timezone('/') # Use 'pytz.utc' for UTC. =
.astimezone() # Converts datetime to passed timezone. - = .replace(tzinfo=) # Changes timezone without conversion. + = .replace(tzinfo=) # Changes timezone without conversion. = .utcoffset() # Returns timezone's current offset from UTC. = .dst() # Returns daylight saving time offset. ``` From 5c743570ee27fd1809a36b581b1cfc7e9f90e260 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:45:03 +0100 Subject: [PATCH 0104/1913] Datetime fix --- README.md | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 0cd944364..8e351c353 100644 --- a/README.md +++ b/README.md @@ -456,8 +456,9 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- -* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes.** -* **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** +* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes, all of which are immutable and hashable.** +* **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't. +* **If object is naive it is presumed to be in system's timezone.** ```python # $ pip3 install pytz @@ -483,6 +484,15 @@ import pytz = DT.now() # Aware datetime from current time. ``` +### Timezone +```python + = pytz.timezone('/') # Use 'pytz.utc' for UTC. + =
.astimezone() # Converts datetime to passed timezone. + = .replace(tzinfo=) # Changes timezone without conversion. + = .utcoffset() # Returns timezone's current offset from UTC. + = .dst() # Returns daylight saving time offset. +``` + ### Encode ```python = D/T/DT.fromisoformat() # From 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. @@ -519,15 +529,6 @@ import pytz * **`'z'` - Timezone offset, ± and 4 digits** * **`'Z'` - Timezone name** -### Timezone -```python - = pytz.timezone('/') # Use 'pytz.utc' for UTC. - =
.astimezone() # Converts datetime to passed timezone. - = .replace(tzinfo=) # Changes timezone without conversion. - = .utcoffset() # Returns timezone's current offset from UTC. - = .dst() # Returns daylight saving time offset. -``` - Arguments --------- From 683d439a68c4b19a98a061101ac1d8415a32c27f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 01:45:53 +0100 Subject: [PATCH 0105/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8e351c353..7d602e7a7 100644 --- a/README.md +++ b/README.md @@ -457,7 +457,7 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- * **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes, all of which are immutable and hashable.** -* **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't. +* **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** * **If object is naive it is presumed to be in system's timezone.** ```python From 491c9271eadedc521fa9f6bac2d44bfc3280129a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:01:22 +0100 Subject: [PATCH 0106/1913] Datetime fix --- README.md | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 7d602e7a7..339f4a762 100644 --- a/README.md +++ b/README.md @@ -495,23 +495,35 @@ import pytz ### Encode ```python - = D/T/DT.fromisoformat() # From 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. -
= DT.strptime(, '') # Datetime from string according to . + = D/T/DT.fromisoformat() # From 'YYYY-MM-DD' / 'HH:MM:SS.ffffff[+]'. +
= DT.strptime(, '') # Datetime from string according to format. = D/DT.fromordinal() # Date or datetime from days since Christ. - = D/DT.fromtimestamp() # Date or datetime from seconds since Epoch in local time. - = DT.utcfromtimestamp() # Naive datetime from seconds since Epoch in UTC time. - = DT.fromtimestamp(, ) # Aware datetime from seconds since Epoch in time. + = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. + = DT.utcfromtimestamp() # Naive DT from seconds since Epoch in UTC time. + = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode ```python - = .isoformat() # 'YYYY-MM-DD', 'HH:MM:SS.ffffff[+]' or both. - = .strftime('') # Returns customized string representation. - = .toordinal() # Returns days since Christ ignoring time and timezone. - =
.timestamp() # Returns seconds since Epoch in local time or tz if set. + = .isoformat() # 'YYYY-MM-DD' / 'HH:MM:SS.ffffff[+]'. + = .strftime('') # Customized string representation. + = .toordinal() # Days since Christ, ignoring time and timezone. + =
.timestamp() # Seconds since Epoch in local time or tz if set. ``` +### ISO Format +```python +date == 'YYYY-MM-DD' +time == 'HH:MM:SS.ffffff[+]' +datetime == 'YYYY-MM-DDTHH:MM:SS.ffffff[+]' +``` + +* **Date: `'YYYY-MM-DD'`.** +* **Time: `'HH:MM:SS.ffffff[+]'`.** +* **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`.** + + ### Format ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') From 96f8f69152dd77e1e43755e6e316f2506b9ac01b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:10:50 +0100 Subject: [PATCH 0107/1913] Datetime fix --- README.md | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 339f4a762..c21d5a17c 100644 --- a/README.md +++ b/README.md @@ -495,7 +495,7 @@ import pytz ### Encode ```python - = D/T/DT.fromisoformat() # From 'YYYY-MM-DD' / 'HH:MM:SS.ffffff[+]'. + = D/T/DT.fromisoformat('') # D/T/DT from ISO string.
= DT.strptime(, '') # Datetime from string according to format. = D/DT.fromordinal() # Date or datetime from days since Christ. = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. @@ -506,19 +506,13 @@ import pytz ### Decode ```python - = .isoformat() # 'YYYY-MM-DD' / 'HH:MM:SS.ffffff[+]'. + = .isoformat() # ISO string representation. = .strftime('') # Customized string representation. = .toordinal() # Days since Christ, ignoring time and timezone. =
.timestamp() # Seconds since Epoch in local time or tz if set. ``` -### ISO Format -```python -date == 'YYYY-MM-DD' -time == 'HH:MM:SS.ffffff[+]' -datetime == 'YYYY-MM-DDTHH:MM:SS.ffffff[+]' -``` - +### ISO Formats * **Date: `'YYYY-MM-DD'`.** * **Time: `'HH:MM:SS.ffffff[+]'`.** * **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`.** From bca5b0b269cbd890d53cf9df374e282caf741c2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:16:20 +0100 Subject: [PATCH 0108/1913] Datetime fix --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c21d5a17c..70ac71555 100644 --- a/README.md +++ b/README.md @@ -507,23 +507,22 @@ import pytz ### Decode ```python = .isoformat() # ISO string representation. - = .strftime('') # Customized string representation. + = .strftime('') # Custom string representation. = .toordinal() # Days since Christ, ignoring time and timezone. =
.timestamp() # Seconds since Epoch in local time or tz if set. ``` -### ISO Formats +### Format +#### ISO: * **Date: `'YYYY-MM-DD'`.** * **Time: `'HH:MM:SS.ffffff[+]'`.** * **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`.** - -### Format +#### Strptime, strftime: ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ``` -#### Rest of the codes: * **`'y'` - Year, 2 digits** * **`'b'` - Month, abbreviated name** * **`'B'` - Month, full name** From 42fe6ff4fdc6b5162a6b2bcbc19448fa3b57d501 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:18:33 +0100 Subject: [PATCH 0109/1913] Datetime fix --- README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 70ac71555..aa0a3ae57 100644 --- a/README.md +++ b/README.md @@ -512,17 +512,15 @@ import pytz =
.timestamp() # Seconds since Epoch in local time or tz if set. ``` -### Format -#### ISO: +### ISO * **Date: `'YYYY-MM-DD'`.** * **Time: `'HH:MM:SS.ffffff[+]'`.** * **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`.** -#### Strptime, strftime: +### Format ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ``` - * **`'y'` - Year, 2 digits** * **`'b'` - Month, abbreviated name** * **`'B'` - Month, full name** From 5a6562ca8f03d6e2c16f266708ab94313a418004 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:18:55 +0100 Subject: [PATCH 0110/1913] Datetime fix --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index aa0a3ae57..907426320 100644 --- a/README.md +++ b/README.md @@ -513,9 +513,9 @@ import pytz ``` ### ISO -* **Date: `'YYYY-MM-DD'`.** -* **Time: `'HH:MM:SS.ffffff[+]'`.** -* **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`.** +* **Date: `'YYYY-MM-DD'`** +* **Time: `'HH:MM:SS.ffffff[+]'`** +* **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`** ### Format ```python From e4f8edce991ce9ee436bce0e1cf81bb6c9c07066 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:19:33 +0100 Subject: [PATCH 0111/1913] Datetime fix --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 907426320..526edb9e0 100644 --- a/README.md +++ b/README.md @@ -521,6 +521,8 @@ import pytz ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ``` + +#### Rest of the options: * **`'y'` - Year, 2 digits** * **`'b'` - Month, abbreviated name** * **`'B'` - Month, full name** From bc7441b7178d493c6f6f5d77003f750de3208144 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:20:49 +0100 Subject: [PATCH 0112/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 526edb9e0..967b4a298 100644 --- a/README.md +++ b/README.md @@ -522,7 +522,7 @@ import pytz >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ``` -#### Rest of the options: +#### Rest of the codes: * **`'y'` - Year, 2 digits** * **`'b'` - Month, abbreviated name** * **`'B'` - Month, full name** From eae41b5801ccfc29de8bb71aed7a7ac18494ab48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:24:17 +0100 Subject: [PATCH 0113/1913] Datetime fix --- README.md | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/README.md b/README.md index 967b4a298..9c327fd85 100644 --- a/README.md +++ b/README.md @@ -503,6 +503,7 @@ import pytz = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'` or both separated by `'T'`. ### Decode ```python @@ -512,11 +513,6 @@ import pytz =
.timestamp() # Seconds since Epoch in local time or tz if set. ``` -### ISO -* **Date: `'YYYY-MM-DD'`** -* **Time: `'HH:MM:SS.ffffff[+]'`** -* **Datetime: `'YYYY-MM-DDTHH:MM:SS.ffffff[+]'`** - ### Format ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') From aa353265a5373d98d87fc1283bb324890356f3d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:24:37 +0100 Subject: [PATCH 0114/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9c327fd85..720e9275b 100644 --- a/README.md +++ b/README.md @@ -503,7 +503,7 @@ import pytz = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'` or both separated by `'T'`. +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'` or both separated by `'T'`.** ### Decode ```python From 84bc1e780c40a613d5087fbe69bc818ba5366b67 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:26:56 +0100 Subject: [PATCH 0115/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 720e9275b..c2bbaa9cd 100644 --- a/README.md +++ b/README.md @@ -503,7 +503,7 @@ import pytz = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'` or both separated by `'T'`.** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'`, or both separated by `'T'`.** ### Decode ```python From eaed4429f85787dcade7253e9b010ec062718db1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:30:42 +0100 Subject: [PATCH 0116/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c2bbaa9cd..c22314b2e 100644 --- a/README.md +++ b/README.md @@ -456,7 +456,7 @@ from itertools import product, combinations, combinations_with_replacement, perm Datetime -------- -* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes, all of which are immutable and hashable.** +* **Module 'datetime' provides 'date' ``, 'time' ``, 'datetime' `
` and 'timedelta' `` classes. All are immutable and hashable.** * **Time and datetime can be 'aware' ``, meaning they have defined timezone, or 'naive' ``, meaning they don't.** * **If object is naive it is presumed to be in system's timezone.** From 65ac2fce2f8704298091798f06be6369086a6f32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:38:14 +0100 Subject: [PATCH 0117/1913] Datetime fix --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c22314b2e..3aa06cf93 100644 --- a/README.md +++ b/README.md @@ -470,8 +470,9 @@ import pytz ```python = date(year, month, day) = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) -
= datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0) - = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) +
= datetime(year, month, day, hour=0, minute=0, second=0, ...) + = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, + minutes=0, hours=0, weeks=0) ``` * **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means second pass in case of time jumping back for one hour.** From eb122ffcaec3c2c94cf7cbe7c85af9d4c3ef6e82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:43:22 +0100 Subject: [PATCH 0118/1913] Datetime fix --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3aa06cf93..035c25f3d 100644 --- a/README.md +++ b/README.md @@ -487,7 +487,8 @@ import pytz ### Timezone ```python - = pytz.timezone('/') # Use 'pytz.utc' for UTC. + = pytz.utc # UTC timezone. + = pytz.timezone('/') # Timezone from 'Continent/City' string. =
.astimezone() # Converts datetime to passed timezone. = .replace(tzinfo=) # Changes timezone without conversion. = .utcoffset() # Returns timezone's current offset from UTC. From 6a5a76fca9c8a49722c333196feafe7be9c357be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 02:59:51 +0100 Subject: [PATCH 0119/1913] Datetime fix --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 035c25f3d..52ef8bc4c 100644 --- a/README.md +++ b/README.md @@ -489,10 +489,10 @@ import pytz ```python = pytz.utc # UTC timezone. = pytz.timezone('/') # Timezone from 'Continent/City' string. - =
.astimezone() # Converts datetime to passed timezone. - = .replace(tzinfo=) # Changes timezone without conversion. - = .utcoffset() # Returns timezone's current offset from UTC. - = .dst() # Returns daylight saving time offset. + =
.astimezone() # Datetime converted to passed timezone. + = .replace(tzinfo=) # Unconverted object with new timezone. + = .utcoffset() # Timezone's current offset from UTC. + = .dst() # Daylight saving time offset. ``` ### Encode From bd8099f0dbf88866cdadd2f9cf34eeaa4513276b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:04:23 +0100 Subject: [PATCH 0120/1913] Datetime fix --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 52ef8bc4c..387cb1cbe 100644 --- a/README.md +++ b/README.md @@ -491,8 +491,6 @@ import pytz = pytz.timezone('/') # Timezone from 'Continent/City' string. =
.astimezone() # Datetime converted to passed timezone. = .replace(tzinfo=) # Unconverted object with new timezone. - = .utcoffset() # Timezone's current offset from UTC. - = .dst() # Daylight saving time offset. ``` ### Encode From 41c1c48d185021b758085a5d77fda70075b3ffa2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:08:27 +0100 Subject: [PATCH 0121/1913] Datetime fix --- README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 387cb1cbe..6aa05953d 100644 --- a/README.md +++ b/README.md @@ -479,10 +479,9 @@ import pytz ### Now ```python - = D.today() # Current local date. - = DT.today() # Naive datetime from current local time. + = D/DT.today() # Current local date or naive datetime. = DT.utcnow() # Naive datetime from current UTC time. - = DT.now() # Aware datetime from current time. + = DT.now() # Aware datetime from current tz time. ``` ### Timezone From 489de09fbf59640c945527ab548cda945daeaa31 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:10:03 +0100 Subject: [PATCH 0122/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6aa05953d..5d10cd9f0 100644 --- a/README.md +++ b/README.md @@ -488,7 +488,7 @@ import pytz ```python = pytz.utc # UTC timezone. = pytz.timezone('/') # Timezone from 'Continent/City' string. - =
.astimezone() # Datetime converted to passed timezone. + =
.astimezone() # Datetime, converted to passed timezone. = .replace(tzinfo=) # Unconverted object with new timezone. ``` From c6bc792d8dca09700f385c25ff3c9a22ffdb4476 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:13:32 +0100 Subject: [PATCH 0123/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5d10cd9f0..cf214fcee 100644 --- a/README.md +++ b/README.md @@ -494,7 +494,7 @@ import pytz ### Encode ```python - = D/T/DT.fromisoformat('') # D/T/DT from ISO string. + = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string according to format. = D/DT.fromordinal() # Date or datetime from days since Christ. = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. From 458570bf01f74f459ef46a6170dce002e1405a95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:14:22 +0100 Subject: [PATCH 0124/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index cf214fcee..57d81f398 100644 --- a/README.md +++ b/README.md @@ -495,7 +495,7 @@ import pytz ### Encode ```python = D/T/DT.fromisoformat('') # Object from ISO string. -
= DT.strptime(, '') # Datetime from string according to format. +
= DT.strptime(, '') # Datetime from string, according to format. = D/DT.fromordinal() # Date or datetime from days since Christ. = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. = DT.utcfromtimestamp() # Naive DT from seconds since Epoch in UTC time. From f5ee7f0fc5e554a736080115ec60422270d2000d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:16:48 +0100 Subject: [PATCH 0125/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 57d81f398..6b5dc5a1b 100644 --- a/README.md +++ b/README.md @@ -496,8 +496,8 @@ import pytz ```python = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string, according to format. - = D/DT.fromordinal() # Date or datetime from days since Christ. - = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. + = D/DT.fromordinal() # Object from days since Christ. + = D/DT.fromtimestamp() # Object from seconds since Epoch in local time. = DT.utcfromtimestamp() # Naive DT from seconds since Epoch in UTC time. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` From bad760c5dd2de797150239d821b4d720a0dabfef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:18:52 +0100 Subject: [PATCH 0126/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6b5dc5a1b..993ea52cc 100644 --- a/README.md +++ b/README.md @@ -496,8 +496,8 @@ import pytz ```python = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string, according to format. - = D/DT.fromordinal() # Object from days since Christ. - = D/DT.fromtimestamp() # Object from seconds since Epoch in local time. + = D/DT.fromordinal() # D/DT from days since Christ. + = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. = DT.utcfromtimestamp() # Naive DT from seconds since Epoch in UTC time. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` From 4f9a8fde8a5f095365c5c6c3706f6e7114e567fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:21:04 +0100 Subject: [PATCH 0127/1913] Datetime fix --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 993ea52cc..0c11ffc91 100644 --- a/README.md +++ b/README.md @@ -508,8 +508,8 @@ import pytz ```python = .isoformat() # ISO string representation. = .strftime('') # Custom string representation. - = .toordinal() # Days since Christ, ignoring time and timezone. - =
.timestamp() # Seconds since Epoch in local time or tz if set. + = .toordinal() # Days since Christ, ignoring time and tz. + =
.timestamp() # Seconds since Epoch in local time or tz. ``` ### Format From 329502d9e74f87bdba084a2eac24a88ded560401 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:23:20 +0100 Subject: [PATCH 0128/1913] Datetime fix --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0c11ffc91..c4820142a 100644 --- a/README.md +++ b/README.md @@ -518,16 +518,16 @@ import pytz ``` #### Rest of the codes: -* **`'y'` - Year, 2 digits** -* **`'b'` - Month, abbreviated name** -* **`'B'` - Month, full name** -* **`'a'` - Weekday, abbreviated name** -* **`'A'` - Weekday, full name** -* **`'I'` - Hours, 2 digits, 12 hours** -* **`'p'` - AM/PM** -* **`'f'` - Microseconds, 6 digits** -* **`'z'` - Timezone offset, ± and 4 digits** -* **`'Z'` - Timezone name** +* **`'y'` - Year, 2 digits.** +* **`'b'` - Month, abbreviated name.** +* **`'B'` - Month, full name.** +* **`'a'` - Weekday, abbreviated name.** +* **`'A'` - Weekday, full name.** +* **`'I'` - Hours, 2 digits, 12 hours.** +* **`'p'` - AM/PM.** +* **`'f'` - Microseconds, 6 digits.** +* **`'z'` - Timezone offset, ± and 4 digits.** +* **`'Z'` - Timezone name.** Arguments From cf823f25fc95ad3e6292b99b93ca8c18a6ab010e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:32:26 +0100 Subject: [PATCH 0129/1913] Datetime fix --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index c4820142a..802def842 100644 --- a/README.md +++ b/README.md @@ -497,8 +497,6 @@ import pytz = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string, according to format. = D/DT.fromordinal() # D/DT from days since Christ. - = D/DT.fromtimestamp() # D/DT from seconds since Epoch in local time. - = DT.utcfromtimestamp() # Naive DT from seconds since Epoch in UTC time. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** From ce969e256cfb536e900e37f71a4a394c83c39b8f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 03:33:39 +0100 Subject: [PATCH 0130/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 802def842..e0a4e6ec1 100644 --- a/README.md +++ b/README.md @@ -499,8 +499,8 @@ import pytz = D/DT.fromordinal() # D/DT from days since Christ. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` -* **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'`, or both separated by `'T'`.** +* **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode ```python From 91b55481cff01720a7f824c22320347ac2b79042 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 04:57:57 +0100 Subject: [PATCH 0131/1913] Datetime fix --- README.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index e0a4e6ec1..db54a5500 100644 --- a/README.md +++ b/README.md @@ -513,16 +513,13 @@ import pytz ### Format ```python >>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') +>>> dt.strftime("%dth %B '%y %A %I%p") +"14th May '15 Thursday 11PM" ``` #### Rest of the codes: -* **`'y'` - Year, 2 digits.** * **`'b'` - Month, abbreviated name.** -* **`'B'` - Month, full name.** * **`'a'` - Weekday, abbreviated name.** -* **`'A'` - Weekday, full name.** -* **`'I'` - Hours, 2 digits, 12 hours.** -* **`'p'` - AM/PM.** * **`'f'` - Microseconds, 6 digits.** * **`'z'` - Timezone offset, ± and 4 digits.** * **`'Z'` - Timezone name.** From d5e8f1274539c04128a11727f3d3a1049a159350 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 05:09:46 +0100 Subject: [PATCH 0132/1913] Datetime fix --- README.md | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index db54a5500..a483be9d7 100644 --- a/README.md +++ b/README.md @@ -512,17 +512,14 @@ import pytz ### Format ```python ->>> dt = datetime.strptime('2015-05-14 23:39:00', '%Y-%m-%d %H:%M:%S') ->>> dt.strftime("%dth %B '%y %A %I%p") -"14th May '15 Thursday 11PM" +>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') +>>> dt.strftime("%A %dth %B '%y, %I:%m%p %Z") +"Thursday 14th May '15, 11:05PM UTC+02:00" ``` #### Rest of the codes: * **`'b'` - Month, abbreviated name.** * **`'a'` - Weekday, abbreviated name.** -* **`'f'` - Microseconds, 6 digits.** -* **`'z'` - Timezone offset, ± and 4 digits.** -* **`'Z'` - Timezone name.** Arguments From 50106d56276bc47f17cd5f6587d8b7ae704f5246 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:24:55 +0100 Subject: [PATCH 0133/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a483be9d7..2177bfb5c 100644 --- a/README.md +++ b/README.md @@ -499,7 +499,7 @@ import pytz = D/DT.fromordinal() # D/DT from days since Christ. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` -* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[+]'`, or both separated by `'T'`.** +* **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** ### Decode From 867b347d8f736eac6f79b54e7c2c3a09880d6549 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:26:25 +0100 Subject: [PATCH 0134/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 2177bfb5c..db166e8e2 100644 --- a/README.md +++ b/README.md @@ -496,7 +496,7 @@ import pytz ```python = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string, according to format. - = D/DT.fromordinal() # D/DT from days since Christ. + = D/DT.fromordinal() # D/DTn from days since Christ. = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. ``` * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** From de4fd4a46c412e239dc50cdb8befaa25eee29922 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:27:08 +0100 Subject: [PATCH 0135/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index db166e8e2..e38b023c8 100644 --- a/README.md +++ b/README.md @@ -497,7 +497,7 @@ import pytz = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from string, according to format. = D/DT.fromordinal() # D/DTn from days since Christ. - = DT.fromtimestamp(, ) # Aware DT from seconds since Epoch in tz time. + = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** From 7ef8138ca52eb071db320dc1a52d3e625757ceec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:32:46 +0100 Subject: [PATCH 0136/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e38b023c8..1f763fa9f 100644 --- a/README.md +++ b/README.md @@ -487,7 +487,7 @@ import pytz ### Timezone ```python = pytz.utc # UTC timezone. - = pytz.timezone('/') # Timezone from 'Continent/City' string. + = pytz.timezone('/') # Timezone from 'Continent/City_Name' str. =
.astimezone() # Datetime, converted to passed timezone. = .replace(tzinfo=) # Unconverted object with new timezone. ``` From c5cfb61e21577bfc74d4ce3ede3bcf667fce3b5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:41:32 +0100 Subject: [PATCH 0137/1913] Datetime fix --- README.md | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 1f763fa9f..9a8651895 100644 --- a/README.md +++ b/README.md @@ -512,15 +512,11 @@ import pytz ### Format ```python ->>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') ->>> dt.strftime("%A %dth %B '%y, %I:%m%p %Z") -"Thursday 14th May '15, 11:05PM UTC+02:00" +>>> dt = datetime.strptime('2015-06-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') +>>> dt.strftime("%a %dth %B '%y, %I:%m%p %Z") +"Sun 14th June '15, 11:06PM UTC+02:00" ``` -#### Rest of the codes: -* **`'b'` - Month, abbreviated name.** -* **`'a'` - Weekday, abbreviated name.** - Arguments --------- From b195702e77c1c13294866ba59bd98c21e3b6c03e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:43:28 +0100 Subject: [PATCH 0138/1913] Datetime fix --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9a8651895..1f763fa9f 100644 --- a/README.md +++ b/README.md @@ -512,11 +512,15 @@ import pytz ### Format ```python ->>> dt = datetime.strptime('2015-06-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') ->>> dt.strftime("%a %dth %B '%y, %I:%m%p %Z") -"Sun 14th June '15, 11:06PM UTC+02:00" +>>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') +>>> dt.strftime("%A %dth %B '%y, %I:%m%p %Z") +"Thursday 14th May '15, 11:05PM UTC+02:00" ``` +#### Rest of the codes: +* **`'b'` - Month, abbreviated name.** +* **`'a'` - Weekday, abbreviated name.** + Arguments --------- From 64a38fc5c0170fe13eba2a2f60cb95d82ff54bc6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 06:44:06 +0100 Subject: [PATCH 0139/1913] Datetime fix --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1f763fa9f..200b9abd6 100644 --- a/README.md +++ b/README.md @@ -518,8 +518,8 @@ import pytz ``` #### Rest of the codes: -* **`'b'` - Month, abbreviated name.** * **`'a'` - Weekday, abbreviated name.** +* **`'b'` - Month, abbreviated name.** Arguments From 66fffae05427fb220eb7f9c915dec433294497e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 13:53:54 +0100 Subject: [PATCH 0140/1913] Switched pytz for dateutil in datetime. --- README.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 200b9abd6..35de87c15 100644 --- a/README.md +++ b/README.md @@ -461,9 +461,8 @@ Datetime * **If object is naive it is presumed to be in system's timezone.** ```python -# $ pip3 install pytz from datetime import date, time, datetime, timedelta -import pytz +from dateutil.tz import UTC, gettz ``` ### Constructors @@ -486,8 +485,8 @@ import pytz ### Timezone ```python - = pytz.utc # UTC timezone. - = pytz.timezone('/') # Timezone from 'Continent/City_Name' str. + = UTC # UTC timezone. + = gettz('/') # Timezone from 'Continent/City_Name' str. =
.astimezone() # Datetime, converted to passed timezone. = .replace(tzinfo=) # Unconverted object with new timezone. ``` From 6870769e5668995bdc82c1d4f326331ebcb596cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Fri, 15 Mar 2019 22:05:39 +0100 Subject: [PATCH 0141/1913] Datetime --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 35de87c15..759d4fdac 100644 --- a/README.md +++ b/README.md @@ -494,7 +494,7 @@ from dateutil.tz import UTC, gettz ### Encode ```python = D/T/DT.fromisoformat('') # Object from ISO string. -
= DT.strptime(, '') # Datetime from string, according to format. +
= DT.strptime(, '') # Datetime from str, according to format. = D/DT.fromordinal() # D/DTn from days since Christ. = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` @@ -512,8 +512,8 @@ from dateutil.tz import UTC, gettz ### Format ```python >>> dt = datetime.strptime('2015-05-14 23:39:00.00 +0200', '%Y-%m-%d %H:%M:%S.%f %z') ->>> dt.strftime("%A %dth %B '%y, %I:%m%p %Z") -"Thursday 14th May '15, 11:05PM UTC+02:00" +>>> dt.strftime("%A %dth %B '%y, %I:%M%p %Z") +"Thursday 14th May '15, 11:39PM UTC+02:00" ``` #### Rest of the codes: From 3b3ef77d5f0e5cc392d9ed427b953d8dfa0d2be6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 17:17:10 +0100 Subject: [PATCH 0142/1913] Added logging --- README.md | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/README.md b/README.md index 759d4fdac..5e975d0ec 100644 --- a/README.md +++ b/README.md @@ -1657,6 +1657,46 @@ def get_border(screen): ``` +Logging +------- +```python +# $ pip3 install loguru +from loguru import logger +``` + +```python +logger.add('debug_{time}.log', colorize=True) # Connects a log file. +logger.add('error_{time}.log', level='ERROR') # Adds another file for errors or higher. +logger.('A logging message') +``` +* **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical`'.** + +### Rotation +Parameter that sets a condition when a new log file is created. +```python +rotation=||| +``` +* **`''` - Max file size in bytes.** +* **`'`' - Max age of a file.** +* **`'
.astimezone() # Datetime, converted to passed timezone. = .replace(tzinfo=) # Unconverted object with new timezone. ``` From 5ab93d30ef72c8f48ad0e3ab51012a2970726d0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 17:52:01 +0100 Subject: [PATCH 0150/1913] Removed spaces before new lines --- README.md | 52 ++++++++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 976dc09e7..eb4ec7090 100644 --- a/README.md +++ b/README.md @@ -46,11 +46,11 @@ list_of_chars = list() ``` ```python -index = .index() # Returns first index of item. +index = .index() # Returns first index of item. .insert(index, ) # Inserts item at index and moves the rest to the right. = .pop([index]) # Removes and returns item at index or from the end. .remove() # Removes first occurrence of item or raises ValueError. -.clear() # Removes all items. +.clear() # Removes all items. ``` @@ -289,9 +289,9 @@ import re ``` * **Parameter `'flags=re.IGNORECASE'` can be used with all functions.** -* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** -* **Use `r'\1'` or `'\\1'` for backreference.** -* **Use `'?'` to make operator non-greedy.** +* **Parameter `'flags=re.DOTALL'` makes dot also accept newline.** +* **Use `r'\1'` or `'\\1'` for backreference.** +* **Use `'?'` to make operator non-greedy.** ### Match Object ```python @@ -424,7 +424,7 @@ from itertools import product, combinations, combinations_with_replacement, perm ```python >>> product([0, 1], repeat=3) -[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), +[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)] ``` @@ -441,15 +441,15 @@ from itertools import product, combinations, combinations_with_replacement, perm ```python >>> combinations_with_replacement('abc', 2) -[('a', 'a'), ('a', 'b'), ('a', 'c'), - ('b', 'b'), ('b', 'c'), +[('a', 'a'), ('a', 'b'), ('a', 'c'), + ('b', 'b'), ('b', 'c'), ('c', 'c')] ``` ```python >>> permutations('abc', 2) -[('a', 'b'), ('a', 'c'), - ('b', 'a'), ('b', 'c'), +[('a', 'b'), ('a', 'c'), + ('b', 'a'), ('b', 'c'), ('c', 'a'), ('c', 'b')] ``` @@ -505,7 +505,7 @@ from dateutil.tz import UTC, tzlocal, gettz * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** * **On Unix systems Epoch is `'1970-01-01 00:00 UTC'`, `'1970-01-01 01:00 CET'`, ...** -### Decode +### Decode ```python = .isoformat() # ISO string representation. = .strftime('') # Custom string representation. @@ -549,7 +549,7 @@ Splat Operator ```python args = (1, 2) kwargs = {'x': 3, 'y': 4, 'z': 5} -func(*args, **kwargs) +func(*args, **kwargs) ``` #### Is the same as: @@ -677,7 +677,7 @@ creature = Creature() Closure ------- **We have a closure in Python when:** -* **A nested function references a value of its enclosing function and then** +* **A nested function references a value of its enclosing function and then** * **the enclosing function returns the nested function.** ```python @@ -839,7 +839,7 @@ class MyComparable: def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return False ``` ### Hashable @@ -857,7 +857,7 @@ class MyHashable: def __eq__(self, other): if isinstance(other, type(self)): return self.a == other.a - return False + return False def __hash__(self): return hash(self.a) ``` @@ -928,7 +928,7 @@ Enum from enum import Enum, auto class (Enum): - = + = = , = auto() @@ -1278,7 +1278,7 @@ Bytes ### Decode ```python - = .decode(encoding='utf-8') + = .decode(encoding='utf-8') = int.from_bytes(, byteorder='big|little', signed=False) = .hex() ``` @@ -1352,7 +1352,7 @@ Memory View **Used for accessing the internal data of an object that supports the buffer protocol.** ```python - = memoryview( / / ) + = memoryview( / / ) .release() ``` @@ -1494,7 +1494,7 @@ last_el = op.methodcaller('pop')() ``` -Eval +Eval ---- ### Basic ```python @@ -1555,14 +1555,14 @@ def eval_node(node): Coroutine --------- -* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** -* **Coroutines provide more powerful data routing possibilities than iterators.** -* **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** +* **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** +* **Coroutines provide more powerful data routing possibilities than iterators.** +* **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** ### Helper Decorator -* **All coroutines must be "primed" by first calling next().** -* **Remembering to call next() is easy to forget.** -* **Solved by wrapping coroutines with a decorator:** +* **All coroutines must be "primed" by first calling next().** +* **Remembering to call next() is easy to forget.** +* **Solved by wrapping coroutines with a decorator:** ```python def coroutine(func): @@ -1691,7 +1691,7 @@ rotation=||| retention=|| ``` * **`''` - Max number of files.** -* **`''` - Max age of a file.** +* **`''` - Max age of a file.** * **`''` - Max age as a string: `'1 week, 3 days'`, `'2 months'`, ...** ### Compression From a55e023134eb2b3418a2e0d64b121c26704db7b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 17:59:11 +0100 Subject: [PATCH 0151/1913] Chain --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index eb4ec7090..304aa1df4 100644 --- a/README.md +++ b/README.md @@ -190,7 +190,7 @@ from itertools import count, repeat, cycle, chain, islice ``` ```python - = chain(, ) # Empties collections in order. + = chain(, , ...) # Empties collections in order. = chain.from_iterable() # Empties collections inside a collection in order. ``` From a183651ea679290ea6917e57cab62274a1025887 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 19:17:49 +0100 Subject: [PATCH 0152/1913] New --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 304aa1df4..c56b6e92b 100644 --- a/README.md +++ b/README.md @@ -1460,6 +1460,8 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` +* **New() is a class method that gets called before init(). It returns an instance of a class that gets passed to init() as a 'self' argument.** +* **It receives the same arguments as init(), except for the first one which is its class.** ### Metaclass Attribute **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.** From aee3c4dd2f1ac0bed5246fba2badeb72fc530bc8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 19:19:53 +0100 Subject: [PATCH 0153/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c56b6e92b..fba078e55 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). It returns an instance of a class that gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one which is its class.** +* **It receives the same arguments as init(), except for the first one which, is its class.** ### Metaclass Attribute **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.** From 973ee455c1aa36bd7351ecfbb32e6f73aeb0b0f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 19:20:22 +0100 Subject: [PATCH 0154/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index fba078e55..c56b6e92b 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). It returns an instance of a class that gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one which, is its class.** +* **It receives the same arguments as init(), except for the first one which is its class.** ### Metaclass Attribute **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.** From 98e473faa30c607e76fa31b48f5d4dd06f621f4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 19:26:53 +0100 Subject: [PATCH 0155/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index c56b6e92b..ca465ffd4 100644 --- a/README.md +++ b/README.md @@ -1460,7 +1460,7 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` -* **New() is a class method that gets called before init(). It returns an instance of a class that gets passed to init() as a 'self' argument.** +* **New() is a class method that gets called before init(). If it returns an instance of a class, then that instance gets passed to init() as a 'self' argument.** * **It receives the same arguments as init(), except for the first one which is its class.** ### Metaclass Attribute From d07c4a264be12faa560da108b1188b4f05972b25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 19:52:14 +0100 Subject: [PATCH 0156/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ca465ffd4..c8a6b438e 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). If it returns an instance of a class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one which is its class.** +* **It receives the same arguments as init(), except for the first one which is a class.** ### Metaclass Attribute **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.** From 03239e5f8d50f7a8412b2d12417042ef0fcc182f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 20:11:25 +0100 Subject: [PATCH 0157/1913] New --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c8a6b438e..c98fe22fe 100644 --- a/README.md +++ b/README.md @@ -1460,8 +1460,8 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` -* **New() is a class method that gets called before init(). If it returns an instance of a class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one which is a class.** +* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** +* **It receives the same arguments as init(), except for the first one that specifies the class of returned instance.** ### Metaclass Attribute **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.** From 0eda219e9222a18b5cc40fd5aabaebea0f581182 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 20:27:06 +0100 Subject: [PATCH 0158/1913] New --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c98fe22fe..f4d168e26 100644 --- a/README.md +++ b/README.md @@ -1460,8 +1460,8 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` -* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one that specifies the class of returned instance.** +* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument, unless it is called directly as in example above.** +* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance.** ### Metaclass Attribute **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.** From 8ea9072761f1933d93826dc98b413f0f254736e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 21:04:36 +0100 Subject: [PATCH 0159/1913] New --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index f4d168e26..bf755ca51 100644 --- a/README.md +++ b/README.md @@ -1460,8 +1460,9 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` -* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument, unless it is called directly as in example above.** +* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument. * **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance.** +* **New() can also be called directly, usually from a new() method of a child class (`'def __new__(cls): return super().__new__(cls)'`), in which case init() is not called.** ### Metaclass Attribute **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.** From df0ed251a240fe3b2bb1e63bdbb06adca2a88b89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 21:05:19 +0100 Subject: [PATCH 0160/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf755ca51..0689f2dac 100644 --- a/README.md +++ b/README.md @@ -1460,7 +1460,7 @@ class MyMetaClass(type): attrs['a'] = 'abcde' return type.__new__(cls, name, parents, attrs) ``` -* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument. +* **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** * **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance.** * **New() can also be called directly, usually from a new() method of a child class (`'def __new__(cls): return super().__new__(cls)'`), in which case init() is not called.** From 5be0e85f40735ea0b0805886b9d9ff34b9d62268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 21:47:28 +0100 Subject: [PATCH 0161/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0689f2dac..843071472 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance.** +* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (In this case 'MyMetaClass').** * **New() can also be called directly, usually from a new() method of a child class (`'def __new__(cls): return super().__new__(cls)'`), in which case init() is not called.** ### Metaclass Attribute From 8f39b45f8441f21db8b539c6492991bbe9e3d508 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 21:47:59 +0100 Subject: [PATCH 0162/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 843071472..67fc960f9 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (In this case 'MyMetaClass').** +* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (In our case 'MyMetaClass').** * **New() can also be called directly, usually from a new() method of a child class (`'def __new__(cls): return super().__new__(cls)'`), in which case init() is not called.** ### Metaclass Attribute From 138ada2ba1d6dbbd01f2625a31b1f53a14ed3580 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 22:09:38 +0100 Subject: [PATCH 0163/1913] New --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 67fc960f9..19af2df8e 100644 --- a/README.md +++ b/README.md @@ -1461,7 +1461,7 @@ class MyMetaClass(type): return type.__new__(cls, name, parents, attrs) ``` * **New() is a class method that gets called before init(). If it returns an instance of its class, then that instance gets passed to init() as a 'self' argument.** -* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance (In our case 'MyMetaClass').** +* **It receives the same arguments as init(), except for the first one that specifies the desired class of returned instance ('MyMetaClass' in our case).** * **New() can also be called directly, usually from a new() method of a child class (`'def __new__(cls): return super().__new__(cls)'`), in which case init() is not called.** ### Metaclass Attribute From a4d38c807f96de8a8b225424190222522099e614 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 23:10:56 +0100 Subject: [PATCH 0164/1913] Datetime with | instead of slashes --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 19af2df8e..e095528e7 100644 --- a/README.md +++ b/README.md @@ -473,12 +473,12 @@ from dateutil.tz import UTC, tzlocal, gettz = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` -* **Use `'.weekday()'` to get the day of the week (Mon == 0).** +* **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means second pass in case of time jumping back for one hour.** ### Now ```python - = D/DT.today() # Current local date or naive datetime. + = D|DT.today() # Current local date or naive datetime. = DT.utcnow() # Naive datetime from current UTC time. = DT.now() # Aware datetime from current tz time. ``` @@ -492,14 +492,14 @@ from dateutil.tz import UTC, tzlocal, gettz ```python =
.astimezone() # Datetime, converted to passed timezone. - = .replace(tzinfo=) # Unconverted object with new timezone. + = .replace(tzinfo=) # Unconverted object with new timezone. ``` ### Encode ```python - = D/T/DT.fromisoformat('') # Object from ISO string. + = D|T|DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from str, according to format. - = D/DT.fromordinal() # D/DTn from days since Christ. + = D|DT.fromordinal() # D|DTn from days since Christ. = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** @@ -507,9 +507,9 @@ from dateutil.tz import UTC, tzlocal, gettz ### Decode ```python - = .isoformat() # ISO string representation. - = .strftime('') # Custom string representation. - = .toordinal() # Days since Christ, ignoring time and tz. + = .isoformat() # ISO string representation. + = .strftime('') # Custom string representation. + = .toordinal() # Days since Christ, ignoring time and tz. =
.timestamp() # Seconds since Epoch in local time or tz. ``` From 2ed74a576924ab088f8a2f241de2873e7b952ace Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sat, 16 Mar 2019 23:13:17 +0100 Subject: [PATCH 0165/1913] Reverted datetime --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index e095528e7..19af2df8e 100644 --- a/README.md +++ b/README.md @@ -473,12 +473,12 @@ from dateutil.tz import UTC, tzlocal, gettz = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) ``` -* **Use `'.weekday()'` to get the day of the week (Mon == 0).** +* **Use `'.weekday()'` to get the day of the week (Mon == 0).** * **`'fold=1'` means second pass in case of time jumping back for one hour.** ### Now ```python - = D|DT.today() # Current local date or naive datetime. + = D/DT.today() # Current local date or naive datetime. = DT.utcnow() # Naive datetime from current UTC time. = DT.now() # Aware datetime from current tz time. ``` @@ -492,14 +492,14 @@ from dateutil.tz import UTC, tzlocal, gettz ```python =
.astimezone() # Datetime, converted to passed timezone. - = .replace(tzinfo=) # Unconverted object with new timezone. + = .replace(tzinfo=) # Unconverted object with new timezone. ``` ### Encode ```python - = D|T|DT.fromisoformat('') # Object from ISO string. + = D/T/DT.fromisoformat('') # Object from ISO string.
= DT.strptime(, '') # Datetime from str, according to format. - = D|DT.fromordinal() # D|DTn from days since Christ. + = D/DT.fromordinal() # D/DTn from days since Christ. = DT.fromtimestamp(, ) # DTa from seconds since Epoch in tz time. ``` * **ISO strings come in following forms: `'YYYY-MM-DD'`, `'HH:MM:SS.ffffff[±]'`, or both separated by `'T'`.** @@ -507,9 +507,9 @@ from dateutil.tz import UTC, tzlocal, gettz ### Decode ```python - = .isoformat() # ISO string representation. - = .strftime('') # Custom string representation. - = .toordinal() # Days since Christ, ignoring time and tz. + = .isoformat() # ISO string representation. + = .strftime('') # Custom string representation. + = .toordinal() # Days since Christ, ignoring time and tz. =
.timestamp() # Seconds since Epoch in local time or tz. ``` From 62efe52edf534148604a65866d520a91723a5009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 17 Mar 2019 19:19:41 +0100 Subject: [PATCH 0166/1913] Link inside code test --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 19af2df8e..3ea33621a 100644 --- a/README.md +++ b/README.md @@ -366,6 +366,8 @@ Format {65:c} # 'A' {3:08b} # '00000011' -> Binary with leading zeros. {3:0<8b} # '11000000' -> Binary with trailing zeros. +[I'm an inline-style link](https://www.google.com) +'Collections' : (list) ``` #### Float presentation types: @@ -1943,7 +1945,7 @@ Image from PIL import Image ``` -#### Creates PNG image of rainbow gradient: +#### Creates PNG image of a rainbow gradient: ```python width = 100 height = 100 From 6b035d557bbc10c578b53970aa482c9f15cba2fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Sun, 17 Mar 2019 19:20:15 +0100 Subject: [PATCH 0167/1913] Revert --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 3ea33621a..d6587ec1d 100644 --- a/README.md +++ b/README.md @@ -366,8 +366,6 @@ Format {65:c} # 'A' {3:08b} # '00000011' -> Binary with leading zeros. {3:0<8b} # '11000000' -> Binary with trailing zeros. -[I'm an inline-style link](https://www.google.com) -'Collections' : (list) ``` #### Float presentation types: From c6f0df84458c075705a6b501ac86baa08fed744b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 00:18:45 +0100 Subject: [PATCH 0168/1913] Decorator --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index d6587ec1d..3b84e6529 100644 --- a/README.md +++ b/README.md @@ -772,6 +772,7 @@ def fib(n): * **Recursion depth is limited to 1000 by default. To increase it use `'sys.setrecursionlimit()'`.** ### Parametrized Decorator +**A decorator that accepts arguments and returns a normal decorator that accepts a function.** ```python from functools import wraps From 15c7de7b6871f374a2cdbf53c761445aa25124c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 00:23:28 +0100 Subject: [PATCH 0169/1913] Partial --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3b84e6529..b78944062 100644 --- a/README.md +++ b/README.md @@ -703,7 +703,8 @@ from functools import partial ``` ```python ->>> multiply_by_3 = partial(operator.mul, 3) +>>> from operator import mul +>>> multiply_by_3 = partial(mul, 3) >>> multiply_by_3(10) 30 ``` From d6b9628557bdae51f471945c08f266c7c54afcdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 00:24:19 +0100 Subject: [PATCH 0170/1913] Partial --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b78944062..2c29cda91 100644 --- a/README.md +++ b/README.md @@ -703,8 +703,8 @@ from functools import partial ``` ```python ->>> from operator import mul ->>> multiply_by_3 = partial(mul, 3) +>>> import operator as op +>>> multiply_by_3 = partial(op.mul, 3) >>> multiply_by_3(10) 30 ``` From 0df2a3df6e573ed84a49a2ee5c2ace2c4ba40ead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 00:36:13 +0100 Subject: [PATCH 0171/1913] Format --- README.md | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 2c29cda91..0955428ee 100644 --- a/README.md +++ b/README.md @@ -347,12 +347,15 @@ Format {'abcde':10.3} # 'abc ' ``` -### Number Options +### Float Options ```python {1.23456:.3f} # '1.235' {1.23456:10.3f} # ' 1.235' +{1.23456:10.3e} # ' 1.235e+00' +{1.23456:10.3%} # ' 123.456%' ``` +### Int Options ```python { 123456:10,} # ' 123,456' { 123456:10_} # ' 123_456' @@ -363,22 +366,11 @@ Format ``` ```python -{65:c} # 'A' -{3:08b} # '00000011' -> Binary with leading zeros. -{3:0<8b} # '11000000' -> Binary with trailing zeros. +{90:c} # 'Z' +{90:X} # '5A' +{3:08b} # '00000011' ``` -#### Float presentation types: -* **`'f'` - Fixed point: `.f`** -* **`'%'` - Percent: `.%`** -* **`'e'` - Exponent** - -#### Integer presentation types: -* **`'c'` - character** -* **`'b'` - binary** -* **`'x'` - hex** -* **`'X'` - HEX** - Numbers ------- From 2d4274ac38ae18a26a04cc34cf9b735c5a674e87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 00:39:17 +0100 Subject: [PATCH 0172/1913] Format --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index 0955428ee..a4c7b6fe5 100644 --- a/README.md +++ b/README.md @@ -340,9 +340,6 @@ Format **`'!r'` calls object's repr() method, instead of format(), to get a string.** ```python {'abcde'!r:<10} # "'abcde' " -``` - -```python {'abcde':.3} # 'abc' {'abcde':10.3} # 'abc ' ``` From d415fe8c72af3275fa7c245fc785721a358c3c0d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 02:49:39 +0100 Subject: [PATCH 0173/1913] Inheritance --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index a4c7b6fe5..84ecaeb01 100644 --- a/README.md +++ b/README.md @@ -812,7 +812,9 @@ class Person: def __init__(self, name, age): self.name = name self.age = age +``` +```python class Employee(Person): def __init__(self, name, age, staff_num): super().__init__(name, age) From 78c74b3eedeb80e93a9de346e83d6e0cd568bcd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 02:50:41 +0100 Subject: [PATCH 0174/1913] Inheritance --- README.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/README.md b/README.md index 84ecaeb01..a4c7b6fe5 100644 --- a/README.md +++ b/README.md @@ -812,9 +812,7 @@ class Person: def __init__(self, name, age): self.name = name self.age = age -``` -```python class Employee(Person): def __init__(self, name, age, staff_num): super().__init__(name, age) From d9464bb1de4ba4c5c5faea82dfb4218457a9a6e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 06:11:18 +0100 Subject: [PATCH 0175/1913] File --- README.md | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index a4c7b6fe5..15d2f3651 100644 --- a/README.md +++ b/README.md @@ -1070,11 +1070,23 @@ Open * **`'t'` - Text mode (default).** * **`'b'` - Binary mode.** -### Seek +### File ```python -.seek(0) # Move to the start of the file. -.seek(offset) # Move 'offset' chars/bytes from the start. -.seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. +.seek(0) # Move to the start of the file. +.seek(offset) # Move 'offset' chars/bytes from the start. +.seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. +``` + +```python + = .read(size=-1) # Reads 'size' chars/bytes or until EOF. + = .readline() # Returns a line. + = .readlines() # Returns a list of lines. + = next() # Returns a line using buffer. Do not mix. +``` + +```python +write() # Writes a string or bytes object. +writelines() # Writes a list of strings or bytes objects. ``` ### Read Text from File From ded0139cc4aed037b041a503eff5db1b8ecbec86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 06:20:02 +0100 Subject: [PATCH 0176/1913] Open --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 15d2f3651..81cdeb632 100644 --- a/README.md +++ b/README.md @@ -1053,7 +1053,7 @@ value = args. Open ---- -**Opens file and returns a corresponding file object.** +**Opens a file and returns a corresponding file object.** ```python = open('', mode='r', encoding=None) From a9565be577e8cb8d0ce0adc734ed01f339251005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 06:23:08 +0100 Subject: [PATCH 0177/1913] File --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 81cdeb632..97e603387 100644 --- a/README.md +++ b/README.md @@ -1085,8 +1085,8 @@ Open ``` ```python -write() # Writes a string or bytes object. -writelines() # Writes a list of strings or bytes objects. +.write() # Writes a string or bytes object. +.writelines() # Writes a list of strings or bytes objects. ``` ### Read Text from File From 8762d626d0ee86e571eacdd5e38c18a7c74859c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 06:24:41 +0100 Subject: [PATCH 0178/1913] File --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 97e603387..62b1389fa 100644 --- a/README.md +++ b/README.md @@ -1072,8 +1072,8 @@ Open ### File ```python -.seek(0) # Move to the start of the file. -.seek(offset) # Move 'offset' chars/bytes from the start. +.seek(0) # Moves to the start of the file. +.seek(offset) # Moves 'offset' chars/bytes from the start. .seek(offset, ) # Anchor: 0 start, 1 current pos., 2 end. ``` From f1d3549c058bf14b6befed78c4d290c25bc6cc6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 19:27:27 +0100 Subject: [PATCH 0179/1913] File --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 62b1389fa..0ebe35871 100644 --- a/README.md +++ b/README.md @@ -1088,6 +1088,8 @@ Open .write() # Writes a string or bytes object. .writelines() # Writes a list of strings or bytes objects. ``` +* **No method adds or strips trailing newlines.** +* **Changes are not written until file gets closed.** ### Read Text from File ```python From 03ce3f1323f04860439c6fb0c33afc7815501465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 19:34:06 +0100 Subject: [PATCH 0180/1913] Pathlib --- README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 0ebe35871..09fa82692 100644 --- a/README.md +++ b/README.md @@ -1135,11 +1135,14 @@ cwd = Path() = .is_file() = .is_dir() = .iterdir() +``` + +```python = .glob('') ``` ```python - = str() # Returns path as string. + = str() # Returns path as a string. = .parts # Returns all components as strings. = .resolve() # Returns absolute path without symlinks. ``` From e17334034977aced3c79aceb6a06efb1e0b41af4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 20:24:17 +0100 Subject: [PATCH 0181/1913] File --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 09fa82692..04abcc9a9 100644 --- a/README.md +++ b/README.md @@ -1088,7 +1088,7 @@ Open .write() # Writes a string or bytes object. .writelines() # Writes a list of strings or bytes objects. ``` -* **No method adds or strips trailing newlines.** +* **Methods do not add or strip trailing newlines.** * **Changes are not written until file gets closed.** ### Read Text from File From 315ba59184c44332743a288a9cdc7479b6552052 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Mon, 18 Mar 2019 20:34:56 +0100 Subject: [PATCH 0182/1913] File --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 04abcc9a9..ec3b8022b 100644 --- a/README.md +++ b/README.md @@ -1144,7 +1144,7 @@ cwd = Path() ```python = str() # Returns path as a string. = .parts # Returns all components as strings. - = .resolve() # Returns absolute path without symlinks. + = .resolve() # Returns absolute Path without symlinks. ``` ```python From ae4ad26e1c243864b64b5892e14683cf5757ddec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 00:19:28 +0100 Subject: [PATCH 0183/1913] MemoryView --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec3b8022b..bded4265d 100644 --- a/README.md +++ b/README.md @@ -1360,7 +1360,7 @@ Memory View **Used for accessing the internal data of an object that supports the buffer protocol.** ```python - = memoryview( / / ) + = memoryview() .release() ``` From d1e3e215c2ab2b34d4148e58a1c743fce4cbddba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 00:22:59 +0100 Subject: [PATCH 0184/1913] Revert --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bded4265d..ec3b8022b 100644 --- a/README.md +++ b/README.md @@ -1360,7 +1360,7 @@ Memory View **Used for accessing the internal data of an object that supports the buffer protocol.** ```python - = memoryview() + = memoryview( / / ) .release() ``` From 537a654bafab901c447e1accb647eb87fe47db3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 00:31:31 +0100 Subject: [PATCH 0185/1913] Introspection --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ec3b8022b..3802ffdf8 100644 --- a/README.md +++ b/README.md @@ -1414,7 +1414,7 @@ Introspection ### Variables ```python - = dir() # Names of in-scope variables. + = dir() # Names of variables in current scope. = locals() # Dict of local variables. Also vars(). = globals() # Dict of global variables. ``` From 16faad4ce496c166b97b63bf9d6eec508a1b6559 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 02:38:01 +0100 Subject: [PATCH 0186/1913] Inspect --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3802ffdf8..2828fe3b9 100644 --- a/README.md +++ b/README.md @@ -1430,9 +1430,9 @@ setattr(, '', value) ### Parameters ```python from inspect import signature -sig = signature() -no_of_params = len(sig.parameters) -param_names = list(sig.parameters.keys()) + = signature() +no_of_params = len(.parameters) +param_names = list(.parameters.keys()) ``` From 8221fe4bb6c2e06d2bab8193a5ac044cd4603026 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 02:40:25 +0100 Subject: [PATCH 0187/1913] Inheritance --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 2828fe3b9..506878e4a 100644 --- a/README.md +++ b/README.md @@ -819,6 +819,11 @@ class Employee(Person): self.staff_num = staff_num ``` +```python +>>> Employee.mro() +[, , ] +``` + ### Comparable * **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.** * **That means all objects compare not equal by default.** From f12f6b9bd439e91641c878685be328f8a6d51bcf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 04:16:02 +0100 Subject: [PATCH 0188/1913] Coroutine --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 506878e4a..5b582cd7e 100644 --- a/README.md +++ b/README.md @@ -1573,7 +1573,7 @@ Coroutine --------- * **Similar to generator, but generator pulls data through the pipe with iteration, while coroutine pushes data into the pipeline with send().** * **Coroutines provide more powerful data routing possibilities than iterators.** -* **If you built a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** +* **If you build a collection of simple data processing components, you can glue them together into complex arrangements of pipes, branches, merging, etc.** ### Helper Decorator * **All coroutines must be "primed" by first calling next().** From bdb53e6d83bd09402dbd60e7808c133ec1ae0387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 04:17:56 +0100 Subject: [PATCH 0189/1913] Pycon test --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 5b582cd7e..741750c8c 100644 --- a/README.md +++ b/README.md @@ -819,7 +819,7 @@ class Employee(Person): self.staff_num = staff_num ``` -```python +```pycon >>> Employee.mro() [, , ] ``` From fe74af360d52bb3b822479c1e231679380f215b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 04:18:52 +0100 Subject: [PATCH 0190/1913] Reverte --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 741750c8c..5b582cd7e 100644 --- a/README.md +++ b/README.md @@ -819,7 +819,7 @@ class Employee(Person): self.staff_num = staff_num ``` -```pycon +```python >>> Employee.mro() [, , ] ``` From 34f74498ab9a2e4e334ea2a4139011ed4c1161dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 05:32:36 +0100 Subject: [PATCH 0191/1913] Sequence --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 5b582cd7e..dceabfad8 100644 --- a/README.md +++ b/README.md @@ -869,6 +869,8 @@ class MySequence: return len(self.a) def __getitem__(self, i): return self.a[i] + def __setitem__(self, i, value): + self.a[i] = value def __iter__(self): for el in self.a: yield el From 84705b5af4da5b25d6199e6dc3613ba980fc9021 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jure=20=C5=A0orn?= Date: Tue, 19 Mar 2019 05:52:42 +0100 Subject: [PATCH 0192/1913] Logging --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dceabfad8..c520832ad 100644 --- a/README.md +++ b/README.md @@ -1688,7 +1688,7 @@ from loguru import logger ```python logger.add('debug_{time}.log', colorize=True) # Connects a log file. -logger.add('error_{time}.log', level='ERROR') # Adds another file for errors or higher. +logger.add('error_{time}.log', level='ERROR') # Another file for errors or higher. logger.('A logging message') ``` * **Levels: `'debug'`, `'info'`, `'success'`, `'warning'`, `'error'`, `'critical'`.** @@ -1701,7 +1701,7 @@ rotation=||| * **`''` - Max file size in bytes.** * **`''` - Max age of a file.** * **`'