Nick Coghlan | 7 Dec 10:19 2007
Picon

Interest in PEP for callbacks on module import

guido.van.rossum wrote:
> Modified: python/branches/py3k/Lib/numbers.py
> ==============================================================================
> --- python/branches/py3k/Lib/numbers.py	(original)
> +++ python/branches/py3k/Lib/numbers.py	Thu Dec  6 18:45:33 2007
>  <at>  <at>  -43,6 +43,7  <at>  <at> 
>  
>  Inexact.register(complex)
>  Inexact.register(float)
> +# Inexact.register(decimal.Decimal)

With the new abstract base classes in Py3k, I can see it being 
worthwhile to have a standard mechanism to allow callbacks to be 
registered for execution when particular modules are first imported.

For example, to handle the commented out case above:

    <at> imp.imported('decimal')
   def register(decimal):
       Inexact.register(decimal.Decimal)

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.

Does anyone else think this is an issue worth pursuing? We've already 
had a couple of instances come up in relation to the registration of 
array.array and decimal.Decimal with the appropriate abstract base 
classes. I expect there are other areas of the standard library (e.g. 
ctypes, mmap) where being able to register container types when the 
collections module is imported would be beneficial.

Cheers,
Nick.

[1] http://peak.telecommunity.com/DevCenter/Importing

--

-- 
Nick Coghlan   |   ncoghlan <at> gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org

Gmane