I learnt that exec
can create function dynamically from this post Python: dynamically create function at runtime .
I want to create a function on the fly inside an instance method, and use the function after that.
But the code below fails, why?
class A:
def method_a(self, input_function_str: str):
exec('''def hello():
print('123')
''')
# hello() # call hello() here leads to NameError
b = A()
b.method_a()
# hello() # call hello() here also leads to NameError
My goal is that I dynamically create a function based on input_function_str
passing from outside, then use that function somewhere in method_a
.