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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4