[mod_python] namespaces in publisher

Nicolas Lehuen nicolas.lehuen at gmail.com
Thu Jan 27 02:30:51 EST 2005


On Wed, 26 Jan 2005 22:42:14 -0800, snacktime <snacktime at gmail.com> wrote:
> Do variables defined in the main function called by publisher persist
> after the request?
> 
> Also, how do you destroy an instance of a class?  Do you just assign
> it a value of None?  And if you call a class from within a function,
> when you leave the function the class instance is destroyed unless the
> function returns the instance to the caller correct?
> 
> Chris
> _______________________________________________
> Mod_python mailing list
> Mod_python at modpython.org
> http://mailman.modpython.org/mailman/listinfo/mod_python
> 

Hi,

Those are Python-specific questions, not mod_python questions. You
have to learn the difference between global and local variables, or
more precisely how Python handle its namespaces. Do not hesitate to
read the Python Tutorial (or any other Python tutorial) :

http://docs.python.org/tut/tut.html

I'll try to answer your questions, though :

1) No, variables defined in functions are not persisted. Those
variables are only defined in a scope which is dynamically created
each time the function is called. When the function exits, the scope
is destroyed, so next time the function will be called, it will be in
a news scope, with new variables.

2) You can't explicitely destroy objects in Python. Python, like many
other languages now, handles memory automatically. Once an object is
not referenced anywhere in a program, it can be safely removed from
memory. All you can do in Python is to dereference an object with the
'del' keyword (have a look at the documentation), but generally you
don't have to worry about this.

3) Like I wrote in 1), any object which is created is initially
referenced in the local scope of the function. If you do not return
this object, it will be dereferenced at the end of the call since the
local scope will be destructed. If you return the object, when the
local scope is destructed, the object will not be destructed since it
will be referenced somewhere else (in the local scope of the calling
function).

What you must understand is that "it just works". You don't have to
worry about object allocation and destruction. Objects are
automatically destroyed when it is safe. The only thing you have to
understand is how scope are created and destroyed (which is a totally
different mechanism than object allocation/destruction) ; fortunately
it's nearly the same scoping rule as in other languages.

Regards,
Nicolas


More information about the Mod_python mailing list