Skip to content

Commit a815284

Browse files
committed
fix: Emit all types and not scalars
1 parent 4aa45ea commit a815284

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

cosmo/types.py

+18-5
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
from .common import without_keys
88
from typing import Self, Iterator, TypeVar, NoReturn
99

10+
def findSubclasses(cls):
11+
return set(cls.__subclasses__()).union(
12+
[s for c in cls.__subclasses__() for s in findSubclasses(c)])
1013

1114
T = TypeVar('T', bound="AbstractNetboxType")
1215
class AbstractNetboxType(abc.ABC, Iterable):
@@ -16,7 +19,7 @@ def __init__(self, *args, **kwargs):
1619
self._store.update(**kwargs)
1720
for k, v in without_keys(self._store, "__parent").items():
1821
self[k] = self.convert(v)
19-
22+
2023
def __getitem__(self, key):
2124
return self._store[key]
2225

@@ -30,15 +33,20 @@ def __len__(self):
3033
return len(self._store)
3134

3235
def __iter__(self) -> Iterator[Self|str|int|bool|None]:
36+
# I bet, we cannot to this before AbstractClass and all of it's inherited childs are constructed, so we need to do this in here.
37+
iterableSubclasses = findSubclasses(AbstractNetboxType)
38+
3339
yield self
3440
for k, v in without_keys(self._store, ["__parent", "__typename"]).items():
3541
if isinstance(v, dict):
3642
yield from iter(v)
37-
if isinstance(v, list):
43+
elif isinstance(v, list):
3844
for e in v:
3945
yield from e
40-
else:
41-
yield v
46+
elif next((cs for cs in iterableSubclasses if isinstance(v, cs)), None):
47+
yield from iter(v)
48+
49+
# Note: We can omit the emit of scalars, because we do not use them.
4250

4351
def __hash__(self):
4452
non_recursive_clone = without_keys(self._store, "__parent")
@@ -74,7 +82,12 @@ def get(self, *args, **kwargs):
7482
def convert(self, item):
7583
if isinstance(item, dict):
7684
if "__typename" in item.keys():
77-
c = {k: v for k, v in [c.register() for c in AbstractNetboxType.__subclasses__()]}[item["__typename"]]
85+
86+
# Taken from https://stackoverflow.com/questions/3862310/how-to-find-all-the-subclasses-of-a-class-given-its-name
87+
availableSubclasses = findSubclasses(AbstractNetboxType)
88+
availableClassesForTypeNames = {k: v for k, v in [c.register() for c in availableSubclasses]}
89+
90+
c = availableClassesForTypeNames[item["__typename"]]
7891
o = c()
7992
o._store.update(
8093
{k: o.convert(v) for k, v in without_keys(item, "__parent").items()} | {"__parent": self}

0 commit comments

Comments
 (0)