Given the source code of a Python file, I would like to detect all imported objects. For example, given this source:
import mymod
from mymod2 import obj1, obj2, obj3
from mymod3 import aobj
I want to get:
[('mymod2', 'obj1', 'obj2', 'obj3'), ('mymod3', 'aobj')]
I have already tried this regex:
r'from (?P<mod>[_\w\d]+) import (?:(?P<obj>[_\w\d]+)[,\s]?)+'
But I only get the first imported object:
[('mymod2', 'obj1'), ('mymod3', 'aobj')]
A better tool than regular expressions is the
astmodule that comes with Python. To find allfrom ... importstatements in the outermost scope ofa.pyand print all imported names, you could useNote that this simple code will miss any statements that are not directly at module level, such as import statements inside a try-block. This can easily be fixed by using
ast.walk()to walk over all nodes.