Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #52146
| From | Matthew Lefavor <mclefavor@gmail.com> |
|---|---|
| Date | 2013-08-07 15:38 -0400 |
| Subject | Is a Metaclass the appropriate way to solve this problem? |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.326.1375904372.1251.python-list@python.org> (permalink) |
[Multipart message — attachments visible in raw view] - view raw
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
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Is a Metaclass the appropriate way to solve this problem? Matthew Lefavor <mclefavor@gmail.com> - 2013-08-07 15:38 -0400
csiph-web