Skip to content

Commit 6a22233

Browse files
committed
Duck types, Array, Mview, Deque, Operator, Match, Logging
1 parent 576b9f4 commit 6a22233

File tree

3 files changed

+77
-81
lines changed

3 files changed

+77
-81
lines changed

README.md

Lines changed: 36 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1262,8 +1262,7 @@ class MyCollection:
12621262
```
12631263

12641264
### Sequence
1265-
* **Only required methods are getitem() and len().**
1266-
* **Getitem() should return an item at the passed index or raise IndexError.**
1265+
* **Only required methods are getitem() and len(). Getitem() should return the item at the passed index or raise IndexError (this excludes dictionaries because they accept keys).**
12671266
* **Iter() and contains() automatically work on any object that has getitem() defined.**
12681267
* **Reversed() automatically works on any object that has getitem() and len() defined. It returns reversed iterator of object's items.**
12691268
```python
@@ -1287,8 +1286,8 @@ class MySequence:
12871286
* **Passing ABC Iterable to isinstance() or issubclass() only checks whether object/class has special method iter(), while ABC Collection checks for iter(), contains() and len().**
12881287

12891288
### ABC Sequence
1290-
* **It's a richer interface than the basic sequence.**
1291-
* **Extending it generates iter(), contains(), reversed(), index() and count().**
1289+
* **It's a richer interface than the basic sequence that also just requires getitem() and len().**
1290+
* **Extending it generates iter(), contains(), reversed(), index() and count() special methods.**
12921291
* **Unlike `'abc.Iterable'` and `'abc.Collection'`, it is not a duck type. That is why `'issubclass(MySequence, abc.Sequence)'` would return False even if MySequence had all the methods defined. It however recognizes list, tuple, range, str, bytes, bytearray, array, memoryview and deque, since they are registered as Sequence's virtual subclasses.**
12931292
```python
12941293
from collections import abc
@@ -1885,7 +1884,7 @@ import sqlite3
18851884
### Read
18861885
```python
18871886
<cursor> = <conn>.execute('<query>') # Can raise a subclass of sqlite3.Error.
1888-
<tuple> = <cursor>.fetchone() # Returns next row. Also next(<cursor>).
1887+
<tuple> = <cursor>.fetchone() # Returns the next row. Also next(<cursor>).
18891888
<list> = <cursor>.fetchall() # Returns remaining rows. Also list(<cursor>).
18901889
```
18911890

@@ -1905,7 +1904,7 @@ with <conn>: # Exits the block with commit() o
19051904
### Placeholders
19061905
```python
19071906
<conn>.execute('<query>', <list/tuple>) # Replaces every question mark with an item.
1908-
<conn>.execute('<query>', <dict/namedtuple>) # Replaces every :<key> with matching value.
1907+
<conn>.execute('<query>', <dict/namedtuple>) # Replaces every :<key> with a matching value.
19091908
<conn>.executemany('<query>', <coll_of_coll>) # Runs execute() once for each collection.
19101909
```
19111910
* **Passed values can be of type str, int, float, bytes, None, or bool (stored as 1 or 0).**
@@ -2029,21 +2028,21 @@ b'\x00\x01\x00\x02\x00\x00\x00\x03'
20292028

20302029
Array
20312030
-----
2032-
**List that can only hold numbers of a predefined type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.**
2031+
**List that can only hold numbers of a predefined C type. Available types and their minimum sizes in bytes are listed above. Type sizes and byte order are always determined by the system, however bytes of each element can be reversed with byteswap() method.**
20332032

20342033
```python
20352034
from array import array
20362035
```
20372036

20382037
```python
2039-
<array> = array('<typecode>', <coll_of_nums>) # Creates array from collection of numbers.
2040-
<array> = array('<typecode>', <bytes>) # Writes passed bytes to array's memory.
2038+
<array> = array('<typecode>', <coll_of_nums>) # Creates an array from collection of numbers.
2039+
<array> = array('<typecode>', <bytes>) # Writes passed bytes to the array's memory.
20412040
<array> = array('<typecode>', <array>) # Treats passed array as a sequence of numbers.
2042-
<array>.fromfile(<file>, n_items) # Appends file's contents to array's memory.
2041+
<array>.fromfile(<file>, n_items) # Appends file contents to the array's memory.
20432042
```
20442043

20452044
```python
2046-
<bytes> = bytes(<array>) # Returns a copy of array's memory.
2045+
<bytes> = bytes(<array>) # Returns a copy of array's memory as bytes.
20472046
<file>.write(<array>) # Writes array's memory to the binary file.
20482047
```
20492048

@@ -2054,7 +2053,7 @@ Memory View
20542053

20552054
```python
20562055
<mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes is passed, else mutable.
2057-
<obj> = <mview>[index] # Returns int/float. Bytes if format is 'c'.
2056+
<obj> = <mview>[index] # Returns ints/floats. Bytes if format is 'c'.
20582057
<mview> = <mview>[<slice>] # Returns memoryview with rearranged elements.
20592058
<mview> = <mview>.cast('<typecode>') # Only works between B/b/c and other types.
20602059
<mview>.release() # Releases memory buffer of the base object.
@@ -2069,7 +2068,7 @@ Memory View
20692068

