Closures in metaclasses

Falcolas garrickp at gmail.com
Thu Jan 21 21:38:09 CET 2010


On Jan 21, 12:10 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On Jan 21, 6:37 pm, Falcolas <garri... at gmail.com> wrote:
>
> > On Jan 21, 11:24 am, Arnaud Delobelle <arno... at googlemail.com> wrote:
>
> > It was the easiest way I found to add a lot of static methods to the
> > Tag class without writing each one out. __getattr__ was not working
> > for this application. This is for a very simple application, and I
> > didn't want to add a lot of complexity to it's use. I'm always open
> > for other options OTOH.
>
> This should work (untested):
>
> class Tag(object):
>     @staticmethod
>     def _generate_tag(tag_name, *args, **kwargs):
>         # Does the expected, following is just for the example's sake
>         return tag
>
> for tag in ALL_TAGS:
>     setattr(Tag, tag, staticmethod(factory(tag)))
>
> Or you could override __getattr__
>
> --
> Arnaud

I tried overriding __getattr__ and got an error at runtime (the
instance did not have xyz key, etc), and the Tag dict is not
modifiable (granted, I tried Tag.__dict__[tag] = spam, not setattr()).



More information about the Python-list mailing list