Executing global code

MRAB google at mrabarnett.plus.com
Thu Jan 15 18:13:53 EST 2009


Steven D'Aprano wrote:
 > 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.
 >
Perhaps there are functions which contain 'global'. Anyway, the solution
has already been given, namely put it inside a loop, unless there's soem
reason why that's not possible.



More information about the Python-list mailing list