[Tutor] Isolation of code

Dave Kuhlman dkuhlman at rexx.com
Sun Oct 8 17:59:20 CEST 2006

On Sun, Oct 08, 2006 at 12:36:32PM +0530, Noufal Ibrahim wrote:
> Greetings everyone,
>    I'm working on a little project that's similar to tcltutor for python.
> I have a string which has some python code. I "compile" and "eval" this
> to get the output. So far so good. However, when this happens, the
> evaluation is happening in the current namespace so I'm afraid of
> symbols being redefined and messed up.
>    What I want to do is to create a separate namespace for all the code so
> that I can execute it without worrying about symbol mangling.
>    Something like if the code I have is
> code = """
> x=5
> if x==5:
>   print "Yes"
> else:
>   print "No"
> """
> I'd like to be able to create a separate module called (say) "tester"
> with contents
> def __start_exec__():
>   <contents of the code variable>
> then say something like
> import tester
> tester.__start_exec__()
> to actually run the code. This way, the namespace would be separate.

Two points:

1. (Stating something obvious) Code in a module, when called, does
   run in a separate namespace.  For example, if I run:

       import modB

   then any variables set in modB are local to modB.

2. If that separation of namespaces is not "strong" enough for you,
   try something like the following:

       exec somecode in globalDict

   where globalDict is a dictionary.  globalDict will be the
   namespace used by somecode, and, for example, variables created
   (perhaps using assignment) in somecode will be created in
   globalDict rather than in the current namespace.  See:


Dave Kuhlman

More information about the Tutor mailing list