title: Are there possible negative consequences to using import inline?
body: <p>I'm working on a Python program that needs to be able to run even if some of the libraries it needs for some features are missing.  (EDIT: I wrote a little code to implement the best suggested solution and it's <a href="https://github.com/rec/echomesh/blob/master/code/python/echomesh/util/Importer.py" rel="nofollow">here</a>, with a doctest <a href="https://github.com/rec/echomesh/blob/master/code/python/echomesh/util/ImporterTest.py" rel="nofollow">here</a>.)</p>
  
  <p>I solved this by putting the import statements for such libraries inline to the functions that use them, rather than at the top of the Python file.  That means that you can load the file perfectly well even if you don't have the library, though of course you'll throw an ImportError if you try to call one of the functions.</p>
  
  <p>This has worked so well that I find myself sometimes doing this for standard library modules as well - but now I'm wondering if I'm incurring some hidden cost by doing so?</p>
  
  <p>Baseline code:</p>
  
  <pre><code>import numpy
  
  def foo(): 
    return numpy.array([])
  
  def bar(): 
    return numpy.array([1, 2, 3])
  </code></pre>
  
  <p>Code with inline imports:</p>
  
  <pre><code>def foo(): 
    import numpy
    return numpy.array([])
  
  def bar(): 
    import numpy
    return numpy.array([1, 2, 3])
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I agree completely about not inlining standard library code - obviously bad.</p>
  
  <p>I now think that the guarded import is the correct solution.</p>
  
  <p>In particular, I did some timing tests on the calls, and while the time difference probably isn't significant for most applications, it is appreciable (fine line, I know!)</p>
  
  <p>In the trivial case</p>
  
  <pre><code>import numpy
  def f():
    return numpy
  </code></pre>
  
  <p>takes about 180ms on my machine for 100,000 repetitions but</p>
  
  <pre><code>def f():
    import numpy
    return numpy
  </code></pre>
  
  <p>takes about 870ms.</p>
  
  <p>Very rough takeaway is that this costs as much as four trivial function calls - noticeable but not significant in most cases.  Still, best to avoid if it costs you nothing to do so.</p>
  
  <p>In experimenting, I also realized another downside to inline imports - it's that these imports go off at an unpredictable time, when the function is called.  In my application, which has real-time elements, this is unacceptable.</p>