pythonic way to optimize access to imported value?

Bengt Richter bokr at oz.net
Mon Nov 18 13:58:40 EST 2002


On Mon, 18 Nov 2002 01:04:43 -0800, Brian Quinlan <brian at sweetapp.com> wrote:

>Bengt wrote:
>> IOW, IMO there ought to be a way to do a temporary
>global-side-effect-free
>> import and delete all traces of its having been done -- without
>restarting
>> the interpreter or invoking a second interpreter instance.
>
>Does that involve unloading a dynamically imported library? If so, you
>will have to figure out how to do that in a cross-platform manner and
>without breaking existing Python extensions.
>
Ideally.

>Here are some other issues:
>1. What happens if two "throwaway" imports of the same module happen at
>   once?
IWT something analogous to execfile. I.e., depending on what name spaces you chose.

>2. What happens if the extension module modifies global state?
Depends on which global state and how. I.e., (re)binding a name in globals()
so that it refers to the module directly or indirectly would naturally prevent unloading.
But binding a name anywhere outside the module to something independent of the module,
like immutables or dynamically generated data, etc. would be typical usage, not a problem.
    
>3. What happens if the extension module causes external entities to 
>   hold references to its objects?
Sure, that would be a problem for objects that are not separable, but my hope
was that e.g. constants and pure functions and such in .py modules could be
referenced and held while the module and anything unreferenced in it was deleted.
For C modules I would expect limitations.

Hm. Which raises the question of what you get if you write

     pi = __import('math').pi

vs
     pi = __import('math').pi*1.0

I.e., is the first pi a reference to an embedded double within the C module's memory space,
which is therefore not separable? Or is it a true heap-borne python object constructed at load
time? I'd expect the second pi to be free of any math module attachment, but is the first?
I imagine you could write it to work either way.

The same principle could apply to other attributes of a C module, IWT.

Regards,
Bengt Richter



More information about the Python-list mailing list