import from string?

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jan 29 07:49:16 EST 2002


"Mike" <mgould at orchestream.com> wrote in news:1012311260.582359 at lave:

> I'd like all the scripts to be imported as modules to prevent
> namespace clashes and so that the scopeing behaviour is as the script
> authors expect. The problem is that I can't see how to import python
> code held in a string instead of a file.
> 
> I've looked at using the __import__ function but in all cases this
> looks for a built-in module or a file.
> I've also tried using exec and specifying the local and global scopes
> explicitly but this requires the namespaces to be created beforehand. 
> Using the class statement to create namespaces is probably not the way
> forward and providing ordinary dictionary objects doesn't seem to work
> properly. 

Is this what you want?
>>> import new
>>> fred = new.module('fred')
>>> exec('def f():\n  print "hello"\n  print x\n', fred.__dict__)
>>> fred.x = 5
>>> fred.f()
hello
5
>>>


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list