pythonic way to optimize access to imported value?
Michael Hudson
mwh at python.net
Tue Nov 19 12:25:28 EST 2002
bokr at oz.net (Bengt Richter) writes:
> 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 ;-)
It was fname at one point, but I thought that obscure...
> > 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.
Hmm. Yes.
> IIRC I saw some docs on sandboxing import. That's probably the trail
> to follow.
Yeah, just don't touch sys.modules in your __import__, I guess.
I wonder if
import new, __builtin__
mod = new.module(modname)
d = __builtin__.__dict__.copy()
d['__import__'] = my_hook
mod.__dict__['__builtins__'] = d
exec open(file).read() in mod.__dict__
return mod
would be a good start?
> Thanks for the reminders. BTW, is there a reason you preferred
>
> exec open(file).read() in mod.__dict__
> over
> execfile(filepath, mod.__dict__)
> above?
Nope.
Cheers,
M.
--
Exam invigilation - it doesn't come much harder than that, esp if
the book you're reading turns out to be worse than expected.
-- Dirk Bruere, sci.physics.research
More information about the Python-list
mailing list