Is there anyway to selectively inherit/import a class/module?

Steven D'Aprano steve+comp.lang.python at
Tue Jan 3 20:06:20 EST 2012

On Tue, 03 Jan 2012 14:21:36 -0800, Peter wrote:

> I have a program that talks to a device via a serial interface.
> Structurally it looks like this:
> Program A -> module B -> Serial

I don't understand what this means. Program A points to module B, which 
points to ... what is Serial? Where is it? Is it a class inside the 
module, or another module?

> I want to add a protocol layer around the serial port without modifying
> any of the modules above and I want to be able to use BOTH cases of the
> program whenever convenient, 

Where are you using them from? Program A, or another program?

I don't see any way to add the extra functionality to Program A without 
modifying Program A. But if you're okay with that, here's a way to 
conditionally define a class to use:

# inside Program A
import moduleB

if condition:
    Serial = moduleB.Serial  # I assume moduleB has a Serial class
    class Serial(moduleB.Serial):  # subclass
        def mymethod(self):

connection = Serial(...)

> so at first it seemed like a simple case of
> sub-classing the Serial class and then (this is the problem) somehow use
> either the original serial class definition when I wanted the original
> program functionality or the new class when I wanted the extra layer
> present.

No problem. Here's another way to do it:

from moduleB import Serial as SimpleSerial
class ComplexSerial(SimpleSerial):

And now you can use both at the same time.


More information about the Python-list mailing list