Your second way of importing is probably better if you only occasionally need the module. Especially if the module does some heavy initialization works.
What import
does is calling the builtin function __import__(name)
, see details.
if True:
import os
is equivalent to:
if True:
os = __import__('os')
And the best part is that the result of __import__
is cached, so you don't need to worry that by calling it multiple times you would end up parsing the module multiple times.
EDIT: The other answers do have good points, that it is cleaner to have it on top and if the condition is ever evaluated to True, you end up paying the price sooner or later.
I guess it depends on your specific use case too. For example, often times we want to choose one of the implementations of a particular module, we do:
try:
import simplejson as json
except ImportError:
import json