Does the position of python import statements affect performance
<p>I was wondering if the position of import statements in a python program has any affect on performance. For example if I have this</p>

<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib2
import json
import requests
from flask import render_template, request, Flask, session, Markup, jsonify, send_from_directory
from wit import Wit
from os import urandom
from datetime import datetime
from uuid import uuid1
from random import choice
from FAAWrapper import FAA_API
from bs4 import BeautifulSoup



def function1():
    from OpenSSL import SSL
    from fuzzywuzzy import process
    continue

def function2():
    continue
</code></pre>

<p>Would performance be adversely affected by calling function1() being that function1 contains import statements? Should all of my imports be placed at the top or does the import only happen once the first time the function is called?  </p>

<p>Importing does <em>two</em> things:</p>

<ol>
<li><p>If there is no <code>sys.modules</code> entry yet, find and load the module; if Python code, executing the top-level code produces the namespace for that module. This step is skipped if the module has already been loaded.</p></li>
<li><p>Bind a name in the current namespace to the imported object. <code>import foo</code> sets the name <code>foo</code>. <code>from foo import bar</code> binds the name <code>bar</code>, etc.</p></li>
</ol>

<p>Now, <em>local</em> names (in functions) have a speed advantage in that Python stores these in a C array and uses indices in the bytecode to reference them. <em>Global</em> names are stored in a dictionary and have a small hashing overhead each time you do a lookup.</p>

<p>So importing something into a function results in a local, accessing which is faster than referencing a global. This is offset by the hash lookup in <code>sys.modules</code> each time your function runs so only if the name is used in a loop would you notice this. </p>

<p>However, you should only make such optimisations if that code is used on a critical path, in code that is executed a lot. You are paying a maintenance price by hiding imports in functions, and that cost needs to be weighed against the (marginal) speed benefits.</p>

python