How to create a function object from an ast.FunctionDef node?

后端 未结 2 1277
执笔经年
执笔经年 2021-01-19 07:44

I am trying to understand the process by which python code gets executed. Suppose the source has a function definition. Using ast.parse(), I parse it into an as

2条回答
  •  一向
    一向 (楼主)
    2021-01-19 08:14

    In case the function is under a class, below code will help - import ast

    txt = """
    class MyClass():
      def foo(x, y=2):
          z = x*y + 3
          print("z is", z)
          return z**2
    """
    
    tree = ast.parse(txt, mode='exec')
    code = compile(tree, filename='blah', mode='exec')
    namespace = {}
    exec(code, namespace)
    val = "foo"
    dict_item = namespace["MyClass"].__dict__.items()
    for x,y in list(dict_item):
      if val == x:
        print(x)
        print(y)
        print(type(x))
        print(type(y))
    

提交回复
热议问题