Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63742

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

From Ned Batchelder <ned@nedbatchelder.com>
Subject Re: Is it better to import python modules inside function or at the top? What are the pros and cons?
Date 2014-01-11 20:49 -0500
References <ccb82f25-c007-4e90-97d9-5108463ed51f@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.5350.1389491356.18130.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Is it better to import python modules inside function or at the top? What are the pros and cons? Sam <lightaiyee@gmail.com> - 2014-01-11 17:28 -0800
  Re: Is it better to import python modules inside function or at the top? What are the pros and cons? Chris Angelico <rosuav@gmail.com> - 2014-01-12 12:48 +1100
  Re: Is it better to import python modules inside function or at the top? What are the pros and cons? Ned Batchelder <ned@nedbatchelder.com> - 2014-01-11 20:49 -0500

csiph-web