So I have the following code.
code_string = """def f1(p1, p2, p3):
print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
print("text")
"""
code = compile(code_string, '<string>', 'exec')
f1 = code.co_consts[0]
f2 = code.co_consts[2] # code.co_consts is the name of the prior function ("f1")
It compiles a string with some functions into a code object and then stores the code objects of the functions to separate variables.
What I want to know is how to create function objects using the code objects above so I can just call them.
So say ff1 = new_function(f1) where isinstance(ff1, types.FunctionType) would be True and I could just do ff1('a', 'b', 'c') to print "aa, bb, cc".
The code objects in f1 and f2 can be executed using exec. (Though I don't know how to pass arguments into f1 or make a bound method out of them this way)
You already extracted the code objects, now all you have to do is to create the functions objects using types.FuncitonType. It accepts:
from types import FunctionType
code_string = """\
def f1(p1, p2, p3):
print("a{}, b{}, c{}".format(p1, p2, p3))
def f2():
print("text")
"""
code = compile(code_string, "<string>", "exec")
f1_code_object = code.co_consts[0]
f2_code_object = code.co_consts[1]
f1 = FunctionType(f1_code_object, globals(), "f1")
f2 = FunctionType(f2_code_object, globals(), "f2")
print(f1)
print(f2)
f1(10, 20, 30)
f2()
output:
<function f1 at 0x1042a2980>
<function f2 at 0x1042a2a20>
a10, b20, c30
text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With