English 中文(简体)
如何利用最先进的(AbstractStax 树)模块获得完全的“胎”?
原标题:How to get the full "path" to a node using the ast (Abstract Syntax Trees) module?

I m tinkering with Zhu ast(Abstractyntax大树s)模块。

利用ast.NodeVisitor,有可能走一条源树,并显示各种信息,如每一代号:

class MyAST(ast.NodeVisitor):      

     def visit_ClassDef(self, node):
         print(node.col_offset * " " +node.name)         
         self.generic_visit(node)   

     def visit_FunctionDef(self, node):         
         print(node.col_offset * " " + node.name)     
         self.generic_visit(node)   

之后,可将其用于任何一类法典:

tree = ast.parse(open("/path/to/file.py").read())
MyAST().visit(tree)

这将产生一些成果(例如:models.py,从requests包装:

RequestEncodingMixin                                                                                                                                                         
    path_url                                                                                                                                                                 
    _encode_params                                                                                                                                                           
    _encode_files                                                                                                                                                            
RequestHooksMixin                                                                                                                                                            
    register_hook                                                                                                                                                            
    deregister_hook                                                                                                                                                          
Request                                                                                                                                                                      
    __init__
    __repr__
    prepare
(...)

我愿就某一节点知道对它的全部“pa”。 在上述产出样本中,如果在<条码>功能设计/代码>上出现I m,则我知道其母是<条码>。 职等DefRequestHooksMixin,以便我能产生RequestHooksMixin.deregister_hook<>。

问题回答

ast.NodeVisitor 设计时,没有考虑到加固等级,因此,它是产生基于等级的缩减的产出的最佳工具。

相反,你可以使用<条码>ast.iter_child_nodes,以 rec击每一节日子的直接儿童节点,并在课堂或职能时,产生节点和增加退学水平。

import ast

def build_tree(node):
    def _visit(node, level=0):
        if isinstance(node, (ast.ClassDef, ast.FunctionDef)):
            yield node.name, level
            level += 1
        for child in ast.iter_child_nodes(node):
            yield from _build_tree(child, level)
    return  
 .join(f {"    " * level}{name}  for name, level in _visit(node))

so that:

source =    
class Foo:
    def method1(self):
        pass
    def method2(self):
        pass

class Bar:
    def method1(self):
        pass
    def method2(self):
        pass
   
print(build_tree(ast.parse(source)))

outputs:

Foo
    method1
    method2
Bar
    method1
    method2

Demo:





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签