C-style static variables in Python?
Terry Reedy
tjreedy at udel.edu
Thu Apr 1 19:28:18 EDT 2010
On 4/1/2010 6:34 PM, kj wrote:
>
>
> When coding C I have often found static local variables useful for
> doing once-only run-time initializations. For example:
>
> int foo(int x, int y, int z) {
>
> static int first_time = TRUE;
> static Mongo *mongo;
> if (first_time) {
> mongo = heavy_lifting_at_runtime();
> first_time = FALSE;
> }
>
> return frobnicate(mongo, x, y, z);
Global var or class or closure such as below (obviously untested ;=):
make_foo()
mongo = heavy_lifting_at_runtime();
def _(x,y,z):
return frobnicate(mongo, x, y, z)
return _
foo = make_foo
del make_foo # to make sure it is *never* called again ;
Now you only have foo with a hard-to-access private object and no
first_time checks when you call it.
Terry Jan Reedy
More information about the Python-list
mailing list