Metaclasses for class mangling after definition.

D

Daniele Varrazzo

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top