|
| 1 | +import inspect |
| 2 | +from typing import Any, Dict, Type |
| 3 | + |
| 4 | + |
| 5 | +class MISSING: |
| 6 | + __slots__ = () |
| 7 | + |
| 8 | + |
| 9 | +class Umm: |
| 10 | + _attributes = {} |
| 11 | + |
| 12 | + def __init_subclass__(cls, **kwargs): |
| 13 | + super().__init_subclass__(**kwargs) |
| 14 | + |
| 15 | + # TODO(reweeden): Make this work with multiple inheritance? |
| 16 | + parent_cls = super(cls, cls) |
| 17 | + attributes = {**parent_cls._attributes} |
| 18 | + |
| 19 | + for name, typ in get_annotations(cls).items(): |
| 20 | + # TODO(reweeden): What if we're overwriting an attribute from the |
| 21 | + # parent and the types don't match? |
| 22 | + attributes[name] = (typ, getattr(cls, name, MISSING)) |
| 23 | + |
| 24 | + # Update attributes with unannotated default values |
| 25 | + for name, value in inspect.getmembers(cls): |
| 26 | + if name.startswith("_") or inspect.isfunction(value): |
| 27 | + continue |
| 28 | + |
| 29 | + if name not in attributes: |
| 30 | + attributes[name] = (Any, value) |
| 31 | + else: |
| 32 | + typ, _ = attributes[name] |
| 33 | + attributes[name] = (typ, value) |
| 34 | + |
| 35 | + cls._attributes = attributes |
| 36 | + |
| 37 | + def __init__(self, metadata: Dict[str, Any]): |
| 38 | + for name, (typ, default) in self._attributes.items(): |
| 39 | + if inspect.isclass(typ) and issubclass(typ, Umm): |
| 40 | + if type(self) is typ: |
| 41 | + # TODO(reweeden): Error type? |
| 42 | + raise RuntimeError( |
| 43 | + f"Self-reference detected for attribute '{name}'", |
| 44 | + ) |
| 45 | + |
| 46 | + setattr(self, name, typ(metadata)) |
| 47 | + else: |
| 48 | + value = default |
| 49 | + if value is MISSING: |
| 50 | + # TODO(reweeden): Ability to set handler function manually? |
| 51 | + # For example: |
| 52 | + # class Foo(Umm): |
| 53 | + # Attribute: str = Attr() |
| 54 | + # |
| 55 | + # @Attribute.getter |
| 56 | + # def get_attribute(self, metadata): |
| 57 | + # ... |
| 58 | + handler_name = f"get_{name}" |
| 59 | + handler = getattr(self, handler_name, None) |
| 60 | + if handler: |
| 61 | + value = handler(metadata) |
| 62 | + |
| 63 | + if value is MISSING: |
| 64 | + # TODO(reweeden): Error type? |
| 65 | + raise RuntimeError( |
| 66 | + f"Missing value for '{name}'. " |
| 67 | + f"Try implementing a 'get_{name}' method", |
| 68 | + ) |
| 69 | + setattr(self, name, value) |
| 70 | + |
| 71 | + def to_dict(self) -> Dict[str, Any]: |
| 72 | + return _to_dict(self) |
| 73 | + |
| 74 | + |
| 75 | +def get_annotations(cls) -> Dict[str, Type[Any]]: |
| 76 | + if hasattr(inspect, "get_annotations"): |
| 77 | + return inspect.get_annotations(cls, eval_str=True) |
| 78 | + |
| 79 | + # TODO(reweeden): String evaluation |
| 80 | + return dict(cls.__annotations__) |
| 81 | + |
| 82 | + |
| 83 | +def _to_dict(obj: Any) -> Any: |
| 84 | + if isinstance(obj, Umm): |
| 85 | + return { |
| 86 | + name: _to_dict( |
| 87 | + getattr(obj, name), |
| 88 | + ) |
| 89 | + for name in obj._attributes |
| 90 | + } |
| 91 | + |
| 92 | + return obj |
0 commit comments