Is a Metaclass the appropriate way to solve this problem?

Ian Kelly ian.g.kelly at gmail.com
Wed Aug 7 16:28:14 EDT 2013


On Wed, Aug 7, 2013 at 1:38 PM, Matthew Lefavor <mclefavor at gmail.com> wrote:
> 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?

You could use a class decorator.  It's not as flexible as a metaclass,
but from the sound of it you don't need that kind of flexibility; you
just need to modify the class a bit after it's already been created.



More information about the Python-list mailing list