Generic Python

Carl Banks imbosol at vt.edu
Mon Jun 24 13:44:20 EDT 2002


Uwe Mayer wrote:
> Is it somehow possible to have the "base2" class return a class instead
> of an instance?
> Is there another way to solve this problem?


In Python 2.1 and above, you can take advantage of nested scopes to
generate different classes from a template.  The idea is to put the
template class definition inside a function, and have the class refer
to the function's arguments.

def template_factory(baseclass,text):
    class template(baseclass):
        def output(self):
            print text
    return template

Remember to use from __future__ import nested_scopes if you're on
Python 2.1.  If you're using 2.0 or lower, you can still fake the
nested scopes thing with a default argument:

def template_factory(baseclass,text):
    class template(baseclass):
        def output(self,text=text):
            print text
    return template


Here's an example session:

Python 2.1.3 (#1, Apr 20 2002, 10:14:34)
[GCC 2.95.4 20011002 (Debian prerelease)] on linux2
Type "copyright", "credits" or "license" for more information.
>>> from __future__ import nested_scopes
>>> def template_factory(text):
...     class template:
...         def output(self):
...             print text
...     return template
...
>>> a = template_factory("hello, world")
>>> b = a()
>>> b.output()
hello, world
>>> c = template_factory("hello, my name is inigo montoya")
>>> d = c()
>>> d.output()
hello, my name is inigo montoya


-- 
CARL BANKS                                http://www.aerojockey.com
"Nullum mihi placet tamquam provocatio magna.  Hoc ex eis non est."



More information about the Python-list mailing list