473,555 Members | 2,333 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static variables in Python?

kj


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.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
Jul 29 '08 #1
15 2951
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.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn

First names in Python are just that, names that point to objects. Those objects
can contain any type of information including other objects. They are NOT
buckets where things are stored.

1) Names (variables in Perl/C) defined within a Python function are placed in
its local namespace. They are not visible in the global namespace.

2) Yes you can have a local name point to a global. This is often used in
classes with attributes because looking up local is somewhat quicker than
looking up the class attribute.

def foo():
x = expensive_call
return do_stuff_with(x ())

In this particular case it doesn't really help.

It would be more useful in something like:

class foo(object):
def __init__(self, initialvalue = 0)
self.currentval ue = initialvalue

def longloopingmeth od(self, listtosum):
currentvalue = self.currentval ue
for v in listtosum:
currentvalue += v
BTW - There are BETTER ways to sum a list, so this is just an example.

-Larry
Jul 29 '08 #2
kj
In <w8************ *************** ***@comcast.com Larry Bates <la*********@we bsafe.com`write s:
>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.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn
>First names in Python are just that, names that point to objects. Those objects
can contain any type of information including other objects. They are NOT
buckets where things are stored.
>1) Names (variables in Perl/C) defined within a Python function are placed in
its local namespace. They are not visible in the global namespace.
>2) Yes you can have a local name point to a global. This is often used in
classes with attributes because looking up local is somewhat quicker than
looking up the class attribute.
>def foo():
x = expensive_call
return do_stuff_with(x ())
Maybe I'm missing your point, the goal is to have a "runtime
constant" associated with the function. In the your definition of
foo, expensive_call gets called every time that foo gets called;
this is what I'm trying to avoid!

Maybe it's easier to see what I mean with javascript:

function foo() {
if (foo.x === undefined) foo.x = expensive_call( );
return do_stuff_with(f oo.x);
}

Here, expensive_call is called only once (assuming it never returns
undefined).

OK, I guess that in Python the only way to do what I want to do is
with objects...

kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
Jul 29 '08 #3
kj wrote:
In <w8************ *************** ***@comcast.com Larry Bates <la*********@we bsafe.com`write s:
>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.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}
};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn

>First names in Python are just that, names that point to objects. Those objects
can contain any type of information including other objects. They are NOT
buckets where things are stored.
>1) Names (variables in Perl/C) defined within a Python function are placed in
its local namespace. They are not visible in the global namespace.
>2) Yes you can have a local name point to a global. This is often used in
classes with attributes because looking up local is somewhat quicker than
looking up the class attribute.
>def foo():
x = expensive_call
return do_stuff_with(x ())

Maybe I'm missing your point, the goal is to have a "runtime
constant" associated with the function. In the your definition of
foo, expensive_call gets called every time that foo gets called;
this is what I'm trying to avoid!

Maybe it's easier to see what I mean with javascript:

function foo() {
if (foo.x === undefined) foo.x = expensive_call( );
return do_stuff_with(f oo.x);
}

Here, expensive_call is called only once (assuming it never returns
undefined).

OK, I guess that in Python the only way to do what I want to do is
with objects...

kynn
You might consider using a singleton class.

Colin W.
Jul 29 '08 #4
kj:
OK, I guess that in Python the only way to do what I want to do
is with objects...
There are other ways, like assigning the value out of the function,
because Python functions too are objects:

def iamslow():
return 100
def foo(x):
return x + foo.y
foo.y = iamslow() # slow computation
print foo(1)
print foo(2)

Output is:
101
102

Another way is this, a bit more clean, with the same output:

def iamslow():
return 100
def foo(x, y=iamslow()):
return x + y
print foo(1)
print foo(2)

But I suggest you to use a class in this situation, it's often the way
that will keep your code more bug-free, and more readable by near-
casual readers too. Python philosophy asks you to write readable code
instead of clever code when possible, this is a difference from Perl,
I presume.

