0

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

1 Answer 1

1

I'd take the problem in three steps:

  1. 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.
  2. Get the source code for the module. Using inspect.getsource is probably the easiest way (but you could also just try open(the_module.__file__).read() and it is likely to work).
  3. 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 builtin compile instead, as long as you pass the appropriate flag (ast.PyCF_ONLY_AST appears to be 1024 on my system, so compile(source, filename, 'exec', 1024) should work).
answered Jun 3, 2018 at 23:20
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.