Skip to content

Commit 89aca79

Browse files
committed
Class, Duck types, Command Line Arguments, Open, Bytes, Profile
1 parent b318d14 commit 89aca79

4 files changed

Lines changed: 84 additions & 85 deletions

File tree

README.md

Lines changed: 40 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -974,20 +974,20 @@ class MyClass:
974974
* **Methods decorated with `'@staticmethod'` receive neither 'self' nor 'cls' argument.**
975975
* **Return value of str() special method should be readable and of repr() unambiguous. If only repr() is defined, it will also be used for str().**
976976

977-
#### Expressions that call object's str() special method:
977+
#### Expressions that call str() special method:
978978
```python
979979
f'{obj}'
980980
print(obj)
981981
logging.warning(obj)
982982
<csv_writer>.writerow([obj])
983983
```
984984

985-
#### Expressions that call object's repr() special method:
985+
#### Expressions that call repr() special method:
986986
```python
987987
f'{obj!r}'
988988
print/str/repr([obj])
989989
print/str/repr({obj: obj})
990-
print/str/repr(<dataclass>(obj))
990+
print/str/repr(MyDataClass(obj))
991991
```
992992

993993
### Subclass
@@ -1040,8 +1040,8 @@ class <class_name>:
10401040
<attr_name>: list/dict/set = field(default_factory=list/dict/set)
10411041
```
10421042
* **Objects can be made [sortable](#sortable) with `'order=True'` and immutable with `'frozen=True'`.**
1043-
* **For object to be [hashable](#hashable), all attributes must be hashable and arg. 'frozen' must be True.**
1044-
* **Function field() is needed because `'<attr_name>: list = []'` would make a list that is shared among all instances. Its 'default_factory' argument accepts any [callable](#callable) object.**
1043+
* **For object to be [hashable](#hashable), all attributes must be hashable and `'frozen'` must be `'True'`.**
1044+
* **Function field() is needed because `'<attr_name>: list = []'` would make a list that is&nbsp;shared among all instances. Its 'default_factory' argument accepts any [callable](#callable) object.**
10451045
* **For attributes of arbitrary type use `'typing.Any'`.**
10461046

10471047
#### Inline:
@@ -1093,7 +1093,7 @@ Duck Types
10931093
### Comparable
10941094
* **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 memory address that is guaranteed to be unique).**
10951095
* **Only the left side object has eq() method called, unless it returns NotImplemented, in which case the right object is consulted. Result is False if both return NotImplemented.**
1096-
* **Ne() automatically works on any object that has eq() defined.**
1096+
* **Method ne() (called by `'!='`) automatically works on any object that has eq() defined.**
10971097

10981098
```python
10991099
class MyComparable:
@@ -1107,7 +1107,7 @@ class MyComparable:
11071107

11081108
### Hashable
11091109
* **Hashable object needs both hash() and eq() methods and its hash value must not change.**
1110-
* **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().**
1110+
* **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 the eq() method.**
11111111

11121112
```python
11131113
class MyHashable:
@@ -1173,7 +1173,7 @@ class Counter:
11731173
* **Sequence iterators returned by the [iter()](#iterator) function, such as list\_iterator, etc.**
11741174
* **Objects returned by the [itertools](#itertools) module, such as count, repeat and cycle.**
11751175
* **Generators returned by the [generator functions](#generator) and [generator expressions](#comprehensions).**
1176-
* **File objects returned by the [open()](#open) function, etc.**
1176+
* **File objects returned by the [open()](#open) function, [SQLite](#sqlite) cursor objects, etc.**
11771177

11781178
### Callable
11791179
* **All functions and classes have a call() method that is executed when they are called.**
@@ -1535,18 +1535,17 @@ arguments = sys.argv[1:]
15351535
### Argument Parser
15361536
```python
15371537
from argparse import ArgumentParser
1538-
p = ArgumentParser(description=<str>) # Returns a parser object.
1539-
p.add_argument('-<short_name>', '--<name>', action='store_true') # Flag (defaults to False).
1540-
p.add_argument('-<short_name>', '--<name>', type=<type>) # Option (defaults to None).
1541-
p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument.
1542-
p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args.
1543-
p.add_argument('<name>', type=<type>, nargs='?') # Optional argument. Also *.
1544-
args = p.parse_args() # Exits on a parsing error.
1545-
<obj> = args.<name> # Returns `<type>(<arg>)`.
1538+
p = ArgumentParser(description=<str>) # Also accepts 'usage' arg.
1539+
p.add_argument('-<char>', '--<name>', action='store_true') # Flag (defaults to False).
1540+
p.add_argument('-<char>', '--<name>', type=<type>) # Option (defaults to None).
1541+
p.add_argument('<name>', type=<type>, nargs=1) # Mandatory first argument.
1542+
p.add_argument('<name>', type=<type>, nargs='+') # Mandatory remaining args.
1543+
p.add_argument('<name>', type=<type>, nargs='?') # Optional argument. Also *.
1544+
args = p.parse_args() # Exits on a parsing error.
1545+
<obj> = args.<name> # Returns `<type>(<arg>)`.
15461546
```
1547-
1548-
* **Use `'help=<str>'` to set argument description that will be displayed in help message.**
1549-
* **Use `'default=<obj>'` to override None as option's or optional argument's default value.**
1547+
* **Use `'help=<str>'` to set argument description that is used by `'-h'`.**
1548+
* **Use `'default=<obj>'` to set option's or argument's default value.**
15501549

15511550

15521551
Open
@@ -1574,7 +1573,7 @@ Open
15741573
### Exceptions
15751574
* **`'FileNotFoundError'` can be raised when reading with `'r'` or `'r+'`.**
15761575
* **`'FileExistsError'` exception can be raised when writing with `'x'`.**
1577-
* **`'IsADirectoryError'` and `'PermissionError'` can be raised by any.**
1576+
* **`'IsADirectoryError'`, `'PermissionError'` can be raised by any.**
15781577
* **`'OSError'` is the parent class of all listed exceptions.**
15791578

15801579
### File Object
@@ -1589,13 +1588,13 @@ Open
15891588
<str/bytes> = <file>.read(size=-1) # Reads 'size' chars/bytes or until the EOF.
15901589
<str/bytes> = <file>.readline() # Returns a line or empty string/bytes on EOF.
15911590
<list> = <file>.readlines() # Returns remaining lines. Also list(<file>).
1592-
<str/bytes> = next(<file>) # Returns a line using a read-ahead buffer.
1591+
<str/bytes> = next(<file>) # Returns a line using the read-ahead buffer.
15931592
```
15941593

