Skip to content

Commit 00f7728

Browse files
committed
Decorator, Duck types, Enum, Exceptions
1 parent d044e60 commit 00f7728

File tree

4 files changed

+69
-73
lines changed

4 files changed

+69
-73
lines changed

README.md

Lines changed: 30 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -640,9 +640,9 @@ import zoneinfo, dateutil.tz
640640

641641
### Decode
642642
```python
643-
<str> = <D/T/DT>.isoformat(sep='T') # Also `timespec='auto/hours/minutes/seconds/…'`.
643+
<str> = <D/T/DT>.isoformat(sep='T') # Also `timespec='auto/hours/minutes/seconds…'`.
644644
<str> = <D/T/DT>.strftime('<format>') # Custom string representation of the object.
645-
<int> = <D/DT>.toordinal() # Days since NYE 1, ignoring time and timezone.
645+
<int> = <D/DT>.toordinal() # Days since NYE 1. Ignores DT's time and zone.
646646
<float> = <DTn>.timestamp() # Seconds since the Epoch, from local naive DT.
647647
<float> = <DTa>.timestamp() # Seconds since the Epoch, from aware datetime.
648648
```
@@ -794,7 +794,7 @@ from functools import reduce
794794

795795
### Walrus Operator
796796
```python
797-
>>> [i for a in '0123' if (i := int(a)) > 0] # Assigns to variable mid-sentence.
797+
>>> [i for ch in '0123' if (i := int(ch)) > 0] # Assigns to variable mid-sentence.
798798
[1, 2, 3]
799799
```
800800

@@ -885,8 +885,7 @@ def get_counter():
885885

