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

Function validate_attributes

Solutions/8_1/structure.py:61–88  ·  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

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

Callers 1

__init_subclass__Method · 0.70

Calls 3

validatedFunction · 0.90
appendMethod · 0.80
create_initMethod · 0.45

Tested by

no test coverage detected