Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have something like Perl 5.10's "state" variables?

Tags:

python

perl

In Perl 5.10, I can say:

sub foo () {
  state $x = 1;
  say $x++;
}

foo();
foo();
foo();

...and it will print out:

1
2
3

Does Python have something like this?

like image 897
mike Avatar asked Mar 03 '09 00:03

mike


People also ask

What is state Perl?

State Variables via state() in Perl There is another type of lexical variable in Perl, which is similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.

What are state variables programming?

Variables in programming refer to storage location that can contain values. These values can be changed during runtime. The variable can be used at multiple places within code and they will all refer to the value stored within it. Solidity provides two types of variable—state and memory variables.


2 Answers

A class may be a better fit here (and is usually a better fit for anything involving "state"):

class Stateful(object):

    def __init__(self):
        self.state_var = 0

    def __call__(self):
        self.state_var = self.state_var + 1
        print self.state_var

foo = Stateful()
foo()
foo()
like image 199
Ali Afshar Avatar answered Oct 12 '22 13:10

Ali Afshar


The closest parallel is probably to attach values to the function itself.

def foo():
    foo.bar = foo.bar + 1

foo.bar = 0

foo()
foo()
foo()

print foo.bar # prints 3
like image 24
Kenan Banks Avatar answered Oct 12 '22 12:10

Kenan Banks