Skip to content

Commit 316e20d

Browse files
committed
Docs: Better dispatch example
1 parent 0c6f2e8 commit 316e20d

File tree

2 files changed

+35
-23
lines changed

2 files changed

+35
-23
lines changed

README.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,20 @@ class Point:
139139
y: int = 0
140140

141141
@dp
142-
def __init__(self, points: list):
142+
def __init__(self, points: list | tuple):
143143
self.x, self.y = points
144+
145+
@dp
146+
def __init__(self, points: dict):
147+
self.x = points['x']
148+
self.y = points['y']
144149

145-
# Use either the default constructors or the custom constructor
146-
assert Point() == Point(0, 0) == Point([0, 0])
150+
# Test constructors
151+
p0 = Point() # Default constructor
152+
assert p0 == Point(0, 0) # Default constructor
153+
assert p0 == Point([0, 0]) # User constructor
154+
assert p0 == Point((0, 0)) # User constructor
155+
assert p0 == Point({"x": 0, "y": 0}) # User constructor
147156
```
148157

149158

docs/dispatch.rst

Lines changed: 23 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -67,32 +67,35 @@ Then, the group can be used as a decorator for any number of functions.
6767

6868
Dispatch maintains the original name of every function. So, functions of different names will never collide with each other.
6969

70+
The order in which you define functions doesn't matter.
71+
7072
Example:
7173
::
7274

73-
@dp
74-
def f(a: int):
75-
print("Got int:", a)
76-
77-
@dp
78-
def f(a): # No type means Any type
79-
print("Got:", a)
80-
81-
@dp
82-
def g(a: str):
83-
print("Got string in g:", a)
84-
85-
...
75+
dp = Dispatch()
8676

87-
>>> f(1)
88-
Got int: 1
89-
>>> f("a")
90-
Got: a
91-
>>> g("a")
92-
Got string in g: a
77+
@dataclass(frozen=False)
78+
class Point:
79+
x: int = 0
80+
y: int = 0
81+
82+
@dp
83+
def __init__(self, points: list | tuple):
84+
self.x, self.y = points
85+
86+
@dp
87+
def __init__(self, points: dict):
88+
self.x = points['x']
89+
self.y = points['y']
90+
91+
# Test constructors
92+
p0 = Point() # Default constructor
93+
assert p0 == Point(0, 0) # Default constructor
94+
assert p0 == Point([0, 0]) # User constructor
95+
assert p0 == Point((0, 0)) # User constructor
96+
assert p0 == Point({"x": 0, "y": 0}) # User constructor
9397

9498

95-
The order in which you define functions doesn't matter.
9699

97100
Specificity
98101
-----------

0 commit comments

Comments
 (0)