Commits

ebo  committed 8c9455d

compile now creates function objects with the correct globals object.

  • Participants
  • Parent commits ca82f16

Comments (0)

Files changed (1)

File topcompiler.py

     return codeobj
 
 
-def compile(code):
-    """Compile code into a python function. Code may be a string or a function object"""
+def compile(code, g=None):
+    """Compile code into a python function. Code may be a string or a function object
+The globals object is autosensed when compiling a function object, for strings it inserts topcompiler modules globals. This can be overridden by providing a new globals object as second parameter."""
 
     if not PY_VERSION:
         raise TOPCompilerException("Incompatible Python Version. Expected version 2.6 or 2.7!")
     if isinstance(code, basestring):
         doc = code
         args = []
+        if g == None:
+            g = globals()
     elif isinstance(code, types.FunctionType):
         doc = code.__doc__
         args = code.func_code.co_varnames[:code.func_code.co_argcount]
+        if g == None:
+            g = code.func_globals
 
     ast = plygram.parser.parse(doc)
     TailRecursionAnalysis().analyse(ast)
 
     codeobj = compile_code(ast, args)
 
-    func = types.FunctionType(codeobj, globals())
+    func = types.FunctionType(codeobj, g)
     func.__doc__ = doc
     return func