class factory question

Fábio Santos fabiosantosart at gmail.com
Wed Jun 26 19:35:23 EDT 2013


On 26 Jun 2013 14:14, "Tim" <jtim.arnold at gmail.com> wrote:
>
> I am extending a parser and need to create many classes that are all
subclassed from the same object (defined in an external library).  When my
module is loaded I need all the classes to be created with a particular
name but the behavior is all the same. Currently I have a bunch of lines
like this:
>
>     class Vspace(Base.Command): pass
>     class Boldpath(Base.Command): pass
>
> There are a bunch of lines like that.
> Is there a better way? Something like
>
>     newclasses = ['Vspace', 'Boldpath', ... ]
>     for name in newclasses:
>         tmp = type(name, (Base.Command,) {})
>         tmp.__name__ = name
>
> Is there a more pythonic way?
> thanks,
> --Tim
>

I would say The Most Pythonic Way is to use the class declarations as you
are doing now. Explicit is better than implicit, or so the zen says.

It will be better for tools as well. I'd like to see code completion work
on dynamically created classes like that (unless you use __all__ to list
them.).

And, are you really looking for classes here? If you just want to create
different names with different identities, you could consider using plain
old strings or object() to do that.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130627/7afb8874/attachment.html>


More information about the Python-list mailing list