Inheriting Python modules?
Quinn Dunkan
quinn at retch.ugcs.caltech.edu
Thu Dec 20 15:36:48 EST 2001
On Tue, 18 Dec 2001 17:10:19 GMT, Timo Linna
<timo.SPAM.linna at iki.ME.fi.NOT.invalid> wrote:
>Hi,
>
>How should "dynamic module inheritance" be implemented with Python?
>
>Example:
>
>It should be possible to write: "import defaults" so that it would first
>import everything from common.defaults -module and after that other stuff
>from product.defaults-module. Content of both modules should be accessible
>through one common (defaults) interface so that the caller wouldn't have to
>know from which module the code is actually accessed.
>
>I would NOT like to create "dummy" logical defaults-module which would
>simply import both modules - things should happen automatically at runtime.
Anyway, untested:
class Multi_namespace:
def __init__(self, namespaces):
self.namespaces = namespaces
def __getattr__(self, attr):
for ns in self.namespaces:
try:
return getattr(ns, attr)
except AttributeError:
pass
raise AttributeError(attr)
m = Multi_namespace(map(__import__, (sys, os)))
print m.path
print m.access
If you like that sort of thing, you could stuff 'm' into sys.modules.
Speaking of which, here's a fun way to bind a lot of names:
class c: pass
for k, v in lot_of_names:
setattr(c, k, v)
sys.modules['c'] = c
from c import *
More information about the Python-list
mailing list