20702069
```python
20712070
<list> = list(<mview>) # Returns a list of ints, floats or bytes.
2072-
<str> = str(<mview>, 'utf-8') # Treats memoryview as a bytes object.
2071+
<str> = str(<mview>, 'utf-8') # Treats passed memoryview as a bytes object.
20732072
<str> = <mview>.hex() # Returns hex pairs. Accepts `sep=<str>`.
20742073
```
20752074

@@ -2085,27 +2084,27 @@ from collections import deque
20852084
```python
20862085
<deque> = deque(<collection>) # Use `maxlen=<int>` to set size limit.
20872086
<deque>.appendleft(<el>) # Opposite element is dropped if full.
2088-
<deque>.extendleft(<collection>) # Passed collection gets reversed.
2089-
<deque>.rotate(n=1) # Last element becomes first.
2087+
<deque>.extendleft(<collection>) # Appends elements in reversed order.
2088+
<deque>.rotate(n=1) # Last element becomes the first one.
20902089
<el> = <deque>.popleft() # Raises IndexError if deque is empty.
20912090
```
20922091

20932092

20942093
Operator
20952094
--------
2096-
**Module of functions that provide the functionality of operators. Functions are grouped by operator precedence, from least to most binding. Functions and operators in lines 1, 3 and 5 are also ordered by precedence within a group.**
2095+
**Module of functions that provide the functionality of operators. Functions are grouped by operator precedence, from least to most binding. Functions and operators in first, third and fifth line are also ordered by precedence within a group.**
20972096
```python
20982097
import operator as op
20992098
```
21002099

21012100
```python
21022101
<bool> = op.not_(<obj>) # or, and, not (or/and missing)
21032102
<bool> = op.eq/ne/lt/ge/is_/is_not/contains(<obj>, <obj>) # ==, !=, <, >=, is, is not, in
2104-
<obj> = op.or_/xor/and_(<int/set>, <int/set>) # |, ^, &
2105-
<int> = op.lshift/rshift(<int>, <int>) # <<, >>
2106-
<obj> = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>) # +, -, *, /, //, %
2107-
<num> = op.neg/invert(<num>) # -, ~
2108-
<num> = op.pow(<num>, <num>) # **
2103+
<obj> = op.or_/xor/and_(<int/set>, <int/set>) # |, ^, & (sorted by precedence)
2104+
<int> = op.lshift/rshift(<int>, <int>) # <<, >> (i.e. <int> << n_bits)
2105+
<obj> = op.add/sub/mul/truediv/floordiv/mod(<obj>, <obj>) # +, -, *, /, //, % (two groups)
2106+
<num> = op.neg/invert(<num>) # -, ~ (negate and bitwise not)
2107+
<num> = op.pow(<num>, <num>) # ** (pow() accepts 3 arguments)
21092108
<func> = op.itemgetter/attrgetter/methodcaller(<obj> [, ...]) # [index/key], .name, .name([…])
21102109
```
21112110

