Selecting a different superclass

Jason tenax.raccoon at
Thu Dec 18 16:20:08 CET 2008

On Dec 18, 4:36 am, "psaff... at"
<psaff... at> wrote:
> On 17 Dec, 20:33, "Chris Rebert" <c... at> wrote:
> > superclass = TraceablePointSet if tracing else PointSet
> Perfect - many thanks. Good to know I'm absolved from evil, also ;)
> Peter

Another way would be to have a factory function that builds the
appropriate instance:

class PointSet(object):
    def Create_Instance(*args, **keyargs):
        if TRACE_DATA:
            return TraceablePointSet(*args, **keyargs)
            return PointSet(*args, **keyargs)
    # Normal release class body goes here.

class TraceablePointSet(object):
    # Normal debug class body goes here

point_set = PointSet.Create_Instance()

This is the way you'd do things if you wanted a mix of your release
class instances and debug class instances.  Perhaps there's only a
certain set of initial arguments that need to be checked, or maybe the
TRACE_DATA global can change.  Inside the body you could also
explicitly check for a "trace" parameter, like so:

    if keyargs.get( 'trace_data', False ):
        # Create debug instance ....

That would allow you to create debug instances only when you want

A variation on Chris Rebert's option is also possible:

class _PointSet(object):
    # Normal body definition here

class _TraceablePointSet(object):
    # Traceable body definition here

    PointSet = _TraceablePointSet
    PointSet = _PointSet

Hope this helps.  Python's dynamic nature loves you!


More information about the Python-list mailing list