pythonic way to optimize access to imported value?

Bengt Richter bokr at oz.net
Tue Nov 19 11:22:06 EST 2002


On Tue, 19 Nov 2002 11:47:57 GMT, Michael Hudson <mwh at python.net> wrote:

>bokr at oz.net (Bengt Richter) writes:
>
>> 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.
>
>I don't think this is so hard:
>
>def load_file(file, modname):
               ^^^^- tch, tch ;-)
>    import new
>    mod = new.module(modname)
>    exec open(file).read() in mod.__dict__
>    return mod
>

But as Jeff pointed out, if there are any imports in your imported file,
you have to encapsulate them too. So you need a temporary sandbox
import that captures all the import action into a private container/space.

IIRC I saw some docs on sandboxing import. That's probably the trail to follow.

>Then mod should only have the one reference:
>
>>>> import new
>>>> sys.getrefcount(new.module('temp'))
>1

>
>Also see the imp module; some of the hooks there don't insert in
>sys.modules (but I can't remember which ones now).
>
Thanks for the reminders. BTW, is there a reason you preferred

    exec open(file).read() in mod.__dict__
over
    execfile(filepath, mod.__dict__)
above?

Regards,
Bengt Richter



More information about the Python-list mailing list