<p>I am a little confused by the multitude of ways in which you can import modules in Python.  </p>

<pre><code>import X
import X as Y
from A import B
</code></pre>

<p>I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why.  Should imports happen at a module level or a method/function level?  In the <code>__init__.py</code> or in the module code itself?</p>

<p>My question is not really answered by "<a href="https://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file">Python packages - import by class, not file</a>" although it is obviously related.</p>

I would normally use
```
import X
```
on module level. If you only need a single object from a module, use
```
from X import Y
```
.
Only use
```
import X as Y
```
in case you're otherwise confronted with a name clash.
I only use imports on function level to import stuff I need when the module is used as the main module, like:
```
```
def main():
  import sys
  if len(sys.argv) > 1:
     pass
```
```
HTH