Is a Metaclass the appropriate way to solve this problem?

  • Thread starter Matthew Lefavor
  • Start date

M

Matthew Lefavor

All:

Like most people, I find the whole metaclass topic pretty obscure, and I
have avoided trying to use one for a while. I am also aware of Tim Peter's
famous advice that if you have to ask whether you need a metaclass, then
you almost certainly don't. But in this case I know I am solving a problem
similar to problems that other high-profile Python modules (e.g., Django's
Model class) have solved using metaclasses.

My company is using a database whose interface is defined in a series of
JSON objects. I am writing some interface code to the database and I am
trying to hide the detail of the JSON implementation from the user.

I want the user to be able to define a class representing a database entry
for any arbitrary table, whose attributes represent database entities, like
fields or tags, with syntax something like the following:

class DataSet:
data_set_id = DatabaseKeyField(int)
description = DatabaseField(str)
creation_date = DatabaseField(datetime.date)
creation_timestamp = DatabaseField(datetime.datetime)

def __init__(self, ds_id, description, timestamp):
self.data_set_id = ds_id
self.description = description
self.creation_timestamp = timestamp
self.creation_date = timestamp.date

I know that to create the DatabaseField objects I should be using a
descriptor. But I also want the DataSet to automatically gain methods that
will convert it into the expected JSON syntax (e.g., a __specifier__ method
that will create a JSON object with only "key" fields, and an __object__
method that will create a JSON object with all the fields and other bells
and whistles.)

My ultimate question then: How do I go about adding those kinds of methods
(which iterate through all the attributes which are Database* descriptors)?
I know that I could eschew metaclasses altogether and use a common
super-class, but this doesn't feel like the right situation for inheritance
to me. Is a metaclass going to be the cleanest and easiest-to-understand
way to solve this problem?

Thank you, all!

-MCL
 
Ad

Advertisements


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

Top