Question about object lifetime and access

Dave Angel davea at davea.name
Wed Jan 15 10:11:42 EST 2014


 Asaf Las <roegltd at gmail.com> Wrote in message:
> Hi community 
> 
Welcome.

> 
> Multithreading will be enabled in uwsgi and 'p' will be used for read only.
> 
> Questions are:
> - what is the lifetime for global object (p in this example). 

The name will be visible in this module until the application
 shuts down or till you use del.

> - will the p always have value it got during module loading

The (str) object that you bind to it will survive till you del or
 reassign p.  Reassignment can happen with a simple assignment
 statement or via an 'as' clause. The value of such a str object
 will never change because it's an immutable type.

Convention is to use names that are all uppercase.  And long,
 descriptive names are preferred over one-letter names, especially
 for long-lived ones. Don't worry, long names do not take longer.
 


> - if new thread will be created will p be accessible to it

It is accessible to all threads in the same process.

It is also available to other modules via the import mechanism. 
 But watch out for circular imports, which frequently cause bugs.
 

> - if p is accessible to new thread will new thread initialize p value again?

Module level code runs only once per process. 

> - is it guaranteed to have valid p content (set to "module is loaded") whenever application() function is called.

Except with circular imports.

> - under what condition p is cleaned by gc.

Names are never garbage collected.  See above for objects. 
> 
> The rationale behind these question is to avoid object creation within application() whose content is same and do not change between requests calling application() function and thus to reduce script response time. 
> 

Highly unlikely to matter, and it might slow down a program
 slightly rather than speed it up slightly. Get your program
 readable so you have a chance of catching bugs, pick your
 algorithms reasonably,  and if it's not fast enough, measure, 
 don't guess.


> Thanks in advance!
> 
> 
> 
> 
> 


-- 
DaveA



----Android NewsGroup Reader----
http://www.piaohong.tk/newsgroup




More information about the Python-list mailing list