How to not import imported submodules in a Python module?
<p>In my Python modules I often use sub-modules such as <code>datetime</code>. The issue is that these modules become accessible from outside: </p>

<pre><code># module foo
import datetime

def foosay(a):
    print "Foo say: %s" % a
</code></pre>

<p>From IPython:</p>

<pre><code>import foo
foo.datetime.datetime.now()
</code></pre>

<p>I would like to know how to properly hide the sub-modules that are the internal business of <code>foo</code>.</p>

<p>I naively thought about <code>import datetime as _datetime</code> or even <code>import datetime as __datetime</code>, but this is not very pleasant solution. I've also read about <code>__all__</code>, but it only concerns what is imported using <code>from foo import *</code>. </p>

<p>You can do the import datetime within the function that uses it in module foo:</p>

<pre><code>def foodate():
    import datetime
    print datetime.datetime.now()

def foosay(a):
    print "Foo say: %s" % a
</code></pre>

<p>Now importing foo will not import datetime.</p>

<p><strong>EDIT:</strong> You can also reduce the memory footprint by not importing the whole datetime module, only the methods/functions you need:</p>

<pre><code>from datetime.datetime import now
</code></pre>

python import module visibility