Is there anyway to selectively inherit/import a class/module?
peter.milliken at gmail.com
Tue Jan 3 17:21:36 EST 2012
I have a program that talks to a device via a serial interface.
Structurally it looks like this:
Program A -> module B -> Serial
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, 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.
Module B has
so my first thought was to put the new module in the current directory
and call it "serial.py". This would allow me to run the program with
the new Serial class and when I didn't want that extra layer, all I
had to do was rename the module to something else and let Module B
pick up serial from the site-package area. But (obviously) this
doesn't work because the new class's first few statements are:
So when Module B does the import (and gets the new class definition),
I get an error message (as the new definition is loaded):
AttributeError: 'module' object has no attribute 'Serial' on the Class
Is there anyway to have Module B use the new class without modifying
the content of Module B?
The only other alternative I can think of is to create a copy of the
original program, rename the new class file and have two complete
copies of the program but that is not ideal :-)
More information about the Python-list