static variables in Python?

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Jul 29 19:27:00 EDT 2008


kj <socyl at 987jk.com.invalid> writes:

> Is there a way to mimic C's static variables in Python? Or something
> like it?

A "static variable" in C is one that has access limited to the scope
in which it is declared.

Python approaches the same issue through namespaces: a name binding
made at a class or module level is accessible only via specification
of the class or module namespace.

> 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.

Python functions have local name bindings by default
<URL:http://www.python.org/doc/current/ref/naming.html>.

Python doesn't have "variables" in the sense of boxes containing
values, so it doesn't have "constants" in the sense of boxes that
don't change. Instead, Python has names bound to objects like sticky
notes. A name can later be re-bound to some other object.

What use case are you trying to address? It seems that the normal use
of local function names and class attributes would serve your
described requirements.

-- 
 \     “It is hard to believe that a man is telling the truth when you |
  `\      know that you would lie if you were in his place.” —Henry L. |
_o__)                                                          Mencken |
Ben Finney



More information about the Python-list mailing list