acgtyrant
acgtyrant

Reputation: 1829

Is there any a pure clean class which support getattr and setattr in Python?

I use a Context class:

class Context(object):
    ...

So I can use this class to define a object which support getattr and setattr. I want to use the object to communicate between some threads.

However I think it is stupid to let the user define such a class. So I want to find out is there any a primitive type or a class from the standard library which support getattr and setattr.

I have tried the object class, but the object of it can not set attribute:

a = object()
a.b = 1

class C(object):
    ...

c = C()
c.d = 1

I can set c.d = 1, but a.b complains 'object' object has no attribute 'b'

Upvotes: 1

Views: 453

Answers (1)

Kevin
Kevin

Reputation: 76244

Try types.SimpleNamespace:

A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr.

Unlike object, with SimpleNamespace you can add and remove attributes.

Upvotes: 5

Related Questions