<div dir="ltr">All:<div><br></div><div>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.</div>

<div><br></div><div>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.</div>

<div><br></div><div>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:</div>

<div><br></div><div>class DataSet:</div><div>    data_set_id = DatabaseKeyField(int)</div><div>    description = DatabaseField(str)</div><div>    creation_date = DatabaseField(datetime.date)</div><div>    creation_timestamp = DatabaseField(datetime.datetime)</div>

<div>    </div><div>    def __init__(self, ds_id, description, timestamp):</div><div>        self.data_set_id = ds_id</div><div>        self.description = description</div><div>        self.creation_timestamp = timestamp</div>

<div>        self.creation_date = timestamp.date</div><div><br></div><div>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.)</div>

<div><br></div><div>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?</div>

<div><br></div><div>Thank you, all!</div><div><br></div><div>-MCL</div></div>