MCPcopy Create free account
hub / github.com/dabeaz-course/python-mastery / validate_attributes

Function validate_attributes

Solutions/9_2/structly/structure.py:60–87  ·  view source on GitHub ↗

Class decorator that scans a class definition for Validators and builds a _fields variable that captures their definition order.

(cls)

Source from the content-addressed store, hash-verified

58 validate_attributes(cls)
59
60def validate_attributes(cls):
61 '''
62 Class decorator that scans a class definition for Validators
63 and builds a _fields variable that captures their definition order.
64 '''
65 validators = []
66 for name, val in vars(cls).items():
67 if isinstance(val, Validator):
68 validators.append(val)
69
70 # Apply validated decorator to any callable with annotations
71 elif callable(val) and val.__annotations__:
72 setattr(cls, name, validated(val))
73
74 # Collect all of the field names
75 cls._fields = tuple([v.name for v in validators])
76
77 # Collect type conversions. The lambda x:x is an identity
78 # function that's used in case no expected_type is found.
79 cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
80 for v in validators ])
81
82 # Create the __init__ method
83 if cls._fields:
84 cls.create_init()
85
86
87 return cls
88
89def typed_structure(clsname, **validators):
90 cls = type(clsname, (Structure,), validators)

Callers 1

__init_subclass__Method · 0.70

Calls 3

appendMethod · 0.80
validatedFunction · 0.70
create_initMethod · 0.45

Tested by

no test coverage detected