Context
I have a script, which generates objects of the same class (this class is called State
, for reference). Each object holds some value
and the goal of the objects is to store and move values around. The other attributes of the objects are determined by a nested dictionary, such that the dictionary:
dictionary = {
"foo":[1,2],
"bar":{
"baz":[3],
"qux":[4]
}
}
would produce 4 objects with the following attributes
self.foo = 1, self.bar.baz = 3, self.value = 0
self.foo = 1, self.bar.qux = 4, self.value = 0
self.foo = 2, self.bar.baz = 3, self.value = 0
self.foo = 2, self.bar.qux = 4, self.value = 0
(more information on this process here: Combination of nested dictionaries with arbitrary lengths in python)
Problem
I need to find some way of finding all the objects that have a certain attribute, or set of attributes. For example, all the objects with the attribute self.bar.baz
may need to take on a certain value
, and self.bar.qux
need to take on some other value
.
One potential solution
One solution, is to create a separate object (from the Environment
class, for reference), which is responsible for creating a list of all instantiated objects.
The simplest solution, is append all the objects to a list, and then loop through that list, checking which objects have a set of attributes. However, this gets inefficient very quickly, especially considering the set of objects is typically much more complex than the example above.
A slightly more advanced solution, is for the Environment
object to have all possible attributes e.g.
self.foo
self.bar.baz
self.bar.qux
And the values of these attributes are lists, containing all objects with these attributes. This way, there is no need to filter through the list objects, and objects with a set of attributes can be filtered by returning the set of objects in two or more lists.
However, I'm not sure:
- What the code for this would actually look like?
- If there is a more efficient solution?
Additional constraints
Importantly, the attributes that State
objects have, are not fixed. That is, it may not be foo
and bar
(or baz
or qux
), but may be completely different keys. Therefore, I cannot hardcode the attributes to search for.