Skip to content

Commit 5156e87

Browse files
committed
Add Image.create() class method
Allowing str and list input types in addition to None and dict.
1 parent 1c4fd68 commit 5156e87

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

src/wireviz/DataClasses.py

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,21 @@ def __post_init__(self):
113113
if self.width:
114114
self.height = self.width / aspect_ratio(self.src)
115115

116+
@classmethod
117+
def create(cls, input: Union[None, dict, str, List[Union[dict, str]]]):
118+
"""Create class instance(s) from alternative YAML input types"""
119+
if input in (None, "", []):
120+
return None
121+
if isinstance(input, list):
122+
return [cls.create(entry) for entry in input]
123+
if isinstance(input, str):
124+
input = {"src": input}
125+
if isinstance(input, dict):
126+
return cls(**input)
127+
raise TypeError(
128+
f"Expected None, dict, str, or list as Image input, but got {type(input)}"
129+
)
130+
116131

117132
@dataclass
118133
class AdditionalComponent:
@@ -165,8 +180,7 @@ class Connector:
165180
additional_components: List[AdditionalComponent] = field(default_factory=list)
166181

167182
def __post_init__(self) -> None:
168-
if isinstance(self.image, dict):
169-
self.image = Image(**self.image)
183+
self.image = Image.create(self.image)
170184

171185
self.ports_left = False
172186
self.ports_right = False
@@ -274,8 +288,7 @@ class Cable:
274288
additional_components: List[AdditionalComponent] = field(default_factory=list)
275289

276290
def __post_init__(self) -> None:
277-
if isinstance(self.image, dict):
278-
self.image = Image(**self.image)
291+
self.image = Image.create(self.image)
279292

280293
if isinstance(self.gauge, str): # gauge and unit specified
281294
try:

0 commit comments

Comments
 (0)