Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Reflection

suppose we have many objects in memory. Each one has a distinct id. How can I iterate the memory to find a specific object that is compared to some id ? In order to grab it and use it through getattr ?

like image 487
hephestos Avatar asked Dec 16 '22 15:12

hephestos


2 Answers

You should maintain a collection of these objects as they are created in a class attribute, then provide a class method for retrieving 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]
like image 165
Ned Batchelder Avatar answered Dec 28 '22 08:12

Ned Batchelder


You could ask the garbage collector for all existing objects and iterate through that collection to find what you are looking for, but thats probably the wrong thing to do, unless you have very special reasons to do it.

like image 29
schlenk Avatar answered Dec 28 '22 08:12

schlenk