8000 Numbers, Duck types, Bytes, Match statement · gto76/python-cheatsheet@edb7680 · GitHub
[go: up one dir, main page]

Skip to content

Commit edb7680

Browse files
committed
Numbers, Duck types, Bytes, Match statement
1 parent 40c12e4 commit edb7680

File tree

2 files changed

+36
-42
lines changed

2 files changed

+36
-42
lines changed

README.md

Lines changed: 17 additions & 20 deletions
@@ -1205,7 +1202,7 @@ class Counter:
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ String
320320
<list> = <str>.split() # Splits on one or more whitespace characters.
321321
<list> = <str>.split(sep=None, maxsplit=-1) # Splits on 'sep' str at most 'maxsplit' times.
322322
<list> = <str>.splitlines(keepends=False) # On [\n\r\f\v\x1c-\x1e\x85\u2028\u2029] and \r\n.
323-
<str> = <str>.join(<coll_of_strings>) # Joins elements using string as a separator.
323+
<str> = <str>.join(<coll_of_strings>) # Joins elements by using string as a separator.
324324
```
325325

326326
```python
@@ -524,8 +524,7 @@ from math import log, log10, log2 # Log accepts base as second arg.
524524

525525
### Statistics
526526
```python
527-
from statistics import mean, median, mode # Mode returns the most common value.
528-
from statistics import variance, stdev # Also: pvariance, pstdev, quantiles.
527+
from statistics import mean, median, mode # Also: variance, stdev, quantiles.
529528
```
530529

531530
### Random
@@ -606,7 +605,7 @@ import zoneinfo, dateutil.tz
606605
* **Times and datetimes that have defined timezone are called aware and ones that don't, naive. If object is naive, it is presumed to be in the system's timezone!**
607606
* **`'fold=1'` means the second pass in case of time jumping back for one hour.**
608607
* **Timedelta normalizes arguments to ±days, seconds (< 86 400) and microseconds (< 1M). Its str() method returns `'[±D, ]H:MM:SS[.…]'` and total_seconds() a float of all seconds.**
609-
* **Use `'<D/DT>.weekday()'` to get the day of the week as an int, with Monday being 0.**
608+
* **Use `'<D/DT>.weekday()'` to get the day of the week as an integer, with Monday being 0.**
610609

611610
### Now
612611
```python
@@ -1076,7 +1075,7 @@ class Person:
10761075
```
10771076

10781077
### Slots
1079-
**Mechanism that restricts objects to attributes listed in 'slots', reduces their memory footprint.**
1078+
**Mechanism that restricts objects to attributes listed in 'slots'.**
10801079

10811080
```python
10821081
class MyClassWithSlots:
@@ -1097,8 +1096,7 @@ Duck Types
10971096
**A duck type is an implicit type that prescribes a set of special methods. Any object that has those methods defined is considered a member of that duck type.**
10981097

10991098
### Comparable
1100-
* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`.**
1101-
* **That means all user-defined objects compare not equal by default.**
1099+
* **If eq() method is not overridden, it returns `'id(self) == id(other)'`, which is the same as `'self is other'`. That means all user-defined objects compare not equal by default, because id() returns object's unique identification number (its memory address).**
11021100
* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. False is returned if both return NotImplemented.**
11031101
* **Ne() automatically works on any object that has eq() defined.**
11041102

