[Python-Dev] requirements for moving import over to importlib? (original) (raw)
Terry Reedy tjreedy at udel.edu
Wed Feb 8 00:40:37 CET 2012
- Previous message: [Python-Dev] requirements for moving __import__ over to importlib?
- Next message: [Python-Dev] requirements for moving __import__ over to importlib?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Previous message: [Python-Dev] requirements for moving __import__ over to importlib?
- Next message: [Python-Dev] requirements for moving __import__ over to importlib?
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]