views:

111

answers:

1

im looking into mongoengine, and i wanted to make a class an "EmbeddedDocument" dynamically, so i do this

def custom(cls):
    cls = type( cls.__name__, (EmbeddedDocument,), cls.__dict__.copy() )
    cls.a = FloatField(required=True)
    cls.b = FloatField(required=True)
    return cls

A = custom( A )

and tried it on some classes, but its not doing some of the base class's init or sumthing

in BaseDocument

def __init__(self, **values):
    self._data = {}
    # Assign initial values to instance
    for attr_name, attr_value in self._fields.items():
        if attr_name in values:
            setattr(self, attr_name, values.pop(attr_name))
        else:
            # Use default value if present
            value = getattr(self, attr_name, None)
            setattr(self, attr_name, value)

but this never gets used, thus never setting ._data, and giving me errors. how do i do this?

update:

im playing with it more, and it seems to have an issue with classes with init methods. maybe i need to make it explicit?

+1  A: 

The class you are creating isn't a subclass of cls. You can mix-in EmbeddedDocument, but you still need to be subclassing the original to get the parent's methods (like __init__).

cls = type(cls.__name__, (cls, EmbeddedDocument), {'a': FloatField(required=True), 'b': FloatField(required=True)})

EDIT: you can put the 'a' and 'b' attributes right in the attribute dict passed to type()

teepark