[Python-3000] Interest in PEP for callbacks on module import
Christian Heimes
lists at cheimes.de
Fri Dec 7 12:33:50 CET 2007
Nick Coghlan wrote:
> For example, to handle the commented out case above:
>
> @imp.imported('decimal')
> def register(decimal):
> Inexact.register(decimal.Decimal)
I like the syntax assuming that imp.imported(name) expects a method that
accepts the module object as argument.
> I think a PEP would be needed to decide whether to handle this in a
> fashion similar to that of PJE's Importing toolkit [1] (i.e., using lazy
> imports where the actual loading of the module code is deferred until
> the first access to an attribute of the module), or else to add a new
> mechanism directly to the interpreter code, where the registered
> callbacks would be called as soon as the specified module was loaded.
I find a new mechanism easier to implement. Lazy or deferred imports
require frame hacks and you know how Guido thinks about sys._getframe(). :)
An implementation based on your suggestion is simple. Add a registry to
imp which is a simple dict that maps dotted module names to a list of
callables. Upon import the IMP module calls the callables after the
module is inserted into sys.modules. That's it. :]
Zope's deferredimport [1] package has a nice idea. It supports
deprecation warnings when a deprecated attribute is accessed the first time.
>>> import somemodule
No warning is raised
>>> somemodule.deprecated_feature
DeprecationWarning ...
The package makes use of stack inspection and a proxy package.
> Does anyone else think this is an issue worth pursuing?
Yes, count me in. I like to help with the PEP and implementation. :)
Christian
[1] http://svn.zope.org/zope.deferredimport/trunk/src/zope/deferredimport/
More information about the Python-3000
mailing list