Given only source file, what files does it import?
<p>I'm building a dependency graph in python3 using the <code>ast</code> module. How do I know what file(s) will be imported if that import statement were to be executed?</p>

<p>Not a complete answer, but here are some bits you should be aware of:</p>

<ul>
<li>Imports might happen in conditional or try-catch blocks. So depending on a setting of an environment variable, module A might or might not import module B.</li>
<li>There's a wide variety of import syntax: <code>import A</code>, <code>from A import B</code>, <code>from A import *</code>, <code>from . import A</code>, <code>from .. import A</code>, <code>from ..A import B</code> as well as their versions with <code>A</code> replaced with sub-modules.</li>
<li>Imports can happen in any executable context - the top-level of the file, in a function, in a class definition etc.</li>
<li><code>eval</code> can evaluate code with imports. Up to you if you consider such code to be a dependency.</li>
</ul>

<p>The standard library <a href="https://docs.python.org/3.5/library/modulefinder.html" rel="nofollow">modulefinder</a> module might help.</p>

python python-3.x python-import abstract-syntax-tree