static variables in Python?

Stephan Schulz schulz at sunbroy2.informatik.tu-muenchen.de
Wed Oct 22 12:05:19 EDT 2008


In article <g6nv84$5pv$1 at reader1.panix.com>, kj wrote:
>
>
>Yet another noob question...
>
>Is there a way to mimic C's static variables in Python?  Or something
>like it?  The idea is to equip a given function with a set of
>constants that belong only to it, so as not to clutter the global
>namespace with variables that are not needed elsewhere.

I know I'm coming late to the discussion, but the most natural way for
me would be to simulate the function via a callable object:


class hidden(object):
   def __init__(self):
      self.static_var = 0

   def __call__(self):
      self.static_var+=1
      return self.static_var

fun_with_state = hidden()


>>> fun_with_state()
1
>>> fun_with_state()
2
>>> fun_with_state()
3
>>> fun_with_state()
4

Bye,

    Stephan

-- 
-------------------------- It can be done! ---------------------------------
       Please email me as schulz at eprover.org (Stephan Schulz)
----------------------------------------------------------------------------



More information about the Python-list mailing list