On subsequent imports of a module, Python will look to see if it's already loaded and, if it is, will hand you back a reference to it-- the module won't be reloaded. Repeatedly importing a module inside a method will cause a slight performance hit, but one that you would likely never notice.
The bad thing about importing within functions or methods (or anywhere other than at the very top of a module) is that it's hard to tell what a module's dependencies are. You should only do that under rare circumstances. As far as garbage collection, I'm not sure that will happen with modules, since there's a reference in sys.modules. To boil this down to some succint advice: always place imports at the top of a module unless you have a very good reason to place them elsewhere, and don't worry about the performance impact of imports expect in special cases. On Jul 20, 7:07 am, Pavel Skvazh <[email protected]> wrote: > I was going to ask this for ages now. > > For example we've got a controller. > > import os > > class MyController(BaseController): > def do_stuff(): > import os > os.open(...) > > def do_more(): > import os > os.do(...) > > The question being, what's the best practice here for this exactly in > pylons. > When the server is launched, the top level import is done, making it > availible for everyone in the module. > If I'll only import os in the method, won't it cause more work to > import it every single time the method is run? > > On the other hand, won't it probably be more efficient to import only > for the time, the method that actually uses this import works and then > (i believe) garbage collection will free the memory until the next > time it'll be used. > > I do understand that this question is only loosely related to pylons, > but I'm new to python and don't know know where I can find this low > level behaivior explained, especially in relation to Pylons and WSGI > apps. > If there're sources out their, I'd really appreciate if you'll point > me their. I'd love to rtfm :) > > Thanks a lot! --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "pylons-discuss" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/pylons-discuss?hl=en -~----------~----~----~----~------~----~------~--~---
