Questions re subclassing at "load time"

John J. Lee jjl at pobox.com
Sun Jun 22 15:29:51 EDT 2003


"Edward K. Ream" <edreamleo at charter.net> writes:

> There appears to be an easy way for plugins to override classes in
> an app.
[...rebinding module-global names to new plugin classes...]

IIUC, you've discovered a variation of a nice Python pattern, in which
a class is not directly instantiated, but referred to through an
attribute of another class:

class Helper:
    ...

class Foo:
    helper_class = Helper
    def blah(self):
        self._helper = self.helper_class()
    ...

def use_foo(f):
    ...
    f.blah()
    ...


class NewHelper:
    ...

class NewFoo:
    helper_class = NewHelper


spam = Foo()
use_foo(spam)

eggs = NewFoo()
use_foo(eggs)

ham = Foo()
ham.helper_class = NewHelper
use_foo(eggs)



> Initial experiments appear to show that this scheme works well.  My
> questions:
> 
> 1. Is this scheme completely safe?  Anything to watch out for?

No tricky *technical* details that I'm aware of...


> 2. Any suggestions, improvements or simplifications?

...but, though I think fundamentally your idea is good, rebinding
module names seems at the least an unconventional way to implement it,
likely to lead to confusion in people reading your code.  I don't see
any gain from that unconventional way of doing things (happy to be
proved wrong, though).  Instead, why not use a class instance to
represent your application, and allow plugins to mess with that
(subject to certain rules, no doubt)?  Or let the plugins define new
classes and register them.

Obviously, a major thing to consider is how you're going to stop one
plugin treading on the toes of another, to the extent that that's
possible.


John




More information about the Python-list mailing list