@@ -2137,16 +2136,15 @@ match <object/expression>:
21372136
<wildcard_patt> = _ # Matches any object. Useful in last case.
21382137
<capture_patt> = <name> # Matches any object and binds it to name.
21392138
<as_pattern> = <pattern> as <name> # Binds match to name. Also <type>(<name>).
2140-
<or_pattern> = <pattern> | <pattern> [| ...] # Matches any of the patterns.
2141-
<sequence_patt> = [<pattern>, ...] # Matches sequence with matching items.
2142-
<mapping_patt> = {<value_pattern>: <patt>, ...} # Matches dictionary with matching items.
2143-
<class_pattern> = <type>(<attr_name>=<patt>, ...) # Matches object with matching attributes.
2139+
<or_pattern> = <pattern> | <pattern> [| ...] # Matches if any of listed patterns match.
2140+
<sequence_patt> = [<pattern>, ...] # Matches a sequence. All items must match.
2141+
<mapping_patt> = {<value_pattern>: <patt>, ...} # Matches a dict that has matching items.
2142+
<class_pattern> = <type>(<attr_name>=<patt>, ...) # Matches an object if attributes match.
21442143
```
2145-
* **Sequence pattern can also be written as a tuple, i.e. `'(<patt_1>, [...])'`.**
2144+
* **Sequence pattern can also be written as a tuple, i.e. `'(<pattern_1>, [...])'`.**
21462145
* **Use `'*<name>'` and `'**<name>'` in sequence/mapping patterns to bind remaining items.**
21472146
* **Sequence pattern must match all items of the collection, while mapping pattern does not.**
21482147
* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).**
2149-
* **Built-in types allow a single positional pattern that is matched against the entire object.**
21502148
* **All names that are bound in the matching case, as well as variables initialized in its block, are visible after the match statement.**
21512149

21522150
### Example
@@ -2169,9 +2167,9 @@ import logging as log
21692167

21702168
```python
21712169
log.basicConfig(filename=<path>, level='DEBUG') # Configures the root logger (see Setup).
2172-
log.debug/info/warning/error/critical(<str>) # Sends message to the root logger.
2173-
<Logger> = log.getLogger(__name__) # Returns logger named after the module.
2174-
<Logger>.<level>(<str>) # Sends message to the logger.
2170+
log.debug/info/warning/error/critical(<str>) # Sends passed message to the root logger.
2171+
<Logger> = log.getLogger(__name__) # Returns a logger named after the module.
2172+
<Logger>.<level>(<str>) # Sends the message. Same levels as above.
21752173
<Logger>.exception(<str>) # Error() that appends caught exception.
21762174
```
21772175

@@ -2186,11 +2184,11 @@ log.basicConfig(
21862184
```
21872185

21882186
```python
2189-
<Formatter> = log.Formatter('<format>') # Creates a Formatter.
2190-
<Handler> = log.FileHandler(<path>, mode='a') # Creates a Handler. Also `encoding=None`.
2191-
<Handler>.setFormatter(<Formatter>) # Adds Formatter to the Handler.
2192-
<Handler>.setLevel(<int/str>) # Processes all messages by default.
2193-
<Logger>.addHandler(<Handler>) # Adds Handler to the Logger.
2187+
<Formatter> = log.Formatter('<format>') # Formats messages according to format str.
2188+
<Handler> = log.FileHandler(<path>, mode='a') # Creates a handler. Also `encoding=None`.
2189+
<Handler>.setFormatter(<Formatter>) # Assigns the formatter to the handler.
2190+
<Handler>.setLevel(<int/str>) # It will process all messages by default.
2191+
<Logger>.addHandler(<Handler>) # Appends handler to logger's 'handlers'.
21942192
<Logger>.setLevel(<int/str>) # What is sent to its/ancestors' handlers.
21952193
<Logger>.propagate = <bool> # Cuts off ancestors' handlers if False.
21962194
```
@@ -2333,9 +2331,9 @@ import asyncio as aio
23332331
```python
23342332
import asyncio, collections, curses, curses.textpad, enum, random
23352333

2336-
P = collections.namedtuple('P', 'x y') # Position
2337-
D = enum.Enum('D', 'n e s w') # Direction
2338-
W, H = 15, 7 # Width, Height
2334+
P = collections.namedtuple('P', 'x y') # Position (x and y coordinates).
2335+
D = enum.Enum('D', 'n e s w') # Direction (north, east, etc.).
2336+
W, H = 15, 7 # Width and height constants.
23392337

23402338
def main(screen):
23412339
curses.curs_set(0) # Makes cursor invisible.

0 commit comments

Comments
 (0)