[Python-Dev] requirements for moving __import__ over to importlib?
Terry Reedy
tjreedy at udel.edu
Wed Feb 8 00:40:37 CET 2012
On 2/7/2012 4:51 PM, PJ Eby wrote:
> One thing I'm a bit worried about is repeated imports, especially ones
> that are inside frequently-called functions. In today's versions of
> Python, this is a performance win for "command-line tool platform"
> systems like Mercurial and PEAK, where you want to delay importing as
> long as possible, in case the code that needs the import is never called
> at all... but, if it *is* used, you may still need to use it a lot of
> times.
>
> When writing that kind of code, I usually just unconditionally import
> inside the function, because the C code check for an already-imported
> module is faster than the Python "if" statement I'd have to clutter up
> my otherwise-clean function with.
importlib could provide a parameterized decorator for functions that are
the only consumers of an import. It could operate much like this:
def imps(mod):
def makewrap(f):
def wrapped(*args, **kwds):
print('first/only call to wrapper')
g = globals()
g[mod] = __import__(mod)
g[f.__name__] = f
f(*args, **kwds)
wrapped.__name__ = f.__name__
return wrapped
return makewrap
@imps('itertools')
def ic():
print(itertools.count)
ic()
ic()
#
first/only call to wrapper
<class 'itertools.count'>
<class 'itertools.count'>
--
Terry Jan Reedy
More information about the Python-Dev
mailing list