Executing global code

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Jan 15 17:43:40 EST 2009


On Thu, 15 Jan 2009 17:50:54 +0100, Peter Otten wrote:

> Jakub Debski wrote:
> 
>> Is it possible to execute global code (module-level code) more than
>> once keeping the state of global variables? This means no reload() and
>> no moving the code to a function.
> 
> You have a module containing e. g. these two statements
> 
> x = 42
> x += 1
> 
> and want to rerun it with the effect of x becoming 44? That is not
> possible 

Unless you move the value of x into external storage. Untested:


try:
    f = open('mystorage.txt', 'r')
except IOError:
    x = 42
else:
    x = int(f.read())
x += 1    


Naturally the above is not bulletproof enough for production use.

I'm curious why the Original Poster wants to do such a thing, and 
particularly the prohibition against moving code into a function.



-- 
Steven



More information about the Python-list mailing list