our project collects a bunch of information on an object from a bunch of different sources and for auditing and for resolving conflicts between our data sources we need to keep a bunch of meta data about each attribute
age = 21
age_metadata = {
'source' : 'office gossip',
'relability' : 0
{
the problem is the classes start to look like this.
class Person
def __init__(self, id, ):
self.id = id
self.id_meta = None
self.age = None
self.age_meta = None
self.name = None
which looks ugly and doubles the number of attributes everything has so what I want is to nest the metadata under each attribute. so if I need it I can call bob.age.meta instead of bob.age_meta and I want to do this while leaving the attributes more or less unchanged. so I want something that always me to use it like:
def main():
bob = Person(1)
bob.age.meta = 'random metadata'
bob.age = 30
assert bob.age.meta == 'random metadata'
Now I think this should be possible using a combo of a descriptor class to intercept the assignment + some monkey patching/ metaclassing magic to preserve the metadata.. but I'm new to all these features and am getting very lost. here is my current sketch.long way from working code:
class AttributeWithMeta(object):
"""interceot attribute fucntions"""
def __get__(self, instance, owner):
return self._value
def __set__(self, instance, value):
"""take attribute and somehow replace it with monkey patched version"""
self._value = magic(value,meta)
@staticmethod
def magic(value, meta):
"""adds meta attribute to objects regardless of type"""
return value_with_meta
class Person(object):
age = AttributeWithMeta()
def __init__(self, id):
self.id = id
Am I going in the right direction? is there some other way to do this that I'm missing? Am I trying to do the impossible here?
P.S worst case age.get_meta() would be acceptable if attributes are problematic.