class factory question

Peter Otten __peter__ at web.de
Wed Jun 26 10:46:55 EDT 2013


Tim wrote:

> 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

No, you are not understanding how Python namespaces work ;) 
To get a Vspace in the global namespace you'd have to bind that name

Vspace = type(...)

which defeats your plan of mass creation of such names. The clean way to 
cope with the situation is to use a dict:

classnames = ["Vspace", ...]
classes = {name: type(name, ...) for name in classnames}

Then you can access the Vspace class with

classes["Vspace"]

If that is inconvenient for your usecase you can alternatively update the 
global (module) namespace:

globals().update((name, type(name, ...) for name in classnames)

For example:

>>> class A(object): pass
... 
>>> globals().update((n, type(n, (A,), {})) for n in ["Beta", "Gamma"])
>>> Beta
<class '__main__.Beta'>
>>> issubclass(Beta, A)
True





More information about the Python-list mailing list