How to get a python module name using ast? I tried the following to get the Module Node, but looks like it does not have the name information:
class v(ast.NodeVisitor):
def visit_Module(self, node):
print "Module : %s" % node
v().visit_Module(ast.parse(f.read(), filename))
I basically need the actual module name (If it is inside a package then the complete one like a.b.module).
AFAIU, this information doesn’t exist in
ast. More formally, the abstract grammar for Module in Python is:So as you can see a
Modulejust has a body which is a list of statement nodes. There’s no name.Do note that you pass
f.read()to the visitor. That returns the contents of the file, without actually knowing or caring how that file is named – where can you take the module name from it?From executing Python code, you can use
__name__and__package__from inside Python code.