<div class="gmail_quote">On Tue, Feb 7, 2012 at 6:40 PM, Terry Reedy <span dir="ltr"><<a href="mailto:tjreedy@udel.edu">tjreedy@udel.edu</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<div class="im">importlib could provide a parameterized decorator for functions that are the only consumers of an import. It could operate much like this:</div>
<br>
def imps(mod):<br>
def makewrap(f):<br>
def wrapped(*args, **kwds):<br>
print('first/only call to wrapper')<br>
g = globals()<br>
g[mod] = __import__(mod)<br>
g[f.__name__] = f<br>
f(*args, **kwds)<br>
wrapped.__name__ = f.__name__<br>
return wrapped<br>
return makewrap<br>
<br>
@imps('itertools')<br>
def ic():<br>
print(itertools.count)<br>
<br>
ic()<br>
ic()<br>
#<br>
first/only call to wrapper<br>
<class 'itertools.count'><br>
<class 'itertools.count'><br></blockquote><div><br></div><div>If I were going to rewrite code, I'd just use lazy imports (see <a href="http://pypi.python.org/pypi/Importing">http://pypi.python.org/pypi/Importing</a> ). They're even faster than this approach (or using plain import statements), as they have zero per-call function call overhead. It's just that not everything I write can depend on Importing.</div>
<div><br></div><div>Throw an equivalent into the stdlib, though, and I guess I wouldn't have to worry about dependencies...</div><div><br></div><div>(To be clearer; I'm talking about the <a href="http://peak.telecommunity.com/DevCenter/Importing#lazy-imports">http://peak.telecommunity.com/DevCenter/Importing#lazy-imports</a> feature, which sticks a dummy module subclass instance into sys.modules, whose __gettattribute__ does a reload() of the module, forcing the normal import process to run, after first changing the dummy object's type to something that doesn't have the __getattribute__ any more. This ensures that all accesses after the first one are at normal module attribute access speed. That, and the "whenImported" decorator from Importing would probably be of general stdlib usefulness too.)</div>
<div><br></div></div>