deleting global namespaces

Thomas Wouters thomas at xs4all.net
Sat Feb 5 15:41:29 CET 2000


On Fri, Feb 04, 2000 at 11:10:05PM +0000, mdvorak at ninell.cz wrote:

> My idea is that each component will sit in
> a module and there will be some functions which
> will take care of starting the module and performing
> clean up upon exit.

> But the problem is there is no way to force Python to
> delete module together with all variables/functions
> which exist in its global namespace - that is
> I cannot perform any clean up. Upon exit I would
> have to go through all global objects and delete
> them explicitly, but I cannot do this, because
> throughout the application one module can be
> started multiple times and each time it has to
> run like it was started for the first time.

There is no guaranteed automatic way to make Python delete something. The
only way to 'delete' something is to remove all references to it, and make
the refcounter (or garbage collector, in Java) delete the object. But it
sounds to me like you are trying to use the wrong tool for the wrong task --
modules only get executed once, upon the first load time. The top level of a
module is intended to run just once in it's lifetime, not every time you
wish to reset the data to the starting point.

To do what you want, either work with functioncalls to reset the module to
its initial state, or just use objects. Using objects is probably the best
method, as it groups data, methods and state in one easy-to-use package ;)

So you can do either:

module.py:
-----
var = SomeState
def reset():
	global var
	var = SomeState

def do_something_with_var():
	...
-----

and manually call reset() when you wish to reset the data, or:

module.py:
-----
class Module:
	def __init__(self):
		self.var = SomeState
	def do_something_with_var(self):
		...
-----

If you then wish to reset to the initial state, just create a new
module.Module object.

Regards,

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list