Skip to content

Instantly share code, notes, and snippets.

@subhashb
Last active August 27, 2020 21:22

Revisions

  1. subhashb revised this gist Aug 27, 2020. 1 changed file with 9 additions and 6 deletions.
    15 changes: 9 additions & 6 deletions dynamic-properties.py
    Original 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")

    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}")
    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
  2. subhashb created this gist Aug 27, 2020.
    45 changes: 45 additions & 0 deletions dynamic-properties.py
    Original 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}")