473,385 Members | 1,610 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Static variables

Hello,
does python have static variables? I mean function-local variables that keep
their state between invocations of the function.

Thanks,

Florian
Jan 24 '07 #1
9 2371
On 2007-01-24, Florian Lindner <Fl*************@xgm.dewrote:
does python have static variables? I mean function-local
variables that keep their state between invocations of the
function.
Yup. Here's a nice way. I don't how recent your Python must be
to support this, though.
>>def foo(x):
.... print foo.static_n, x
.... foo.static_n += 1
....
>>foo.static_n = 0
for i in range(5):
.... foo("?")
....
0 ?
1 ?
2 ?
3 ?
4 ?

If you need to use an earlier version, then a "boxed" value
stored as a keyword parameter will also work.
>>def foo(x, s=[0]):
.... print s[0], x
.... s[0] += 1
....
>>for i in range(5):
.... foo("!")
....
0 !
1 !
2 !
3 !
4 !

The latter is not as nice, since your "static" variable is easy
to clobber by passing something into the function.

--
Neil Cerutti
Jan 24 '07 #2
Florian Lindner a écrit :
Hello,
does python have static variables? I mean function-local variables that keep
their state between invocations of the function.
Not directly. But there are ways to have similar behaviour:

1/ the mutable default argument hack:

def fun(arg, _hidden_state=[0]):
_hidden_state[0] += arg
return _hidden_static[0] * 2

2/ using OO:

class Fun(object):
def __init__(self, static=0):
self._state = static
def __call__(self, arg):
self._state += arg
return self._state * 2

fun = Fun()
HTH
Jan 24 '07 #3
Neil Cerutti a écrit :
On 2007-01-24, Florian Lindner <Fl*************@xgm.dewrote:
>>does python have static variables? I mean function-local
variables that keep their state between invocations of the
function.


Yup. Here's a nice way. I don't how recent your Python must be
to support this, though.

>>>>def foo(x):

... print foo.static_n, x
... foo.static_n += 1
...
>>>>foo.static_n = 0
Yup,I had forgotten this one. FWIW, it's an old trick.

There's also the closure solution:

def make_foo(start_at=0):
static = [start_at]
def foo(x):
print static[0], x
static[0] += 1
return foo

foo = make_foo()

And this let you share state between functions:

def make_counter(start_at=0, step=1):
count = [start_at]
def inc():
count[0] += step
return count[0]
def reset():
count[0] = [start_at]
return count[0]
def peek():
return count[0]

return inc, reset, peek

foo, bar, baaz = make_counter(42, -1)
print baaz()
for x in range(5):
print foo()
print bar()
print baaz()

Jan 24 '07 #4
On Wed, 24 Jan 2007 21:48:38 +0100, Florian Lindner wrote:
Hello,
does python have static variables? I mean function-local variables that keep
their state between invocations of the function.
There are two ways of doing that (that I know of).

The simplest method is by having a mutable default argument. Here's an
example:

def foo(x, _history=[]):
print _history, x
_history.append(x)
>>foo(2)
[] 2
>>foo(3)
[2] 3
>>foo(5)
[2, 3] 5
Another method is to add an attribute to the function after you've created
it:

def foo(x):
print foo.last, x
foo.last = x

foo.last = None

>>foo(3)
None 3
>>foo(6)
3 6
>>foo(2)
6 2
But the most powerful method is using generators, which remember their
entire internal state between calls. Here's a simple example, one that
returns the integers 0, 1, 3, 6, 10, ...

