On Sat, 10 Dec 2005 19:40:08 -0800, Robert Kern <[EMAIL PROTECTED]> wrote:
>Bengt Richter wrote: > >> Are you willing to type a one-letter prefix to your .re ? E.g., >> >> >>> class I(object): >> ... def __getattr__(self, attr): >> ... return __import__(attr) > >[snip] > >> There are special caveats re imports in threads, but otherwise >> I don't know of any significant downsides to importing at various >> points of need in the code. The actual import is only done the first time, >> so it's effectively just a lookup in sys.modules from there on. >> Am I missing something? > >Packages. > Ok, if you're willing to add a trailing '._' to indicate the end of a package path, and start it with a P instead of an I, you could try the following (just a hack, not tested beyond what you see, (again ;-) ) ----< impexpr.py >-------------------- class I(object): __cache = {} def __getattr__(self, attr, cache = __cache): try: return cache[attr] except KeyError: cache[attr] = ret = __import__(attr) return ret getdotted = __getattr__ class P(I): def __init__(self): self.elems = [] def __getattr__(self, attr): if attr == '_': dotted = '.'.join(self.elems) mod = self.getdotted(dotted) for attr in self.elems[1:]: mod = getattr(mod, attr) self.elems = [] return mod else: self.elems.append(attr) return self P, I = P(), I() -------------------------------------- >>> from ut.impexpr import I, P >>> I.math.pi 3.1415926535897931 >>> I.os.path.isfile <function isfile at 0x02EB5534> >>> P.ut.miscutil._.prb <function prb at 0x02F1EBC4> >>> type(I)._I__cache.keys() ['ut.miscutil', 'os', 'math'] >>> P.ut.miscutil._.disex <function disex at 0x02F1EDBC> >>> type(I)._I__cache.keys() ['ut.miscutil', 'os', 'math'] >>> I.ut.miscutil <module 'ut.miscutil' from 'c:\pywk\ut\miscutil.pyc'> >>> I.ut <module 'ut' from 'c:\pywk\ut\__init__.pyc'> I am not recommending this particularly. I just like to see how close python already is to allowing the spelling folks initially think requires a language change ;-) Regards, Bengt Richter -- http://mail.python.org/mailman/listinfo/python-list