I am trying to make an interpreter of code written in some language in python and currently stuck on interpreting functions. It seems there is a way of creating classes dynamically with something like MyClass = type("MyClass", (object, ), dict())
but I can't find a way of creating functions. I have an idea of direct line to line translation of code in python code and execution but that's not really what I want to do. So is there a way to create functions dynamically or the best I can get is something like:
foo_code = compile('def foo(): return "bar"', "<string>", "exec")
foo_func = FunctionType(foo_code.co_consts[0], globals(), "foo")
with need of translation?
CodePudding user response:
Just found out the answer. The best way to dynamically create the function is to not create it at all. It kind of conflicts with my question but still solves the problem. The idea is to put a structure of a function as key in a dictionary and a line of the beginning of the function as a value. So now it is possible by structure of the function find it, execute and then return to normal execution by saving the last line of Main in advance.