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

Function validate_attributes

Solutions/9_4/structly/structure.py:62–89  ·  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

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