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

Chris Angelico rosuav at gmail.com
Sat Jan 11 20:48:10 EST 2014


On Sun, Jan 12, 2014 at 12:28 PM, Sam <lightaiyee at gmail.com> 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?

Most of the work of importing is still going to be done only once
(after that, the import just grabs a cached reference to the same
module). It's normally clearer to import at the top of the module,
especially if you have multiple functions calling on the same module,
but there are two other concerns:

1) If the module can't be found, would you rather know as soon as your
module is loaded, or is it better to load your module without it and
then fail only when that function is called?

2) If the module takes a long time to load, would you rather pay that
cost as soon as your module is loaded, or on the first use of the
function that needs it?

ChrisA



More information about the Python-list mailing list