function with a state

X

Xah Lee

is it possible in Python to create a function that maintains a variable
value?

something like this:

globe=0;
def myFun():
globe=globe+1
return globe

apparently it can't be done like that. I thought it can probably be
done by prefixing the variable with some package context...

the Python doc is quite stilted. Where in the python doc is a programer
supposed read about how the package/module system in Python works?
(besides the tutorial that touches it)

Xah
(e-mail address removed)
http://xahlee.org/PageTwo_dir/more.html
 
P

Patrick Useldinger

Xah said:
globe=0;
def myFun():
globe=globe+1
return globe

The short answer is to use the global statement:

globe=0
def myFun():
global globe
globe=globe+1
return globe

more elegant is:

globe=0
globe=myfun(globe)
def myFun(var):
return var+1

and still more elegant is using classes and class attributes instead of
global variables.

-pu
 
A

and-google

Xah Lee said:
is it possible in Python to create a function that maintains a
variable value?

Yes. There's no concept of a 'static' function variable as such, but
there are many other ways to achieve the same thing.
globe=0;
def myFun():
globe=globe+1
return globe

This would work except that you have to tell it explicitly that you're
working with a global, otherwise Python sees the "globe=" and decides
you want 'globe' be a local variable.

globe= 0
def myFun():
global globe
globe= globe+1
return globe

Alternatively, wrap the value in a mutable type so you don't have to do
an assignment (and can use it in nested scopes):

globe= [ 0 ]
def myFun():
globe[0]+= 1
return globe[0]

A hack you can use to hide statics from code outside the function is to
abuse the fact that default parameters are calcuated at define-time:

def myFun(globe= [ 0 ]):
globe[0]+= 1
return globe[0]

For more complicated cases, it might be better to be explicit and use
objects:

class Counter:
def __init__(self):
self.globe= 0
def count(self):
self.globe+= 1
return self.globe

myFun= Counter().count
 
K

Kent Johnson

Patrick said:
The short answer is to use the global statement:

globe=0
def myFun():
global globe
globe=globe+1
return globe

more elegant is:

globe=0
globe=myfun(globe)
def myFun(var):
return var+1

This mystifies me. What is myfun()? What is var intended to be?

Kent
 
R

Reinhold Birkenfeld

Xah said:
is it possible in Python to create a function that maintains a variable
value?

something like this:

globe=0;
def myFun():
globe=globe+1
return globe

You could work with function attributes:


def myFun():
try: myFun.globe += 1
except: myFun.globe = 1

return myFun.globe

or with a default function argument:


class Dummy: pass

def myFun(globe=Dummy()):
try: globe.globe += 1
except: globe.globe = 1

return globe.globe

Reinhold
 
A

Andrew Koenig

globe=0;
def myFun():
globe=globe+1
return globe

apparently it can't be done like that. I thought it can probably be
done by prefixing the variable with some package context...

You can do this:

globe=0
def myFun():
global globe
globe=globe+1
return globe

The question you should ask yourself, however, is why you want to do this.
Do you really want to tie your function to a single global variable? Are
you sure you will never need more than one?

For example, the function you've written represents a counter. Are you sure
you will never need more than one such counter?
 
G

gene.tani

I believe python docs are quite *un*-stilted. Modules and packages are
not complicated. Read chapter 7 of the nutshell, it's only 10 pages
long. 2.3 and 2.4 didn't introduce any fundamental changes in how
modules work AFAIK
 
P

Patrick Useldinger

Kent said:
This mystifies me. What is myfun()? What is var intended to be?

myfun is an error ;-) should be myFun, of course.

var is parameter of function myFun. If you call myFun with variable
globe, all references to var will be replaced by globe inside function
myFun.

-pu
 
K

Kent Johnson

Patrick said:
myfun is an error ;-) should be myFun, of course.

var is parameter of function myFun. If you call myFun with variable
globe, all references to var will be replaced by globe inside function
myFun.

Oh. I thought there was some deep magic here that I was missing :)

You also have to define myFun before you call it...

def myFun(var):
return var+1

globe = 0
....
globe = myFun(globe)

Kent
 
M

Mike Meyer

Xah Lee said:
the Python doc is quite stilted. Where in the python doc is a programer
supposed read about how the package/module system in Python works?
(besides the tutorial that touches it)

The python docs at <URL: http://docs.python.org/ref/naming.html > are
perfectly clear. It explains the namespaces used when resolving
variable names, and how to subvert the standard resolution to solve
your problem.

<mike
 
S

Stephen Thorne

The short answer is to use the global statement:

globe=0
def myFun():
global globe
globe=globe+1
return globe

more elegant is:

globe=0
globe=myfun(globe)
def myFun(var):
return var+1

and still more elegant is using classes and class attributes instead of
global variables.

Or what about just using the function object directly?

def myFun():
myFun.x += 1
return myFun.x
myFun.x = 0

for test in range(10):
assert myFun()+1 == myFun()
assert myFun()*2+3 == myFun()+myFun()
assert range(myFun(), myFun()+9) == [myFun() for x in range(10)]
assert range(myFun()+2, myFun()+11) == [myFun() for x in range(10)]

:))

couldn't-help-feeding-the-troll-ly-y'rs.
Stephen Thorne.
 
R

Reinhold Birkenfeld

Reinhold said:
or with a default function argument:


class Dummy: pass

def myFun(globe=Dummy()):
try: globe.globe += 1
except: globe.globe = 1

return globe.globe

A quicker way:

def myFun(globe=[0]):
globe[0] += 1
return globe[0]

Reinhold
 
X

Xah Lee

thanks for the help...

-------
the python doc is stilted. It tried to organized the thing and with a
style around some highbrow inane "computer science" outlook.