def number_series():
increment = 1
n = 0
while True:
yield n # instead of return
n += increment
increment += 1
Notice that in this case there is no exit to the function: it loops
forever because the series goes on for ever. If you want to exit the
generator, just use a plain return statement (don't return anything), or
just exit the loop and fall off the end of the function.

This is how we might use it:

Create an iterator object from the generator function, and print the first
six values:
>>gen = number_series()
for i in range(6): print gen.next()
....
0
1
3
6
10
15

Sum the values from the current point up to 100:
>>s = 0
n = gen.next()
n
21
>>for x in gen:
.... if x >= 100:
.... break
.... n += x
....
>>n
420

Reset the iterator to the start:
>>gen = number_series()
For generators that terminate, you can get all the values in one go with
this:

everything = list(gen) # or everything = list(number_series())

but don't try this on my example, because it doesn't terminate!
--
Steven.

Jan 24 '07 #5
Florian Lindner wrote:
Hello,
does python have static variables? I mean function-local variables that keep
their state between invocations of the function.

Thanks,

Florian
Nope. Not really.

In new versions of Python, functions and methods can have attributes
that can be used like function level static variables.

However, I usually use module level attributes for such things.

Gary Herron

Jan 24 '07 #6
Florian Lindner wrote:
Hello,
does python have static variables? I mean function-local variables that keep
their state between invocations of the function.

Thanks,

Florian
Nope. Not really.

In new versions of Python, functions and methods can have attributes
that can be used like function level static variables.

However, I usually use module level attributes for such things.

Gary Herron

Jan 24 '07 #7
Bruno Desthuilliers:
And this let you share state between functions:

def make_counter(start_at=0, step=1):
count = [start_at]
def inc():
count[0] += step
return count[0]
def reset():
count[0] = [start_at]
return count[0]
def peek():
return count[0]

return inc, reset, peek

foo, bar, baaz = make_counter(42, -1)
print baaz()
for x in range(5):
print foo()
print bar()
print baaz()
An interesting solution, I have never created such grouped clorures. I
don't know if this solution is better than a class with some class
attributes plus some class methods...

Bye,
bearophile

Jan 25 '07 #8
be************@lycos.com writes:
An interesting solution, I have never created such grouped closures. I
don't know if this solution is better than a class with some class
attributes plus some class methods...
It's a Scheme idiom but I think once the object gets this complicated,
it's probably more Pythonic to use a class.
Jan 25 '07 #9
be************@lycos.com a écrit :
Bruno Desthuilliers:
>And this let you share state between functions:

def make_counter(start_at=0, step=1):
count = [start_at]
def inc():
count[0] += step
return count[0]
def reset():
count[0] = [start_at]
return count[0]
def peek():
return count[0]

return inc, reset, peek

foo, bar, baaz = make_counter(42, -1)
print baaz()
for x in range(5):
print foo()
print bar()
print baaz()

An interesting solution, I have never created such grouped clorures.
It's a common idiom in some functional languages.
I
don't know if this solution is better than a class with some class
attributes plus some class methods...
It's somewhat equivalent, but in Python, I'd surely use a class instead !-)
Jan 25 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: BCC | last post by:
Hi, I have a class with several member variables that should be initialized according to user input before an object is instantiated. Using a static variable is required here. But, I would...
2
by: katekukku | last post by:
HI, Could anyone please tell me what are static variables and what exactly are there features. I am a little bit confused. Thank You
115
by: Mark Shelor | last post by:
I've encountered a troublesome inconsistency in the C-language Perl extension I've written for CPAN (Digest::SHA). The problem involves the use of a static array within a performance-critical...
4
by: Wayne | last post by:
Hi, I'm new to .NET and have a question about the use of static variables vs. session variables in a web form in C#. Instead of using a session variable to hold a string to persist during...
4
by: Bryan Green | last post by:
So I'm working on a project for a C# class I'm taking, where I need to keep some running totals via static variables. I need three classes for three different types of objects. The base class and...
25
by: Sahil Malik [MVP] | last post by:
So here's a rather simple question. Say in an ASP.NET application, I wish to share common constants as static variables in global.asax (I know there's web.config bla bla .. but lets just say I...
8
by: Simone Chiaretta | last post by:
I've a very strange behaveour related to a website we built: from times to times, something should happen on the server, and all static variables inside the web application, both defined inside aspx...
5
by: Jesper Schmidt | last post by:
When does CLR performs initialization of static variables in a class library? (1) when the class library is loaded (2) when a static variable is first referenced (3) when... It seems that...
9
by: CDMAPoster | last post by:
About a year ago there was a thread about the use of global variables in A97: http://groups.google.com/group/comp.databases.ms-access/browse_frm/thread/fedc837a5aeb6157 Best Practices by Kang...
16
by: RB | last post by:
Hi clever people :-) I've noticed a lot of people stating not to use static variables with ASP.NET, and, as I understand it, the reason is because the variable is shared across user sessions -...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.