Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting module name with ast

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).

like image 972
amit Avatar asked Mar 09 '26 04:03

amit


1 Answers

AFAIU, this information doesn't exist in ast. More formally, the abstract grammar for Module in Python is:

mod = Module(stmt* body)
    | Interactive(stmt* body)
    | Expression(expr body)

    -- not really an actual node but useful in Jython's typesystem.
    | Suite(stmt* body)

So as you can see a Module just 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.

like image 148
Eli Bendersky Avatar answered Mar 11 '26 20:03

Eli Bendersky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!