Tuesday, 20 August 2013

How to run "exec" from the global scope in python

How to run "exec" from the global scope in python

I have a Class. In that class I have a function. In the function, I have a
string variable that holds definitions of several python functions.
I would like from the function to create the functions that are defined in
the variable, such that they will be created in the global scope.
After this operation, I would like to be able to call to the new function
from the global scope.
For example:
class MyClass:
def create_functions():
functions_to_create = """
def glob1():
return "G1"
def glob2():
return "G2"
"""
# ----> HERE IS THE MISSING PART, LIKE RUNNING exec in the global scope
<----
# The following function should work:
def other_function_in_global_scope():
print "glob1: %s, glob2: %s" % (glob1(), glob2())
What should be in the MISSING PART?
Thanks in advance!!!

No comments:

Post a Comment