jeudi 26 mars 2020

How to add metadata to an instance attribute in python?

I'm trying to randomly fill attributes of some give object with data for testing purposes.

My data objects would look like this:

class SomeObject(BaseClass):
    def __init__(self):
        self.name = ""
        self.age = 0

class SomeOtherObject(BaseClass):
    def __init__(self):
        self.date = None
        self.description = ""

where BaseClass implements some minor behaviour and the deriving class just initializes its own attributes.

I would like to have a class that, given a data object, fills all marked attributes with some random value, but the value needs to fit into the context of the attribute (name = Jon Doe, age = 30). Because the data has to be valid and I need to add new classes to this in the future, i need my data generating object to know which type of value it needs to generate for each specific attribute.

I Java, for example, I could add metadata to an attribute like this:

@Name
private String name;

Is there a way to implement this in python so that i dont need to wrap the attributes in my data objects into custom classes like this:

...
    self.name = Name()
...

I would like to do something like this:

class SomeObject(BaseClass):
    def __init__(self):
        @name
        self.name = ""
        @age
        self.age = 0

def some_method():
    generator = DataGenerator()
    object = SomeObject()
    generator.fill_object(object)




Aucun commentaire:

Enregistrer un commentaire