15951594
```python
1596-
<file>.write(<str/bytes>) # Writes a str or bytes object to write buffer.
1595+
<file>.write(<str/bytes>) # Writes str or bytes object to write buffer.
15971596
<file>.writelines(<collection>) # Writes a coll. of strings or bytes objects.
1598-
<file>.flush() # Flushes write buffer. Runs every 4096/8192 B.
1597+
<file>.flush() # Flushes write buff. Runs every 4096/8192 B.
15991598
<file>.close() # Closes the file after flushing write buffer.
16001599
```
16011600
* **Methods do not add or strip trailing newlines, not even writelines().**
@@ -1949,26 +1948,26 @@ Bytes
19491948
**An immutable sequence of single bytes. Mutable version is called bytearray.**
19501949

19511950
```python
1952-
<bytes> = b'<str>' # Accepts ASCII characters and \x00 to \xff.
1953-
<int> = <bytes>[index] # Returns the byte as int between 0 and 255.
1954-
<bytes> = <bytes>[<slice>] # Returns bytes even if it has one element.
1955-
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes as a separator.
1951+
<bytes> = b'<str>' # Accepts ASCII characters and \x00 to \xff.
1952+
<int> = <bytes>[index] # Returns the byte as int between 0 and 255.
1953+
<bytes> = <bytes>[<slice>] # Returns bytes even if it has one element.
1954+
<bytes> = <bytes>.join(<coll_of_bytes>) # Joins elements using bytes as a separator.
19561955
```
19571956

19581957
### Encode
19591958
```python
1960-
<bytes> = bytes(<coll_of_ints>) # Passed integers must be between 0 and 255.
1961-
<bytes> = bytes(<str>, 'utf-8') # Encodes the string. Same as <str>.encode().
1962-
<bytes> = bytes.fromhex('<hex>') # Hex pairs can be separated by whitespaces.
1963-
<bytes> = <int>.to_bytes(n_bytes, 'big') # Accepts `byteorder='little', signed=True`.
1959+
<bytes> = bytes(<coll_of_ints>) # Passed integers must be between 0 and 255.
1960+
<bytes> = bytes(<str>, 'utf-8') # Encodes the string. Same as <str>.encode().
1961+
<bytes> = bytes.fromhex('<hex>') # Hex pairs can be separated by whitespaces.
1962+
<bytes> = <int>.to_bytes(n_bytes) # Accepts `byteorder='little', signed=True`.
19641963
```
19651964

19661965
### Decode
19671966
```python
1968-
<list> = list(<bytes>) # Returns a list of ints between 0 and 255.
1969-
<str> = str(<bytes>, 'utf-8') # Returns a string. Same as <bytes>.decode().
1970-
<str> = <bytes>.hex() # Returns hex pairs separated by `sep=<str>`.
1971-
<int> = int.from_bytes(<bytes>, 'big') # Accepts `byteorder='little', signed=True`.
1967+
<list> = list(<bytes>) # Returns a list of ints between 0 and 255.
1968+
<str> = str(<bytes>, 'utf-8') # Returns a string. Same as <bytes>.decode().
1969+
<str> = <bytes>.hex() # Returns hex pairs separated by `sep=<str>`.
1970+
<int> = int.from_bytes(<bytes>) # Accepts `byteorder='little', signed=True`.
19721971
```
19731972

19741973

@@ -2621,12 +2620,12 @@ Line # Hits Time Per Hit % Time Line Contents
26212620

26222621
### Call and Flame Graphs
26232622
```bash
2624-
$ apt/brew install graphviz && pip3 install gprof2dot snakeviz # Or download installer.
2625-
$ tail --lines=+2 test.py > test.py # Removes the first line.
2626-
$ python3 -m cProfile -o test.prof test.py # Runs a tracing profiler.
2627-
$ gprof2dot --format=pstats test.prof | dot -T png -o test.png # Generates a call graph.
2628-
$ xdg-open/open test.png # Displays the call graph.
2629-
$ snakeviz test.prof # Displays a flame graph.
2623+
$ apt install graphviz && pip3 install gprof2dot snakeviz # Or install graphviz.exe.
2624+
$ tail --lines=+2 test.py > test.py # Removes the first line.
2625+
$ python3 -m cProfile -o test.prof test.py # Runs a tracing profiler.
2626+
$ gprof2dot -f pstats test.prof | dot -T png -o test.png # Generates a call graph.
2627+
$ xdg-open test.png # Displays the call graph.
2628+
$ snakeviz test.prof # Displays a flame graph.
26302629
```
26312630

26322631
### Sampling and Memory Profilers

0 commit comments

Comments
 (0)