|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from dataclasses import dataclass, Field |
| 4 | +from abc import ABC, abstractmethod |
| 5 | +from dataclasses import fields as dc_fields |
| 6 | + |
| 7 | +from typing_extensions import Dict, Iterable, List, Type, Optional, TYPE_CHECKING |
| 8 | + |
| 9 | + |
| 10 | +@dataclass |
| 11 | +class DiscoveredAttribute: |
| 12 | + """Attribute discovered on a class.""" |
| 13 | + |
| 14 | + field: Field |
| 15 | + """The dataclass field object that is wrapped.""" |
| 16 | + public_name: Optional[str] = None |
| 17 | + """The public name of the field.""" |
| 18 | + |
| 19 | + def __post_init__(self): |
| 20 | + if self.public_name is None: |
| 21 | + self.public_name = self.field.name |
| 22 | + |
| 23 | + def __hash__(self) -> int: |
| 24 | + return hash(self.field) |
| 25 | + |
| 26 | + |
| 27 | +@dataclass |
| 28 | +class AttributeIntrospector(ABC): |
| 29 | + """Strategy that discovers class attributes for diagramming. |
| 30 | +
|
| 31 | + Implementations return the set of dataclass-backed attributes that |
| 32 | + should appear on a class diagram, including their public names. |
| 33 | + """ |
| 34 | + |
| 35 | + @abstractmethod |
| 36 | + def discover(self, owner_cls: Type) -> List[DiscoveredAttribute]: |
| 37 | + """Return discovered attributes for `owner_cls`. |
| 38 | +
|
| 39 | + The `field` of each result must be a dataclass `Field` belonging to |
| 40 | + `owner_cls`, while `public_name` is how it should be addressed and displayed. |
| 41 | + """ |
| 42 | + raise NotImplementedError |
| 43 | + |
| 44 | + |
| 45 | +@dataclass |
| 46 | +class DataclassOnlyIntrospector(AttributeIntrospector): |
| 47 | + """Discover only public dataclass fields (no leading underscore).""" |
| 48 | + |
| 49 | + def discover(self, owner_cls: Type) -> List[DiscoveredAttribute]: |
| 50 | + result: List[DiscoveredAttribute] = [] |
| 51 | + for f in dc_fields(owner_cls): |
| 52 | + if not f.name.startswith("_"): |
| 53 | + result.append(DiscoveredAttribute(public_name=f.name, field=f)) |
| 54 | + return result |
0 commit comments