Let's say the name of the module is available in form of a string rather than module object. How do I locate its source code location and load the abstract syntax tree (if the source code is present)?
asked Jun 3, 2018 at 21:56
Rahim Mammadli
1831 silver badge9 bronze badges
1 Answer 1
I'd take the problem in three steps:
- Import the module by name. This should be relatively easy using
importlib.import_module, though you could bodge up your own version with the builtin__import__if you needed to. - Get the source code for the module. Using
inspect.getsourceis probably the easiest way (but you could also just tryopen(the_module.__file__).read()and it is likely to work). - Parse the source into an AST. This should be easy with
ast.parse. Even for this step, the library isn't essential, as you can use the builtincompileinstead, as long as you pass the appropriate flag (ast.PyCF_ONLY_ASTappears to be1024on my system, socompile(source, filename, 'exec', 1024)should work).
answered Jun 3, 2018 at 23:20
Blckknght
106k11 gold badges135 silver badges188 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py