Question about object lifetime and access

Asaf Las roegltd at gmail.com
Wed Jan 15 08:14:59 EST 2014


Thanks a lot for detailed answer! 

i plan to assign object to name only when module loads, that means outside of function or class method. Then object will be accessed from functions only for read purpose. 

I have read somewhere that global objects are referenced from module namespace will never have reference count down to 0 even if they are not referenced from functions or class methods. Is this true? Does it mean that global objects are destroyed when interpreter exits or thread where it runs is terminated?


On Wednesday, January 15, 2014 2:13:56 PM UTC+2, Asaf Las wrote:
> Hi community 
> 
> 
> 
> i am beginner in Python and have possibly silly questions i could not figure out answers for. 
> 
> 
> 
> Below is the test application working with uwsgi to test json-rpc.
> 
> ------------------------------------------------------------------------
> 
> from multiprocessing import Process
> 
> from werkzeug.wrappers import Request, Response
> 
> from werkzeug.serving import run_simple
> 
> 
> 
> from jsonrpc import JSONRPCResponseManager, dispatcher
> 
> 
> 
> p = "module is loaded"   <------ (3)
> 
> print(p)
> 
> print(id(p))
> 
> 
> 
> @Request.application
> 
> def application(request):
> 
>     print("server started")
> 
>     
> 
>     print(id(p))
> 
>     
> 
>     # Dispatcher is dictionary {<method_name>: callable}
> 
>     dispatcher["echo"] = lambda s: s                   <---- (1)
> 
>     dispatcher["add"] = lambda a, b: a + b             <---- (2)
> 
>     
> 
>     print("request data ==> ", request.data)
> 
>     response = JSONRPCResponseManager.handle(request.data, dispatcher)
> 
>     return Response(response.json, mimetype='application/json')
> 
> ------------------------------------------------------------------------
> 
> 
> 
> As program will grow new rpc method dispatchers will be added so there is idea to reduce initialization code at steps 1 and 2 by making them global objects created at module loading, like string p at step 3.
> 
> 
> 
> 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). 
> 
> - will the p always have value it got during module loading
> 
> - if new thread will be created will p be accessible to it
> 
> - if p is accessible to new thread will new thread initialize p value again?
> 
> - is it guaranteed to have valid p content (set to "module is loaded") whenever application() function is called.
> 
> - under what condition p is cleaned by gc.
> 
> 
> 
> 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. 
> 
> 
> 
> Thanks in advance!




More information about the Python-list mailing list