How can I recursively create class properties in Python?

Viewed 320

Python supports creating properties "on the fly", like so.

class MyClass:
    def __init__(self):
        pass

x = MyClass
x.new = 5
print(x.new)  # prints 5

But this is a tad ugly. I have to have some instruction within the class, either a function or a class property definition.

But the main hindrance is this...

x.first.second = 1  # this will raise

And it raises because first doesn't exist, obviously. I would have to do something like this instead.

x.first = MyClass()
x.first.second = 1
print(x.first.second)

I want to recursively create properties as they're needed. Is this possible?

1 Answers

Use __getattr__ to create a new attribute namespace and return. __eq__ is implemented. The behavior is similar to types.SimpleNamespace.

class Namespace:
    def __init__(self):
        pass

    def __getattr__(self, item):
        ret = Namespace()
        setattr(self, item, ret)
        return ret

    def __eq__(self, other):
        return isinstance(other, Namespace) and vars(self) == vars(other)


ns = Namespace()
ns.first.second = 1

print(ns.first.second)  # 1

However, this has side effect

print(ns.unknown)   # <__main__.Namespace object at 0x0000025FC1E5B400>
Related