A generic question: idiom for a paramterized base class?

Blair Hall b.hall at irl.cri.nz
Tue Jul 30 17:25:02 EDT 2002


I would like to know if there is a Python idom to elegantly solve the
following problem. I have a base class that needs to instantiate generic
classes that
are actually derived from it. In C++ this can be achieved by passsing
the derived class as a template parameter to the base class
(something like:
    class Derived : public GenericBase<Derived> { ... };
)

In terms of Python, this is my problem.

The following module works fine:

############ example.py ###########
class GenericBase(object):
    def __iadd__(self,other):
        return TAdd(self,other) # Problem!!
    def __add__(self,r):
        return GenericBase.__iadd__(self,r)
    def __radd__(self,l):
        return GenericBase.__iadd__(l,self)

# One type of TAdd:
class TAdd(object,GenericBase):
    def __init__(self,l,r):
        print "TAdd instance"

class TNode(object,GenericBase):
    def __init__(self):
        print "TNode instance"
############################

You can use to to do something like:

>>> import example
>>> x = example.TNode()
TNode instance
>>> y = example.TNode()
TNode instance
>>> t = x + y
TAdd instance

However, the first class, GenericBase, is actually one that I need to
reuse in a number
of different situations, each with different TAdd definitions!

What can I do? If I put the GenericBase in a module of its own (base.py)
and import it into
example.py then the following results:

>>> x = example.TNode()
TNode instance
>>> y = example.TNode()
TNode instance
>>> t = x + y
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "base.py", line 5, in __add__
    return GenericBase.__iadd__(self,r)
  File "base.py", line 3, in __iadd__
    return TAdd(self,other) # Problem!!
NameError: global name 'TAdd' is not defined

The answer would appear to be to modify 'import' so that the local
namespace
for modules base and example are the same. Is this reasonable? Can it be
done?






More information about the Python-list mailing list