473,394 Members | 1,737 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,394 software developers and data experts.

Static Variables in Python?

Is it possible to have a static variable in Python -
a local variable in a function that retains its value.

For example, suppose I have:

def set_bit (bit_index, bit_value):
static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bits [bit_index] = bit_value

print "\tBit Array:"
int i
while (i < len(bits):
print bits[i],
print '\n'
I realize this can be implemented by making bits global, but can
this be done by making it private only internal to set_bit()? I don't
want bits to be reinitialized each time. It must retain the set values
for the next time it is called.
Thanks in advance:
Michael Yanowitz

Jul 31 '06 #1
10 3314
Michael Yanowitz schreef:
Is it possible to have a static variable in Python -
a local variable in a function that retains its value.

For example, suppose I have:

def set_bit (bit_index, bit_value):
static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bits [bit_index] = bit_value

print "\tBit Array:"
int i
while (i < len(bits):
print bits[i],
print '\n'
I realize this can be implemented by making bits global, but can
this be done by making it private only internal to set_bit()? I don't
want bits to be reinitialized each time. It must retain the set values
for the next time it is called.
You could do it by defining static_bits as a keyword parameter with a
default value:
>>def set_bit(bit_index, bit_value, static_bits=[0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0]):
static_bits[bit_index] = bit_value
return static_bits
>>set_bit(2, 1)
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>set_bit(3, 1)
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>set_bit(2, 0)
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

It might be a better idea to use a class for this though:
>>class Bits(object):
def __init__(self):
self.bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def set(self, index, value):
self.bits[index] = value
return self.bits

>>bits = Bits()
bits.set(2, 1)
[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>bits.set(3, 1)
[0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>bits.set(2, 0)
[0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

When using a class, you can have different lists of bits independently
of each other in a program. And you can define other operations on the
bits: you could for example create methods to set or clear all bits at
once. With your approach, set_bit is the only function that has access
to the bits so you can't easily create other operations.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Jul 31 '06 #2

Michael Yanowitz wrote:
Is it possible to have a static variable in Python -
a local variable in a function that retains its value.

For example, suppose I have:

def set_bit (bit_index, bit_value):
static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bits [bit_index] = bit_value

print "\tBit Array:"
int i
while (i < len(bits):
print bits[i],
print '\n'
I realize this can be implemented by making bits global, but can
this be done by making it private only internal to set_bit()? I don't
want bits to be reinitialized each time. It must retain the set values
for the next time it is called.
If you declare bits in set_bit() as "global bits = ...", it will create
it as a global variable without you having to declare it outside of the
function. Just be careful about name conflicts.

Jul 31 '06 #3
tac-tics:
If you declare bits in set_bit() as "global bits = ...", it will create
it as a global variable without you having to declare it outside of the
function. Just be careful about name conflicts.
Are you sure?

def fun():
global x = 10
fun()
print x

Bye,
bearophile

Jul 31 '06 #4
be************@lycos.com wrote:
tac-tics:
>If you declare bits in set_bit() as "global bits = ...", it will create
it as a global variable without you having to declare it outside of the
function. Just be careful about name conflicts.

Are you sure?

def fun():
global x = 10
fun()
print x

Bye,
bearophile
This works for me:
>>def fun():
global x
x = 10

>>fun()
print x
10
>>>
But of course:
>>def fun():
global x = 10

SyntaxError: invalid syntax
>>>
Jul 31 '06 #5
Roel Schroeven a écrit :
Michael Yanowitz schreef:
> Is it possible to have a static variable in Python - a local
variable in a function that retains its value.
(snip)
>
You could do it by defining static_bits as a keyword parameter with a
default value:
(snip)
It might be a better idea to use a class for this though:
(snip)

Last solution being to use a closure:

def make_bits():
bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def set_bit(bit_index, bit_value):
bits[bit_index] = bit_values
def get_bits():
# returns a copy so we don't overwrite
return bits[:]
return set_bit, get_bits

set_bit, get_bits = make_bits()

But the better solution is probably to make it a class.
Jul 31 '06 #6
Michael Yanowitz a écrit :
Is it possible to have a static variable in Python -
a local variable in a function that retains its value.

For example, suppose I have:

def set_bit (bit_index, bit_value):
static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bits [bit_index] = bit_value

print "\tBit Array:"
int i
Syntax error
while (i < len(bits):
print bits[i],
Nice infinite loop...

Python's canonical way to iterate over a sequence is the for loop:
for bit in bits:
print bit,

And FWIW, for what you want to do, you don't even need a loop:
print "\n".join(map(str, bits))
print '\n'
>
I realize this can be implemented by making bits global, but can
this be done by making it private only internal to set_bit()? I don't
want bits to be reinitialized each time. It must retain the set values
for the next time it is called.
While there are some more or less hackish solutions (cf Roel answers and
my answers to it), the usual way to have functions maintaining state is
to define a class and instanciate it. Note that Python's functions are
objects, and that it's possible to write your own callable objects too
if you really want a function call syntax:

class Setbit(object):
def __init__(self):
self._bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
def call(self, index, value):
self._bits[index] = value
def values(self):
return self._bits[:]

set_bit = Setbit()
set_bit(1, 1)
print "".join(map(str, set_bit.values()))

Jul 31 '06 #7

Michael Yanowitz wrote:
Is it possible to have a static variable in Python -
a local variable in a function that retains its value.

For example, suppose I have:

def set_bit (bit_index, bit_value):
static bits = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
bits [bit_index] = bit_value

print "\tBit Array:"
int i
while (i < len(bits):
print bits[i],
print '\n'
I realize this can be implemented by making bits global, but can
this be done by making it private only internal to set_bit()? I don't
want bits to be reinitialized each time. It must retain the set values
for the next time it is called.
Thanks in advance:
Michael Yanowitz
You can do things with function attributes

def foo(x):
foo.static += x
return foo.static
foo.static = 0

If you are going to set function attributes a lot, then you might like
to addd an attriute setter decorator to your toolbox:

def attributeSetter( **kw):
" decorator creator: initialises function attributes"
def func2(func):
" decorator: initialises function attributes"
func.__dict__.update(kw)
return func
return func2

def accumulator(n):
""" return an accumulator function that starts at n
>>x3 = accumulator(3)
x3.acc
3
>>x3(4)
7
>>x3.acc
7
"""
@attributeSetter(acc = n)
def accum(i):
accum.acc+= i
return accum.acc
return accum
- Paddy

Jul 31 '06 #8
But of course:
>
>>def fun():
global x = 10

SyntaxError: invalid syntax
>>>
global x
x = 10

Close enough ^^;

Jul 31 '06 #9
In article <11*********************@p79g2000cwp.googlegroups. com>,
Paddy <pa*******@netscape.netwrote:
Aug 7 '06 #10

Cameron Laird wrote:
In article <11*********************@p79g2000cwp.googlegroups. com>,
Paddy <pa*******@netscape.netwrote:
.
[substantial thread
with many serious
alternatives]
.
.
You can do things with function attributes

def foo(x):
foo.static += x
return foo.static
foo.static = 0
.
.
.
My favorite variation is this:

def accumulator(x):
# On first execution, the attribute is not yet known.
# This technique allows use of accumulator() as a
# function without the "consumer" having to initialize
# it.
if not "static" in dir(accumulator):
accumulator.static = 0
accumulator.static += x
return accumulator.static

print accumulator(3)
print accumulator(5)
Thanks Cameron, I'll accumulate this in my toolbox.

- pad.

Aug 8 '06 #11

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

Similar topics

3
by: Daniel Schüle | last post by:
Hi all I have 2 questions 1) is there a way do declare static variables in a class? I coded this logic in global variable foo_cnt 2) is there a way to see the types of all data/function...
2
by: | last post by:
I've been looking for a way of have static variables in a python class and all I have found is this: class A: static = def f(self): A.static =
8
by: Grzegorz Dostatni | last post by:
I had an idea yesterday. (Yes, I know. Sorry). If we don't need to declare variables as having a certain type, why do we need to import modules into the program? Isn't the "import sys" redundant...
3
by: mudd | last post by:
How do I build Python so that I get static libraries instead of dynamic libraries (e.g. build/lib.solaris-2.8-sun4u-2.3/math.so)? John
4
by: Neil Zanella | last post by:
Hello, I would like to know whether it is possible to define static class methods and data members in Python (similar to the way it can be done in C++ or Java). These do not seem to be mentioned...
9
by: Florian Lindner | last post by:
Hello, does python have static variables? I mean function-local variables that keep their state between invocations of the function. Thanks, Florian
3
by: dmitrey | last post by:
Thank you in advance, Dmitrey
37
by: minkoo.seo | last post by:
Hi. I've got a question on the differences and how to define static and class variables. AFAIK, class methods are the ones which receives the class itself as an argument, while static methods...
15
by: kj | last post by:
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,...
0
by: Luis Zarrabeitia | last post by:
Quoting Joe Strout <joe@strout.net>: I'm sure your credentials are bigger than mine. But he is right. A lot of languages have ditched the "concept" of a static variable on a method (how do you...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.