i found the little section on global
(http://python.org/doc/2.4/ref/global.html)
and can't make out what shit it is trying to say without having read
and figured out the entire doc of its style and contexts and
definitions. (formalization varies and computing model and jargons mean
different things.)

Python doc writers needs to re-organize and re-style their docs so that
its organization is towards programing, as opposed to how the
implementation works (as in the Lib Reference), or a formalization of
the language spec. (e.g. the fucking semi-joke of "(for language
lawyers)" and BNF and those Runtime "Service" shits.) Its style
needs to shift from highbrowism to pragmatic and exemplary.

I've addressed some of the jargon-riding ills common in industry with
examples from the Python doc, archived here:
http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html

as to the way of its stiltedenss and academicism, which make it hard
for programers to find or apply any info, i'll expound later.

PS just so that there is no misunderstanding: The docs of unix and
Perl, are fucking criminally incompetent. Python docs, although stilted
in a academic way, but nevertheless is solid, and its writers are
educated, and tried best to make it a quality one, albeit sometimes
inevitably showed some masterbation and jargonization. While the unix
and Perl docs, (and essentially all things out of unix, e.g. Apache
docs), are fucking incompetent drivels and in many cases exorbitant
lies, and they semi-present it as humor and want and brainwash people
to take them as norm. In a nutshell, these people are spreading
untruths and indirectly are causing massive harm in the computing
industry. People, we need to stop it. This each of us can do by not
accepting their attitudes or behavior. In online forums, work place,
conventions, conversations etc., raise questions or otherwise voice
your opinion whenever you can.

Xah
(e-mail address removed)
http://xahlee.org/PageTwo_dir/more.html
 
S

Steve Holden

Xah said:
thanks for the help...
[usual semi-literate expletive-deleted rant omitted]


<sarcasm>And your writing is so lucid and comprehensible, it's a pity
you can't simply rewrite the documentation so the rest of the world can
understand it.</sarcasm>

While the Python documentation does, of course, have its shortcomings,
you will not improve it by indulging in this kind of nonsense, which
appears to have become some kind of reflex. Your apparent assumption
that your idiotic behavior will make any difference to anything or
anybody is arrogant beyond belief. This is a real pity, as your web site
makes it apparent that in matters where you possess genuine knowledge
you can produce worthwhile work.

Please abandon any notion that your own writings are in any way superior
to the object of your complaints. At least I can learn Python from the
documentation. From you I can learn nothing, you are so self-absorbed
that it would take a pneumatic drill to penetrate that thick skull.

regards
Steve

PS: There is no "e" in masturbation, as any properly-qualified wanker
should know.
 
S

Sean Blakey

thanks for the help...

-------
the python doc is stilted. It tried to organized the thing and with a
style around some highbrow inane "computer science" outlook.

i found the little section on global
(http://python.org/doc/2.4/ref/global.html)
and can't make out what shit it is trying to say without having read
and figured out the entire doc of its style and contexts and
definitions. (formalization varies and computing model and jargons mean
different things.)

Python doc writers needs to re-organize and re-style their docs so that
its organization is towards programing, as opposed to how the
implementation works (as in the Lib Reference), or a formalization of
the language spec. (e.g. the fucking semi-joke of "(for language
lawyers)" and BNF and those Runtime "Service" shits.) Its style
needs to shift from highbrowism to pragmatic and exemplary.

I've addressed some of the jargon-riding ills common in industry with
examples from the Python doc, archived here:
http://xahlee.org/Periodic_dosage_dir/t2/xlali_skami_cukta.html

as to the way of its stiltedenss and academicism, which make it hard
for programers to find or apply any info, i'll expound later.

PS just so that there is no misunderstanding: The docs of unix and
Perl, are fucking criminally incompetent. Python docs, although stilted
in a academic way, but nevertheless is solid, and its writers are
educated, and tried best to make it a quality one, albeit sometimes
inevitably showed some masterbation and jargonization. While the unix
and Perl docs, (and essentially all things out of unix, e.g. Apache
docs), are fucking incompetent drivels and in many cases exorbitant
lies, and they semi-present it as humor and want and brainwash people
to take them as norm. In a nutshell, these people are spreading
untruths and indirectly are causing massive harm in the computing
industry. People, we need to stop it. This each of us can do by not
accepting their attitudes or behavior. In online forums, work place,
conventions, conversations etc., raise questions or otherwise voice
your opinion whenever you can.

Xah
(e-mail address removed)
http://xahlee.org/PageTwo_dir/more.html

Have you submitted a patch? I'm curious how you would document "global".
 
P

Peter Hansen

Xah said:
this is intriguing. How does it work?
not a rhetorical question, but where in the python doc can i read about
it?

The tutorial, presumably, since there is nothing here
that isn't covered by the most basic aspects of Python.

Really, what did you think was there that was so
intriguing? A function is defined. It takes a
parameter and returns its value plus one. A
variable is created with the value 0. The
function is called, passing the value of the
variable, and the return value (remember, the
function just adds one!) is assigned to the
variable. Now "globe" equals 1.

Again, what aspect of this startled you?

-Peter
 
D

Dan Bishop

Xah Lee said:
is it possible in Python to create a function that maintains a
variable value?

Yes. There's no concept of a 'static' function variable as such, but
there are many other ways to achieve the same thing.
globe=0;
def myFun():
globe=globe+1
return globe

[snip]

For more complicated cases, it might be better to be explicit and use
objects:

class Counter:
def __init__(self):
self.globe= 0
def count(self):
self.globe+= 1
return self.globe

myFun= Counter().count

You can also use generators.
.... var = 0
.... while True:
.... var += 1
.... yield var
....4
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top