Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #63741
| References | <ccb82f25-c007-4e90-97d9-5108463ed51f@googlegroups.com> |
|---|---|
| Date | 2014-01-12 12:48 +1100 |
| Subject | Re: Is it better to import python modules inside function or at the top? What are the pros and cons? |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.5349.1389491293.18130.python-list@python.org> (permalink) |
On Sun, Jan 12, 2014 at 12:28 PM, Sam <lightaiyee@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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