On Mon, Jul 20, 2009 at 07:07:08AM -0700, Pavel Skvazh 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.

PEP-8: imports at top level
http://www.python.org/dev/peps/pep-0008/

> When the server is launched, the top level import is done, making it
> availible for everyone in the module.

I think the import of a controller is not done eagerly; controllers are
imported when the first request is routed to a particular controller.

> 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?

Yes, but is 1 ms of extra work really that important?

  m...@platonas:~ $ python -m timeit 'import os'
  1000000 loops, best of 3: 0.972 usec per loop

> 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.

No; once a module is imported it stays in memory.  The reference from
sys.modules[module_name] keeps it alive.  You can forcefully unload it
with del sys.modules['os'], but I don't think the memory savings (if
any) will be worth the trouble.

Always measure when optimizing.  Never make assumptions.

> 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 :)

This presentation is very good for understanding the low-level behaviour
of Python: http://video.google.com/videoplay?docid=7760178035196894549

I don't recall if it dives into the import mechanism and garbage
collection; it's been a while since I watched it.

Cheers!
Marius Gedminas
-- 
Ways in which you can avoid starting a flame war on a Debian mailing list.
The subtle:

 * Write in your TODO list that you definitely need to reply to that mail

        -- Enrico Zini

Attachment: signature.asc
Description: Digital signature

Reply via email to