@@ -1113,9 +1111,8 @@ class MyComparable:
11131111
```
11141112

11151113
### Hashable
1116-
* **Hashable object needs both hash() and eq() methods and its hash value should never change.**
1117-
* **Hashable objects that compare equal must have the same hash value, meaning default hash() that returns `'id(self)'` will not do.**
1118-
* **That is why Python automatically makes classes unhashable if you only implement eq().**
1114+
* **Hashable object needs both hash() and eq() methods and its hash value must not change.**
1115+
* **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().**
11191116

11201117
```python
11211118
class MyHashable:
@@ -1133,7 +1130,7 @@ class MyHashable:
11331130
```
11341131

11351132
### Sortable
1136-
* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods and the rest will be automatically generated.**
1133+
* **With 'total_ordering' decorator, you only need to provide eq() and one of lt(), gt(), le() or ge() special methods (used by <, >, <=, >=) and the rest will be automatically generated.**
11371134
* **Functions sorted() and min() only require lt() method, while max() only requires gt(). However, it is best to define them all so that confusion doesn't arise in other contexts.**
11381135
* **When two lists, strings or dataclasses are compared, their values get compared in order until a pair of unequal values is found. The comparison of this two values is then returned. The shorter sequence is considered smaller in case of all values being equal.**
11391136
* **To sort collection of strings in proper alphabetical order pass `'key=locale.strxfrm'` to sorted() after running `'locale.setlocale(locale.LC_COLLATE, "en_US.UTF-8")'`.**
12051202
### Context Manager
12061203
* **With statements only work on objects that have enter() and exit() special methods.**
12071204
* **Enter() should lock the resources and optionally return an object.**
1208-
* **Exit() should release the resources.**
1205+
* **Exit() should release the resources (for example close a file).**
12091206
* **Any exception that happens inside the with block is passed to the exit() method.**
12101207
* **The exit() method can suppress the exception by returning a true value.**
12111208
```python
@@ -1530,7 +1527,7 @@ Input
15301527
```
15311528
* **Reads a line from the user input or pipe if present (trailing newline gets stripped).**
15321529
* **If argument is passed, it gets printed to the standard output before input is read.**
1533-
* **EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if input stream is exhausted.**
1530+
* **EOFError is raised if user hits EOF (ctrl-d/ctrl-z⏎) or if stream is already exhausted.**
15341531

15351532

15361533
Command Line Arguments
@@ -1955,22 +1952,22 @@ Bytes
19551952

19561953
```python
19571954
<bytes> = b'<str>' # Only accepts ASCII characters and \x00-\xff.
1958-
<int> = <bytes>[index] # Returns an int in range from 0 to 255.
1955+
<int> = <bytes>[index] # Returns an integer in range from 0 to 255.
19591956
<bytes> = <bytes>[<slice>] # Returns bytes even if it has only one element.
1960-
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes as a separator.
1957+
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements by using bytes as a separator.
19611958
```
19621959

19631960
### Encode
19641961
```python
1965-
<bytes> = bytes(<coll_of_ints>) # Ints must be in range from 0 to 255.
1962+
<bytes> = bytes(<coll_of_ints>) # Integers must be in range from 0 to 255.
19661963
<bytes> = bytes(<str>, 'utf-8') # Encodes the string. Also <str>.encode().
19671964
<bytes> = bytes.fromhex('<hex>') # Hex pairs can be separated by whitespaces.
19681965
<bytes> = <int>.to_bytes(n_bytes, …) # `byteorder='big/little', signed=False`.
19691966
```
19701967

19711968
### Decode
19721969
```python
1973-
<list> = list(<bytes>) # Returns ints in range from 0 to 255.
1970+
<list> = list(<bytes>) # Returns integers in range from 0 to 255.
19741971
<str> = str(<bytes>, 'utf-8') # Returns a string. Also <bytes>.decode().
19751972
<str> = <bytes>.hex() # Returns hex pairs. Accepts `sep=<str>`.
19761973
<int> = int.from_bytes(<bytes>, …) # `byteorder='big/little', signed=False`.
@@ -2059,7 +2056,7 @@ Memory View
20592056

20602057
```python
20612058
<mview> = memoryview(<bytes/bytearray/array>) # Immutable if bytes is passed, else mutable.
2062-
<obj> = <mview>[index] # Returns int or float. Bytes if format is 'c'.
2059+
<obj> = <mview>[index] # Returns int/float. Bytes if format is 'c'.
20632060
<mview> = <mview>[<slice>] # Returns memoryview with rearranged elements.
20642061
<mview> = <mview>.cast('<typecode>') # Only works between B/b/c and other types.
20652062
<mview>.release() # Releases memory buffer of the base object.
@@ -2126,7 +2123,7 @@ first_element = op.methodcaller('pop', 0)(<list>)
21262123

21272124
Match Statement
21282125
---------------
2129-
**Executes the first block with matching pattern. Added in Python 3.10.**
2126+
**Executes the first block with matching pattern.**
21302127

21312128
```python
21322129
match <object/expression>:
@@ -2147,7 +2144,7 @@ match <object/expression>:
21472144
<mapping_patt> = {<value_pattern>: <patt>, ...} # Matches dictionary with matching items.
21482145
<class_pattern> = <type>(<attr_name>=<patt>, ...) # Matches object with matching attributes.
21492146
```
2150-
* **Sequence pattern can also be written as a tuple.**
2147+
* **Sequence pattern can also be written as a tuple, i.e. `'(<patt_1>, [...])'`.**
21512148
* **Use `'*<name>'` and `'**<name>'` in sequence/mapping patterns to bind remaining items.**
21522149
* **Sequence pattern must match all items of the collection, while mapping pattern does not.**
21532150
* **Patterns can be surrounded with brackets to override precedence (`'|'` > `'as'` > `','`).**

0 commit comments

Comments
 (0)
0