[Python-3000] Function overloading (Math in Python 3.0)

Phillip J. Eby pje at telecommunity.com
Fri May 19 16:28:14 CEST 2006


At 10:17 PM 5/18/2006 -0700, "Guido van Rossum" <guido at python.org> wrote:
>But even so we'd have to solve the delayed-loading issue: you don't
>want "import gmath" to imply "import decimal, math, cmath, gnump" nor
>would you (ideally) have "import decimal" imply "import gmath". But if
>both are imported (in either order) the right thing should happen.
>How...?

By putting something like this in decimal:

     @onImport('gmath')
     def register(gmath):
         defop gmath.sqrt(x: decimal):
             # etc.

PEAK already has an equivalent to 'onImport' that can do this without the 
need for import hooks.

If the module is already imported, the function just gets called 
normally.  If it's not imported, it puts an instance of a ModuleType 
subclass into sys.modules, whose __getattribute__ calls reload() to 
actually load the module, and then changes the module object's type back to 
normal and calls any functions that were registered for that module.

(This actually results in lazy loading, in that if you 'import gmath' after 
'import decimal', gmath won't really be imported until you reference one of 
its attributes, or until you 'from gmath import sqrt' or something.)



More information about the Python-3000 mailing list