Metaclasses for class mangling after definition.

Daniele Varrazzo dvarrazzo at virgilio.it
Mon Jul 19 17:09:52 CEST 2004


Hi everybody,

I am writing a base class for <<entity>> stereotype classes, to implement
controlled access to the state and expose some of the access logic (in order
to dinamically build javascript code for client-side checks, for example).

Currently the idiom needed to subclass it is something like:

class Group(Entity):
    _interface = Entity._extend_interface(
        id = Direct(state_field='grp_id',
            filters=(ReadOnlyFilter(),),
            doc="The univocal database id for the group."),

        name = Direct(
            filters=(
                StringFilter(),
                MaxLenFilter(max_len=40,
                    message="The group name can be at most "
                            "%(max_len)s characters long."),),
            doc = "A descriptive name for the group."),
    )

    _state = Entity._extend_state(
        grp_id=None,
        name=None,
    )

    # ... class definition ...

make_entity(Group)

The make_entity() call compiles some dinamically generated code to produce
the properties required to access the class. But adding such line after each
entity definition bothers me.

I don't know much about metaclasses: could they help me to automatically
perform such mangling on the classes "at compile time" (or at least once in
the class lifetime)? Hints about that?

What make_entity does is here down. Basically each Field instance (Direct is
a Field subclass) in the _interface dictionary (a class member) create a
property object on the same class that will perform the access for the class
instances.

def make_entity(entity):
    """Complete the Entity subclass building its attributes."""
    for (field_name, field) in entity._interface.iteritems():
        if not hasattr(entity, field_name):
            field.field_name = field_name
            field.create_accessors(entity)

Thank you in advance

Daniele




More information about the Python-list mailing list