How can I do 'from foo import bar as b' with imp in Python2.7?
<p>I need to import a module without knowing it's location in advance; The user will specify the location as an argument to my script. </p>

<p>I know I can use <code>imp</code> for imports, like </p>

<pre><code>import imp
foo = imp.load_source('foo', '/path/to/foo.py')
</code></pre>

<p>which is functionally equivalent to </p>

<pre><code>import foo
</code></pre>

<p>if foo was found in PATH. </p>

<p>How can I construct something similar to </p>

<pre><code>from foo import bar as b
</code></pre>

<p>?</p>

<p>As I commented, you can use normal attribute access to get the <code>bar</code> object from the module object returned from <code>imp.load_source</code>, even within the same expression:</p>

<pre><code>b = imp.load_source('foo', '/path/to/foo.py').bar
</code></pre>

<p>This isn't quite the same as <code>from foo import bar as b</code>, since <code>load_source</code> always reads the source file and creates a new module object with new contents. An <code>import</code> statement will only load the module once, and use the cached version of it from <code>sys.modules</code> if you import it again.</p>

python python-2.7 python-import