Use partialmethod for a fixed validation mode
Use partialmethod for a fixed validation mode
functools.partialmethod is useful when several instance methods differ only by a fixed argument. UsernamePolicy.validate takes its mode before its value, and marks both as positional-only. validate_strict binds "strict"; validate_display binds "display". When either descriptor is read from policy, Python binds self and returns a callable with the selected mode already supplied.
The strict branch calls str.isidentifier(), so "blue sky" is rejected because its space cannot occur in an identifier. The display branch instead calls strip() only to test for an all-whitespace value and returns the original value, "blue sky", unchanged. Catching the expected ValueError lets the example print both outcomes while its assertions make the two policies explicit.
The positional-only arrangement matters for the word “fixed”: calling policy.validate_strict("blue sky", "display") supplies too many positional arguments instead of replacing the stored mode. That ordering may be less natural for a public general-purpose validate API, so a normal forwarding method can be clearer when callers need named parameters. This is input validation, not authorization: callers that can access validate directly can still request either recognized mode.
from functools import partialmethod
class UsernamePolicy:
def validate(self, mode, value, /):
if mode == "strict":
if not value.isidentifier():
raise ValueError("spaces are not allowed")
elif mode == "display":
if not value.strip():
raise ValueError("a display name is required")
else:
raise ValueError(f"unknown mode: {mode}")
return value
validate_strict = partialmethod(validate, "strict")
validate_display = partialmethod(validate, "display")
policy = UsernamePolicy()
try:
policy.validate_strict("blue sky")
except ValueError as error:
assert str(error) == "spaces are not allowed"
print(f"strict: {error}")
shown = policy.validate_display("blue sky")
assert shown == "blue sky"
print(f"display: {shown}")
Expected stdout:
strict: spaces are not allowed
display: blue sky
By Batu. AI assistance was used to prepare this article.
Comments
Post a Comment