Changing base class of a big hierarchy

Alex Martelli aleax at
Mon Aug 4 14:20:25 CEST 2003

John J. Lee wrote:

> bokr at (Bengt Richter) writes:
>> On 03 Aug 2003 12:31:37 +0100, jjl at (John J. Lee) wrote:
>> >I'm trying to change a base class of a big class hierarchy.  The
>> >hierarchy in question is 4DOM (from PyXML).  4DOM has an FtNode class
>> >that defines __getattr__ and __setattr__ that I need to override.
>> >
>> If FtNode lived in a separate module that was imported, could you
>> import an impostor module which would override subsequent imports?
> That's a tempting idea, but is it possible (without a lot of work) to
> do it *without* ending up with sys.modules containing my hacked
> FtNode?  I don't want my hacked class hierarchy to infect other
> peoples code that innocently imports xml.dom.
> How would you go about it?

Well, you could:
  -- import the original FtNode (say "import FtNode")
  -- save xxx = sys.modules['FtNode']
  -- patch sys.modules['FtNode'] = yourhackedmodule
  -- do the deed
  -- restore sys.modules['FtNode'] = xxx

Now lots of OTHER modules (imported during "do the deed") might
be 'infected', but regarding sys.modules['FtNode'] specifically,
you're safe.  If you can identify the whole set of modules that
need to be saved, temporarily removed, than restored in this way,
the generalization should be easy.  This may break down if any
code you're using has 'import' statements in functions or methods,
since said import statements will now access the restored modules
when they execute after you've done the restoration, but most
code imports only at module top-level, so this might work.

I'd still prefer to work on the class hierarchies and keep the
modules alone, due to this kind of issues and fragilities, but
the module-based approach might also be workable.


More information about the Python-list mailing list