I believe the following "static" command would be useful in Python.
def foo():
static i = [10, 11]
static firstcall = True
if firstcall:
print "First pass"
firstcall = False
i[0] += 1
print i[0]
foo()
foo()
This would output:
First pass
11
12
Just like in C, the variables i and firstcall are only assigned the
first time foo() is called. To get this effect currently, one could
use default arguments or wrapping the whole thing in a class. Both of
these solutions seem like hacks, the above method IMO is more
Pythonic. :)
I have a feeling this has been discussed before, but I can't find
anything on it. Thanks,
--Nick 10 1660
Nick Jacobson wrote: I believe the following "static" command would be useful in Python.
[snip] Just like in C, the variables i and firstcall are only assigned the first time foo() is called. To get this effect currently, one could use default arguments or wrapping the whole thing in a class. Both of these solutions seem like hacks, the above method IMO is more Pythonic. :)
I'm not sure how to interpret the smiley, but I'll take it
you weren't actually joking...
Why do you call using OO ("wrapping it in a class", as you say)
a "hack"? Generally speaking, using objects to contain state
information such as this is exactly what most people would call
the cleanest, best approach.
class HasState:
def __init__(self):
self.firstCall = True
self.i = [10, 11]
def foo(self):
if self.firstCall:
print "First pass"
self.firstCall = False
self.i[0] += 1
print self.i[0]
obj = HasState()
obj.foo()
obj.foo()
Now, without arguing that it has 11 lines instead of 8 to do the
same thing (because then I'd just point out that this was a contrived
example anyway, and that it is more easily extended, and more obvious
what was going on, etc. :-) ), can you describe why you call this is
a "hack"?
-Peter
Peter Hansen wrote: Nick Jacobson wrote:
I believe the following "static" command would be useful in Python.
I do not ! Static variable are like global... [snip]
Just like in C, the variables i and firstcall are only assigned the first time foo() is called. To get this effect currently, one could use default arguments or wrapping the whole thing in a class. Both of these solutions seem like hacks, the above method IMO is more Pythonic. :)
or use global with carefully choosed name...
class HasState: def __init__(self): self.firstCall = True self.i = [10, 11]
def foo(self): if self.firstCall: print "First pass" self.firstCall = False self.i[0] += 1 print self.i[0]
obj = HasState() obj.foo() obj.foo()
Like this solution because most of the timethis is not really static
variable that we want but a per context "static" variable.
Anyway, if this is really static variable that you want,
what about this : 8-) i = [10 ,11] firstcall = True
def foo():
.... global i
.... global firstcall
.... if firstcall:
.... print "First pass"
.... firstcall = False
.... i[0] += 1
.... print i[0]
.... foo()
First pass
11 foo()
12
--
Yermat
"Nick Jacobson" <ni***********@yahoo.com> wrote in message news:f8**************************@posting.google.c om...
| I believe the following "static" command would be useful in Python.
|
| def foo():
| static i = [10, 11]
| static firstcall = True
| if firstcall:
| print "First pass"
| firstcall = False
| i[0] += 1
| print i[0]
| foo()
| foo()
|
|
| This would output:
|
| First pass
| 11
| 12
|
| Just like in C, the variables i and firstcall are only assigned the
| first time foo() is called. To get this effect currently, one could
| use default arguments or wrapping the whole thing in a class. Both of
| these solutions seem like hacks, the above method IMO is more
| Pythonic. :)
"Pythonic" way is to use the oddity of default arguments:
def foo( static_vars = {'i':[10, 11],'firstcall':True} ):
if static_vars['firstcall']:
print "First pass"
static_vars['firstcall'] = False
static_vars['i'][0] += 1
print static_vars['i'][0]
foo()
foo()
--
Georgy
Nick Jacobson wrote: I believe the following "static" command would be useful in Python.
[...] Just like in C, the variables i and firstcall are only assigned the first time foo() is called. To get this effect currently, one could use default arguments or wrapping the whole thing in a class. Both of these solutions seem like hacks, the above method IMO is more Pythonic. :)
You could also use funtion properties def statictest ():
.... statictest.counter += 1
.... print statictest.counter
.... statictest.counter = 0 statictest ()
1 statictest ()
2
But this uses two lookups: one for the function in module scope and one for
the property. Three if you want to do this in a method
(class.method.property).
Just to describe all the possibilities, I probably wouldn't use this myself.
Daniel
> Why do you call using OO ("wrapping it in a class", as you say) a "hack"? Generally speaking, using objects to contain state information such as this is exactly what most people would call the cleanest, best approach.
class HasState: def __init__(self): self.firstCall = True self.i = [10, 11]
def foo(self): if self.firstCall: print "First pass" self.firstCall = False self.i[0] += 1 print self.i[0]
obj = HasState() obj.foo() obj.foo()
Now, without arguing that it has 11 lines instead of 8 to do the same thing (because then I'd just point out that this was a contrived example anyway, and that it is more easily extended, and more obvious what was going on, etc. :-) ), can you describe why you call this is a "hack"?
-Peter
I don't know if "hack" is the right word. What I meant is it seems
like overkill to have to make (and name) a class, plus add a second
function, every time you want a function to have a static variable.
> >>> i = [10 ,11] >>> firstcall = True >>> >>> def foo(): ... global i ... global firstcall ... if firstcall: ... print "First pass" ... firstcall = False ... i[0] += 1 ... print i[0] ... >>> foo() First pass 11 >>> foo()
12
Hmm. I would like it, but it pollutes the global namespace. Two
functions might want to use firstcall, for example (if they want to
just do something on the first pass). That's an error at most, and
renaming issues at the least.
Thanks for the idea, though..
Nick Jacobson wrote: I don't know if "hack" is the right word. What I meant is it seems like overkill to have to make (and name) a class, plus add a second function, every time you want a function to have a static variable.
I can't recall the last time I wanted a function to have
a static variable. Years, it's been...
(That probably just says something about our approach to design
and coding. I'm not criticizing you, just explaining why what
I showed seems natural and simple to mean, but not to you.)
-Peter
On Thu, Apr 29, 2004 at 12:09:03PM -0700, Nick Jacobson wrote: Why do you call using OO ("wrapping it in a class", as you say) a "hack"? Generally speaking, using objects to contain state information such as this is exactly what most people would call the cleanest, best approach.
class HasState: def __init__(self): self.firstCall = True self.i = [10, 11]
def foo(self): if self.firstCall: print "First pass" self.firstCall = False self.i[0] += 1 print self.i[0]
obj = HasState() obj.foo() obj.foo()
Now, without arguing that it has 11 lines instead of 8 to do the same thing (because then I'd just point out that this was a contrived example anyway, and that it is more easily extended, and more obvious what was going on, etc. :-) ), can you describe why you call this is a "hack"?
-Peter
I don't know if "hack" is the right word. What I meant is it seems like overkill to have to make (and name) a class, plus add a second function, every time you want a function to have a static variable.
Keeping state in functions is usually a "hack." Class instances have
state, functions just do stuff. That said you can get by just fine
using default arguments for small amounts of state in functions.
def foo(i=[]):
if (not i): # only true once
print "First!"
i.extend([10, 11])
i[0] += 1
print i[0]
But you really really don't want state in plain functions (as opposed
to member functions of objects). I would consider any function that
does something different when called twice with the same arguments broken.
Unless the name of the function starts with 'random' *wink*.
-jackdied
Peter Hansen wrote: Nick Jacobson wrote:
I believe the following "static" command would be useful in Python.
[snip]
Just like in C, the variables i and firstcall are only assigned the first time foo() is called. To get this effect currently, one could use default arguments or wrapping the whole thing in a class. Both of these solutions seem like hacks, the above method IMO is more Pythonic. :)
I'm not sure how to interpret the smiley, but I'll take it you weren't actually joking...
Why do you call using OO ("wrapping it in a class", as you say) a "hack"? Generally speaking, using objects to contain state information such as this is exactly what most people would call the cleanest, best approach. [...]
There's also a bunch of people who would consider this (modulo my
obvious mistakes ;) the cleanest, best approach:
(let ((first-call #t)
(i '(10 11)))
(define (foo)
(when (first-call)
(begin (display "first pass") (set! first-call #f))
(set! (array-ref i 0) (+ (array-ref i 0) 1))
(display (array-ref i 0))))
I.e. capture the state in a normal lexical variable.
Cheers,
Michael
Peter <pe***@engcorp.com> wrote on 04/29/04 at 14:37: I'm not sure how to interpret the smiley, but I'll take it you weren't actually joking...
Why do you call using OO ("wrapping it in a class", as you say) a "hack"? Generally speaking, using objects to contain state information such as this is exactly what most people would call the cleanest, best approach.
I'm not the original poster, but I'm going to side with him.
Class, to me, implies a fair number of things about the intended
use of what the author has written. Jacobson is talking about
a much simpler construct/feature than what one would normally
use a class for. His proposal might seem like mere syntactic
sugar to avoid making a class, but IMHO it will lead to code
that is more readable - code that doesn't imply it's anything
other than a function with a persistant, stateful variable.
Steve This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Alexander Mahr |
last post by:
Dear Newsgroup,
I'm somehow confused with the usage of the static keyword.
I can see two function of the keyword static in conjunction with a data
member of a class.
1. The data member...
|
by: Bryan Parkoff |
last post by:
I have noticed that C programmers put static keyword beside global
variable and global functions in C source codes. I believe that it is not
necessary and it is not the practice in C++. Static...
|
by: Datta Patil |
last post by:
Hi ,
#include<stdio.h>
func(static int k) /* point2 : why this is not giving error */
{
int i = 10 ;
// static int j = &i ; /* point 1: this will give compile time error */
return k;
}
/*...
|
by: Bas Wassink |
last post by:
Hello there,
I'm having trouble understanding a warning produced by 'splint', a
code-checker. The warning produced is:
keywords.c: (in function keyw_get_string)
keywords.c:60:31: Released...
|
by: The8thSense |
last post by:
how to declare static varible and static method inside a class ?
i try
"public static ABC as integer = 10"
and it said my declaration is invalid
Thanks
|
by: shantanu |
last post by:
Hi,
How can we declare a static variable or function declared in one
source file, which is to be used in other source file?
|
by: nospam_timur |
last post by:
Let's say I have two files, myfile.h and myfile.c:
myfile.h:
int myfunction(int x);
myfile.c:
#include "myfile.h"
|
by: lcdgoncalves |
last post by:
Hi everyone
Is there a real need to use keyword static with functions, if we
simply don't declare their prototypes in .h file?
Many textbooks avoid to discuss this matter and/or discuss only...
|
by: DaTurk |
last post by:
Hi,
I have an interesting issue, well, it's not really an issue, but I'd
like to understand the mechanics of what's going on. I have a file,
in CLI, which has a class declared, and a static...
|
by: Jess |
last post by:
Hello,
I learned that there are five kinds of static objects, namely
1. global objects
2. object defined in namespace scope
3. object declared static instead classes
4. objects declared...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
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...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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: 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: 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...
|
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...
| |