Last active
August 27, 2020 21:22
Revisions
-
subhashb revised this gist
Aug 27, 2020 . 1 changed file with 9 additions and 6 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -37,9 +37,12 @@ def setup_properties(cls): registry.register(ElementTypes.CAR, "car1") registry.register(ElementTypes.CAR, "car2") assert dict(registry._elements) == { "CAR": ["car1", "car2"], "PHONE": ["phone1", "phone2"], } assert hasattr(registry, "phone") assert hasattr(registry, "car") assert registry.car == ["car1", "car2"] assert registry.phone == ["phone1", "phone2"] # This fails -
subhashb created this gist
Aug 27, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,45 @@ from collections import defaultdict from enum import Enum class ElementTypes(Enum): PHONE = "PHONE" CAR = "CAR" class Registry: def __new__(cls, *args, **kwargs): cls.setup_properties() instance = super(Registry, cls).__new__(cls, *args, **kwargs) return instance def __init__(self): self._elements = defaultdict(list) def register(self, element_type, item): self._elements[element_type.value].append(item) def get(self, element_type): return self._elements[element_type.value] @classmethod def setup_properties(cls): for item in ElementTypes: prop_name = item.value prop = property(lambda self: self.get(item)) setattr(Registry, prop_name.lower(), prop) registry = Registry() registry.register(ElementTypes.PHONE, "phone1") registry.register(ElementTypes.PHONE, "phone2") registry.register(ElementTypes.CAR, "car1") registry.register(ElementTypes.CAR, "car2") print(f"Registry holds all elements: {registry._elements}") print(f"Registry has properties too: {dir(registry)}") # Should print phones and cars, but only prints cars print(f"Printing car: {registry.car}") print(f"Printing phones: {registry.phone}")