It depends.
Most of the time you want it at the top. This isn't because of PEP-8 (anyone who cites PEP-8 as a justification in and of itself misunderstands design rationale), but for the practical reasons underlying PEP-8's recommendation:
If you put imports inside functions, and those imports aren't available, it's likely to hide problems. Instead of throwing an exception when your module is imported, it'll only happen when some function is called. It's also a bit less efficient, pulling in the name on demand, though that's usually minor.
However, this isn't a hard rule. You may want to import on demand with certain types of feature detection. For example,
def decode(s):
try:
import cjson
return cjson.decode(s)
except ImportError:
import simplejson
return simplejson.loads(s)
print decode('[1,2,3]')
or similarly,
try:
import cjson
def decode(s):
return cjson.decode(s)
except ImportError:
import simplejson
def decode(s):
return simplejson.loads(s)
print decode('[1,2,3]')
You may also specifically want to support certain method calls only if a module is available, without causing the whole module to depend on it.