(original) (raw)
On Tue, Feb 7, 2012 at 6:40 PM, Terry Reedy <tjreedy@udel.edu> wrote:
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'>
If I were going to rewrite code, I'd just use lazy imports (see http://pypi.python.org/pypi/Importing ). �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.
Throw an equivalent into the stdlib, though, and I guess I wouldn't have to worry about dependencies...
(To be clearer; I'm talking about the�http://peak.telecommunity.com/DevCenter/Importing#lazy-imports�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.)