Bye,
bearophile
Jul 29 '08 #5
kj <so***@987jk.co m.invalidwrites :
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
Jul 29 '08 #6
On Tue, 29 Jul 2008 21:31:01 +0000, kj wrote:
In <w8************ *************** ***@comcast.com Larry Bates <la*********@we bsafe.com`write s:

[snip]

Maybe it's easier to see what I mean with javascript:

function foo() {
if (foo.x === undefined) foo.x = expensive_call( );
return do_stuff_with(f oo.x);
}
def foo():
if not hasattr(foo, 'x'): foo.x = expensive_call( )
return do_stuff_with(f oo.x)

or, maybe just define foo in two steps:

def foo():
return do_stuff_with(f oo.x)

foo.x = expensive_call( )
Jul 30 '08 #7
On Jul 29, 1:40 pm, kj <so...@987jk.co m.invalidwrote:
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.

For example, in Perl one can define a function foo like this

*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}

};

In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.

Is there an equivalent in Python?

Thanks!

kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.
If the constant parameters are really only needed in one particular
function, you can use default function arguments. An added benefit is
that you can override them with another value if necessary.

def fun(x, y, parameter1=0, parameter2=1):
...
Jul 30 '08 #8
be************@ lycos.com wrote:
kj:
>OK, I guess that in Python the only way to do what I want to do
is with objects...

There are other ways, like assigning the value out of the function,
because Python functions too are objects:
....
But I suggest you to use a class in this situation, it's often the way
that will keep your code more bug-free, and more readable by near-
casual readers too. Python philosophy asks you to write readable code
instead of clever code when possible, this is a difference from Perl,
I presume.

Bye,
bearophile
Here's a solution using decorators, I like it, but I'm biased:

def staticAttrs(**k wds):
"""
Adds attributes to a function, akin to c-style
"static" variables
"""

def _decorator(fcn) :
for k in kwds:
setattr(fcn, k, kwds[k])
return fcn
return _decorator

@staticAttrs(n= 0)
def rememberCalls() :
"""
>>rememberCalls ()
0
>>rememberCalls ()
1
>>rememberCalls ()
2
"""
print rememberCalls.n
rememberCalls.n += 1

~Scott
Jul 30 '08 #9
On Jul 29, 6:33 pm, "Russ P." <Russ.Paie...@g mail.comwrote:
On Jul 29, 1:40 pm, kj <so...@987jk.co m.invalidwrote:
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.
For example, in Perl one can define a function foo like this
*foo = do {
my $x = expensive_call( );
sub {
return do_stuff_with( $x, @_ );
}
};
In this case, foo is defined by assigning to it a closure that has
an associated variable, $x, in its scope.
Is there an equivalent in Python?
Thanks!
kynn
--
NOTE: In my address everything before the first period is backwards;
and the last period, and everything after it, should be discarded.

If the constant parameters are really only needed in one particular
function, you can use default function arguments. An added benefit is
that you can override them with another value if necessary.

def fun(x, y, parameter1=0, parameter2=1):
...
I should add that the parameters need not be literal numbers. They can
be computed values as well. They will be computed only once, on the
first pass through the function definition, which I presume is exactly
what you want.

I think this is the simplest solution to the problem you posed.
Jul 30 '08 #10

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

Similar topics

3
1631
by: Daniel Schle | 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 members of a class? dir(cls) returns a list of strings (of members) so it's logical that type(tmp.i) fails ...
2
1787
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
1811
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 if all I want is to call "sys.setrecursionlimit(5000)" ? Why couldn't we just try loading the module of a name "sys" to see if it exists and re-try...
3
7277
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
8005
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 in "Learning Python" by Mark Lutz and David Ascher. It seems like they are a relatively new feature... It seems to me that any truly OO programming...
9
2377
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
2910
by: dmitrey | last post by:
Thank you in advance, Dmitrey
37
5437
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 are the one which runs statically with the defining class. Hence, my understanding is that static variables must be bound to the class defining the...
0
3978
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 parse that sentence, btw?) in favour of using encapsulation. Of the top of my head, there is Java, C# and Python, and I think even PHP and Perl....
0
7547
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8060
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7904
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6176
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5452
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5171
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3575
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2037
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.