C-style static variables in Python?

Paul Rubin no.email at nospam.invalid
Fri Apr 2 05:32:43 CEST 2010


kj <no.email at please.post> writes:
> 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) { ...


Here are some cheesy ways.

1. Put an attribute onto the function name:

  def foo(x, y, z):
    if foo.first_time:
       foo.mongo = heavy_lifting_at_runtime()
       foo.first_time = False
    ...
  foo.first_time = True

2. Use a mutable keyword parameter:

   def foo(x, y, z, wrapped_mongo=[]):
      if len(wrapped_mongo) == 0:
         wrapped_mongo.append(heavy_lifting_at_runtime())
      mongo = wrapped_mongo[0]
      ...

3. Streamline the first method a little:

    def foo(x, y, z):
       if len(foo.wrapped_mongo == 0):
          foo.wrapped_mongo.append(heavy_lifting_at_runtime())
       mongo = foo.wrapped_mongo[0]      
       ...
   foo.wrapped_mongo = []

All of these of course don't give as good encapsulation as one might
like.



More information about the Python-list mailing list