[Python-Dev] a strange case
Troy Melhase
troy@gci.net
Fri, 16 May 2003 13:45:25 -0800
> Jeremy> I think we decided this wasn't a pure bugfix :-). Some poor
> Jeremy> soul may have code that relies on being able to subclass a
> Jeremy> module.
>
> How about at least deprecating that feature in 2.2.3 and warning about it
> so that poor soul knows this won't be supported forever?
I think I'm knocking on the poor-house door.
Just last night, it occurred to me that modules could be made callable via
subclassing. "Why in the world would you want callable modules you ask?" I
don't have a real need, but I often see the line blurred between package,
module, and class. Witness:
from Foo import Bar
frob = Bar()
If Bar is initially a class, then is reimplemented as a module, client code
must change to account for that. If Bar is reimplemented as a callable
module, clients remain unaffected.
I haven't any code that relies on subclassing the module type, but many times
I've gone thru the cycle of coding a class then promoting it to a module as
it becomes more complex. I'm certainly not advocating that the module type
be subclassable or not, but I did want to point out a possible legitmate need
to derive from it. Many apologies if I'm wasting space and time.
-troy
Silly example:
troy@marchhare tmp $ cat foo.py
def op():
print 'foo op'
def frob():
print 'foo frob'
def __call__(a, b, c):
print 'module foo called!', a, b, c
troy@marchhare tmp $ cat bar.py
class ModuleObject(type(__builtins__)):
def __init__(self, amodule):
self.amodule = amodule
self.__name__ = amodule.__name__
self.__file__ = amodule.__file__
def __getattr__(self, attr):
return getattr(self.amodule, attr)
def __call__(self, *a, **b):
return self.amodule.__call__(*a, **b)
import foo
foo = ModuleObject(foo)
foo(1,2,3)
troy@marchhare tmp $ python2.3 bar.py
module foo called! 1 2 3