Python reflection

Suppose we have many objects in memory. Each of them has a separate identifier. How can I iterate memory to find a specific object, which is compared to some id? To grab it and use it through getattr?

+4
source share
4 answers

You must maintain a collection of these objects as they are created in the class attribute, and then provide a class method to retrieve them.

Something along the lines of:

class Thing(object): all = {} def __init__(self, id, also, etc): self.id = id self.all[id] = self @classmethod def by_id(cls, id): return cls.all[id] 
+10
source

You can query the garbage collector for all existing objects and iterate over this collection to find what you are looking for, but this is probably wrong if you have no special reason for this.

+2
source

You can make a “registry”, to which all new instances are subscribed, with matching identifiers-> objects:

 registry = {} class MyClass(object): def __init__(self, ...): id = ... registry[id] = self MyClass.__all__ = registry 

This is equivalent to another decision made (the other is more "python"). I improved this method in two ways: 1) you can create a custom container class for the registry that allows you to search not only with identifiers; 2) you can also create a metaclass that will automatically add the code, but it can get ugly if you also need metaclasses for something else.

edit: since another answer was acceptable, added ways to undo the design template

0
source

First, all of you, answering me, thank you very much for what I had in mind at the weekend:

 for ech in globals(): if str(type(globals()[ech])).find('instance') != -1: if ( globals()[ech].__dict__.has_key('onoma')): print "%s, %s, %s"%( ech, globals()[ech].__dict__, id(globals()[ech]) ) 

who did this work, although I don’t know if this good or bad approach is suitable (“onma” is the Greek word for the name). I read in Python docs about: _id2obj_dict = weakref.WeakValueDictionary () from weakref. And I shot too. Good approach and similar to Ned and Ninyagetsk, I think. But in this case, how can I be sure that the object is completely freed from memory?

0
source

All Articles