Is it better to import python modules inside function or at the top? What are the pros and cons?

Ned Batchelder ned at nedbatchelder.com
Sat Jan 11 20:49:02 EST 2014


On 1/11/14 8:28 PM, Sam wrote:
> I have python modules which are used only in specific functions and the functions are not called all the time. Is it better to import the function inside the function only or is it a better practice to always import all modules at the top of the script? If I import the module inside the function, will it cause a big performance hit because of the import module action that gets to be called every time the function is called?
>
> What are the pros and cons of each approach?
>

Unless there's a good reason, you should import all the modules at the 
top of the file.

Reasons to import in a function:

1) if a function is only sometimes called, and the import is expensive.

2) if a function is only sometimes called, and needs a dependency that 
not all users of your package need.  For example, your library has both 
Flask and Django helper functions, and only Django users call the Django 
function, etc.

3) if you have a circular import, though that can often be fixed in 
better ways.

Note that the cost of imports is only incurred at the first import, so 
you don't have to worry about the import statement executing each time 
your function is called.  After the first import, the cost is about the 
same as a dict lookup (very fast).

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list