Python global class object cache

A small question regarding application architecture:

I have a python script working as a daemon.

Inside, I have many objects, all inherited from one class (let it be called its "essence")

I also have one main object, let it be "topsys"

Entities are identified by a pair (id, type (= class, roughly)), and they are connected in many evil ways. They are also created and deleted all the time, and they need to access other objects.

So, I need a view of the repository, basically a dictionary of dictionaries (one for each type) containing all entities.

And the question is which is better: attach this dictionary to "topsys" as an object or an object of a class, as a property of a class? I would choose the second one (so entities should not know about the existence of "topsys"), but I don’t feel good about using properties directly in classes. Or maybe there is another way?

+4
source share
2 answers

There are not enough details to be sure that it’s best, but in general I would save the actual registry of objects as a module level variable (global) in the upper class and get a method in the base class for accessing it.

_entities = [] class entity(object): @staticmethod def get_entity_registry(): return _entities 

Alternatively, completely hide _entites and output some methods, for example. get_object_by_id , register_object , so you can more easily change the _entities repository later.

By the way, a hint in case you are not there: you probably want to study weakrefs when creating object registries like this.

+6
source

No problem using class properties. Classes are also objects.

In your case, if this little information was available, I would also like to use the class property, because I don’t have ist great dependencies and sometimes I’ll worry less later.

0
source

All Articles