886886
Decorator
887887
---------
888-
* **A decorator takes a function, adds some functionality and returns it.**
889-
* **It can be any [callable](#callable), but is usually implemented as a function that returns a [closure](#closure).**
888+
**A decorator takes a function, adds some functionality and returns it. It can be any [callable](#callable), but is usually implemented as a function that returns a [closure](#closure).**
890889

891890
```python
892891
@decorator_name
@@ -1094,7 +1093,7 @@ Duck Types
10941093
**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.**
10951094

10961095
### Comparable
1097-
* **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).**
1096+
* **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 unique during its lifetime).**
10981097
* **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.**
10991098
* **Ne() automatically works on any object that has eq() defined.**
11001099

@@ -1199,8 +1198,8 @@ class Counter:
11991198

12001199
### Context Manager
12011200
* **With statements only work on objects that have enter() and exit() special methods.**
1202-
* **Enter() should lock the resources and optionally return an object.**
1203-
* **Exit() should release the resources (for example close a file).**
1201+
* **Enter() should lock the resources and optionally return an object (file, lock, etc.).**
1202+
* **Exit() should release the resources (for example close a file, release a lock, etc.).**
12041203
* **Any exception that happens inside the with block is passed to the exit() method.**
12051204
* **The exit() method can suppress the exception by returning a true value.**
12061205
```python
@@ -1332,8 +1331,8 @@ from enum import Enum, auto
13321331
```python
13331332
class <enum_name>(Enum):
13341333
<member_name> = auto() # Increment of the last numeric value or 1.
1335-
<member_name> = <value> # Values don't have to be hashable.
1336-
<member_name> = <el_1>, <el_2> # Values can be collections (this is a tuple).
1334+
<member_name> = <value> # Values don't have to be hashable or unique.
1335+
<member_name> = <el_1>, <el_2> # Values can be collections, like this tuple.
13371336
```
13381337
* **Methods receive the member they were called on as the 'self' argument.**
13391338
* **Accessing a member named after a reserved keyword causes SyntaxError.**
@@ -1342,20 +1341,20 @@ class <enum_name>(Enum):
13421341
<member> = <enum>.<member_name> # Returns a member. Raises AttributeError.
13431342
<member> = <enum>['<member_name>'] # Returns a member. Raises KeyError.
13441343
<member> = <enum>(<value>) # Returns a member. Raises ValueError.
1345-
<str> = <member>.name # Returns member's name.
1346-
<obj> = <member>.value # Returns member's value.
1344+
<str> = <member>.name # Returns the member's name.
1345+
<obj> = <member>.value # Returns the member's value.
13471346
```
13481347

13491348
```python
1350-
<list> = list(<enum>) # Returns enum's members.
1351-
<list> = [a.name for a in <enum>] # Returns enum's member names.
1352-
<list> = [a.value for a in <enum>] # Returns enum's member values.
1349+
<list> = list(<enum>) # Returns a list of enum's members.
1350+
<list> = <enum>._member_names_ # Returns a list of member names.
1351+
<list> = [m.value for m in <enum>] # Returns a list of member values.
13531352
```
13541353

13551354
```python
1356-
<enum> = type(<member>) # Returns member's enum.
1357-
<iter> = itertools.cycle(<enum>) # Returns endless iterator of members.
1358-
<member> = random.choice(list(<enum>)) # Returns a random member.
1355+
<enum> = type(<member>) # Returns an enum. Also <memb>.__class__.
1356+
<iter> = itertools.cycle(<enum>) # Returns an endless iterator of members.
1357+
<member> = random.choice(list(<enum>)) # Randomly selects one of the members.
13591358
```
13601359

13611360
### Inline
@@ -1397,8 +1396,8 @@ finally:
13971396
```
13981397
* **Code inside the `'else'` block will only be executed if `'try'` block had no exceptions.**
13991398
* **Code inside the `'finally'` block will always be executed (unless a signal is received).**
1400-
* **All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try statement (only function block delimits scope).**
1401-
* **To catch signals use `'signal.signal(signal_number, <func>)'`.**
1399+
* **All variables that are initialized in executed blocks are also visible in all subsequent blocks, as well as outside the try statement (only a function block delimits scope).**
1400+
* **To catch signals use `'signal.signal(signal_number, handler_function)'`.**
14021401

14031402
### Catching Exceptions
14041403
```python
@@ -1407,10 +1406,10 @@ except <exception> as <name>: ...
14071406
except (<exception>, [...]): ...
14081407
except (<exception>, [...]) as <name>: ...
14091408
```
1410-
* **Also catches subclasses of the exception.**
1411-
* **Use `'traceback.print_exc()'` to print the full error message to stderr.**
1412-
* **Use `'print(<name>)'` to print just the cause of the exception (its arguments).**
1413-
* **Use `'logging.exception(<str>)'` to log the passed message, followed by the full error message of the caught exception. For details see [Logging](#logging).**
1409+
* **Also catches subclasses, e.g. `'IndexError'` is caught by `'except LookupError:'`.**
1410+
* **Use `'traceback.print_exc()'` to print the full error message to standard error stream.**
1411+
* **Use `'print(<name>)'` to print just the cause of the exception (i.e. its arguments).**
1412+
* **Use `'logging.exception(<str>)'` to log the passed message, followed by the full error message of the caught exception. For details about setting up the logger see [Logging](#logging).**
14141413
* **Use `'sys.exc_info()'` to get exception type, object, and traceback of caught exception.**
14151414

14161415
### Raising Exceptions
@@ -1433,33 +1432,33 @@ arguments = <name>.args
14331432
exc_type = <name>.__class__
14341433
filename = <name>.__traceback__.tb_frame.f_code.co_filename
14351434
func_name = <name>.__traceback__.tb_frame.f_code.co_name
1436-
line = linecache.getline(filename, <name>.__traceback__.tb_lineno)
1435+
line_str = linecache.getline(filename, <name>.__traceback__.tb_lineno)
14371436
trace_str = ''.join(traceback.format_tb(<name>.__traceback__))
14381437
error_msg = ''.join(traceback.format_exception(type(<name>), <name>, <name>.__traceback__))
14391438
```
14401439

14411440
### Built-in Exceptions
14421441
```text
14431442
BaseException
1444-
+-- SystemExit # Raised by the sys.exit() function.
1445-
+-- KeyboardInterrupt # Raised when the user hits the interrupt key (ctrl-c).
1443+
+-- SystemExit # Raised by the sys.exit() function (see #Exit for details).
1444+
+-- KeyboardInterrupt # Raised when the user hits the interrupt key (control-c).
14461445
+-- Exception # User-defined exceptions should be derived from this class.
14471446
+-- ArithmeticError # Base class for arithmetic errors such as ZeroDivisionError.
14481447
+-- AssertionError # Raised by `assert <exp>` if expression returns false value.
14491448
+-- AttributeError # Raised when object doesn't have requested attribute/method.
14501449
+-- EOFError # Raised by input() when it hits an end-of-file condition.
14511450
+-- LookupError # Base class for errors when a collection can't find an item.
1452-
| +-- IndexError # Raised when a sequence index is out of range.
1451+
| +-- IndexError # Raised when index of a sequence (list/str) is out of range.
14531452
| +-- KeyError # Raised when a dictionary key or set element is missing.
14541453
+-- MemoryError # Out of memory. May be too late to start deleting variables.
14551454
+-- NameError # Raised when nonexistent name (variable/func/class) is used.
14561455
| +-- UnboundLocalError # Raised when local name is used before it's being defined.
1457-
+-- OSError # Errors such as FileExistsError/TimeoutError (see #Open).
1458-
| +-- ConnectionError # Errors such as BrokenPipeError/ConnectionAbortedError.
1456+
+-- OSError # Errors such as FileExistsError, TimeoutError (see #Open).
1457+
| +-- ConnectionError # Errors such as BrokenPipeError and ConnectionAbortedError.
14591458
+-- RuntimeError # Raised by errors that don't fall into other categories.
14601459
| +-- NotImplementedEr… # Can be raised by abstract methods or by unfinished code.
14611460
| +-- RecursionError # Raised if max recursion depth is exceeded (3k by default).
1462-
+-- StopIteration # Raised when an empty iterator is passed to next().
1461+
+-- StopIteration # Raised when exhausted (empty) iterator is passed to next().
14631462
+-- TypeError # When an argument of the wrong type is passed to function.
14641463
+-- ValueError # When argument has the right type but inappropriate value.
14651464
```

0 commit comments

Comments
 (0)