forked from huangsam/ultimate-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharg_enforcement.py
More file actions
243 lines (188 loc) · 8.17 KB
/
arg_enforcement.py
File metadata and controls
243 lines (188 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""
Positional-only and keyword-only parameters allow you to enforce how
arguments are passed to a function. This feature helps prevent misuse
of function APIs and makes code more maintainable.
- Positional-only parameters (/) were introduced in Python 3.8 (PEP 570)
- Keyword-only parameters (*) were introduced in Python 3.0 (PEP 3102)
These features give you fine-grained control over your function signatures.
"""
def traditional_function(a, b, c):
"""A traditional function where all parameters can be passed either way.
This function accepts arguments positionally or by keyword name.
While flexible, this can lead to API instability if parameter names change.
"""
return a + b + c
def positional_only(a, b, /):
"""Function with positional-only parameters.
The / symbol marks that parameters before it MUST be passed positionally.
This is useful when parameter names are not meaningful or when you want
to reserve the right to change parameter names without breaking callers.
Parameters before / cannot be passed as keyword arguments.
"""
return a + b
def keyword_only(*, x, y):
"""Function with keyword-only parameters.
The * symbol marks that parameters after it MUST be passed by keyword.
This is useful for improving readability at call sites and preventing
accidental argument order mistakes.
Parameters after * cannot be passed positionally.
"""
return x * y
def mixed_parameters(pos_only, /, pos_or_kw, *, kw_only):
"""Function that combines all parameter types.
- pos_only: Must be passed positionally (before /)
- pos_or_kw: Can be passed either way (between / and *)
- kw_only: Must be passed by keyword (after *)
This gives maximum control over the function interface.
"""
return f"{pos_only}-{pos_or_kw}-{kw_only}"
def positional_with_defaults(a, b=10, /):
"""Positional-only parameters can have default values.
Default values work the same way as in traditional functions,
but the parameters still must be passed positionally if provided.
"""
return a + b
def keyword_with_defaults(*, x=5, y=3):
"""Keyword-only parameters can have default values.
When providing arguments, you must use the keyword names.
"""
return x**y
def complex_signature(a, b, /, c, d=10, *, e, f=20):
"""A function demonstrating a complex but valid signature.
- a, b: positional-only
- c: positional-or-keyword (no default)
- d: positional-or-keyword (with default)
- e: keyword-only (no default)
- f: keyword-only (with default)
"""
return a + b + c + d + e + f
def main() -> None:
# Traditional function: can be called either way
assert traditional_function(1, 2, 3) == 6
assert traditional_function(a=1, b=2, c=3) == 6
assert traditional_function(1, b=2, c=3) == 6
# Positional-only function: must use positional arguments
assert positional_only(5, 3) == 8
# Trying to use keyword arguments with positional-only parameters
# will raise a TypeError
positional_error = False
try:
# This will fail because 'a' and 'b' are positional-only
positional_only(a=5, b=3) # type: ignore [call-arg]
except TypeError:
positional_error = True
assert positional_error is True
# You also can't mix positional and keyword for positional-only params
positional_error2 = False
try:
# This will fail because 'b' is positional-only
positional_only(5, b=3) # type: ignore [call-arg]
except TypeError:
positional_error2 = True
assert positional_error2 is True
# Keyword-only function: must use keyword arguments
assert keyword_only(x=4, y=5) == 20
# Trying to use positional arguments with keyword-only parameters
# will raise a TypeError
keyword_error = False
try:
# This will fail because 'x' and 'y' are keyword-only
keyword_only(4, 5) # type: ignore [misc]
except TypeError:
keyword_error = True
assert keyword_error is True
# Mixed parameters demonstrate all three types
result = mixed_parameters("first", "second", kw_only="third")
assert result == "first-second-third"
# The middle parameter can be passed either way
result2 = mixed_parameters("first", pos_or_kw="second", kw_only="third")
assert result2 == "first-second-third"
# But positional-only must be positional
mixed_error = False
try:
mixed_parameters(pos_only="first", pos_or_kw="second", kw_only="third") # type: ignore [call-arg]
except TypeError:
mixed_error = True
assert mixed_error is True
# And keyword-only must be keyword
mixed_error2 = False
try:
mixed_parameters("first", "second", "third") # type: ignore [misc]
except TypeError:
mixed_error2 = True
assert mixed_error2 is True
# Positional-only with defaults
assert positional_with_defaults(5) == 15 # Uses default b=10
assert positional_with_defaults(5, 20) == 25 # Overrides b with 20
# Even with defaults, must use positional syntax
positional_default_error = False
try:
positional_with_defaults(a=5, b=20) # type: ignore [call-arg]
except TypeError:
positional_default_error = True
assert positional_default_error is True
# Keyword-only with defaults
assert keyword_with_defaults() == 125 # Uses defaults: 5^3
assert keyword_with_defaults(x=2) == 8 # 2^3
assert keyword_with_defaults(y=2) == 25 # 5^2
assert keyword_with_defaults(x=3, y=4) == 81 # 3^4
# Must still use keyword syntax even when providing defaults
keyword_default_error = False
try:
keyword_with_defaults(2, 3) # type: ignore [misc]
except TypeError:
keyword_default_error = True
assert keyword_default_error is True
# Complex signature: demonstrating all parameter types
# Minimal call with required params only
result3 = complex_signature(1, 2, 3, e=4)
assert result3 == 40 # 1+2+3+10(default)+4+20(default)
# Providing all parameters
result4 = complex_signature(1, 2, 3, 4, e=5, f=6)
assert result4 == 21 # 1+2+3+4+5+6
# Middle parameter 'c' can be passed by keyword
result5 = complex_signature(1, 2, c=3, e=4)
assert result5 == 40
# Parameter 'd' can also be passed by keyword
result6 = complex_signature(1, 2, 3, d=15, e=4)
assert result6 == 45 # 1+2+3+15+4+20
# But 'a' and 'b' must be positional
complex_error = False
try:
complex_signature(a=1, b=2, c=3, e=4) # type: ignore [call-arg]
except TypeError:
complex_error = True
assert complex_error is True
# And 'e' must be keyword (even though 'f' has a default)
complex_error2 = False
try:
complex_signature(1, 2, 3, 10, 4) # type: ignore [misc]
except TypeError:
complex_error2 = True
assert complex_error2 is True
# Practical use case: Positional-only is great for functions where
# parameter names are not meaningful or may change
def distance(x1, y1, x2, y2, /):
"""Calculate distance between two points.
The parameter names here are somewhat arbitrary (could be p1_x, etc.)
so we make them positional-only to give us flexibility to rename them
without breaking existing code.
"""
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
assert abs(distance(0, 0, 3, 4) - 5.0) < 0.01
# Practical use case: Keyword-only is great for boolean flags or
# optional parameters where the intent should be clear at call site
def create_user(username, *, admin=False, active=True, send_email=False):
"""Create a user with clear intent for optional parameters.
Making admin, active, and send_email keyword-only ensures that
callers must specify exactly what they're setting, improving
readability and preventing accidental mistakes.
"""
return {"username": username, "admin": admin, "active": active, "send_email": send_email}
# Clear intent at call site
user = create_user("john_doe", admin=True, send_email=True)
assert user["admin"] is True
assert user["active"] is True # Used default
assert user["send_email"] is True
if __name__ == "__main__":
main()