class factory question

Tim jtim.arnold at gmail.com
Wed Jun 26 10:08:54 EDT 2013


On Wednesday, June 26, 2013 9:39:12 AM UTC-4, Peter Otten wrote:
> Tim 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?
> 
> What is your objection against that approach?
> By the way, I don't think you need
> >         tmp.__name__ = name


I am not completely understanding the type function I guess. Here is an example from the interpreter:

In [1]: class MyClass(object):
   ...:     pass
   ...:
In [2]: type('Vspace', (MyClass,), {})
Out[2]: __main__.Vspace
In [3]: x = Vspace()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Python27\Scripts\<ipython-input-3-a82f21420bf3> in <module>()
----> 1 x = Vspace()

NameError: name 'Vspace' is not defined

In [4]: Vspace = type('Vspace', (MyClass,), {})
In [5]: x = Vspace()
In [6]: type(x)
Out[6]: __main__.Vspace

I don't understand how to make `Vspace` usable for creating instances later (line 3) when I just call `type`; that is why I thought adding the `__name__` attribute would work. Hmm, now I know that doesn't work either:

In [8]: del Vspace
In [9]: m = type('Vspace', (MyClass,), {})
In [10]: m.__name__ = 'Vspace'
In [11]: x = Vspace()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
C:\Python27\Scripts\<ipython-input-11-a82f21420bf3> in <module>()
----> 1 x = Vspace()

NameError: name 'Vspace' is not defined
In [11]: m
Out[12]: __main__.Vspace

Maybe this is too much trouble just to save a few lines (~50) of code.

thanks,
--Tim




More information about the Python-list mailing list