Accessing Function Variables from Sub-functions

L

Licheng Fang

Specifically: a nested function cannot *RE-BIND* a variable of
an outer function.

Sorry to dig up this old thread, but I would like to know what's the
rationale is. Why can't a nested function rebind a variable of an
outer function?
One solution is the following, which I however do not see as very
clean or nice.
-------8<-------8<-------8<-------8<-------
def test ():
count = [0]
def inc_count ():
count[0] += 1
inc_count ()
inc_count ()
print count[0]
test ()
-------8<-------8<-------8<-------8<-------
Now my question: Is there some way to achieve this with a nicer
syntax?

Depends on your tastes in syntax, e.g.:

def test():
class Bunch: pass
loc = Bunch()
loc.count = 0
def inc_count():
loc.count += 1
inc_count()
inc_count()
print loc.count

or:

def test():
test.count = 0
def inc_count():
test.count += 1
inc_count()
inc_count()
print test.count

and no doubt quite a few others.

I was trying to write a function that creates another function and
returns it when I came across this problem. These two solutions have a
difference:

def M():
M.c = 0
class Bunch:
pass
Bunch.c = 0
def f():
M.c += 1
Bunch.c += 1
print M.c, Bunch.c
return f
6 3

The created functions share their variables binded to the outer
function, but have their separate copies of variables bundled in a
class.

Is binding name to the function object a python way to use 'static'
variables? But how to initialize them?
 
D

Diez B. Roggisch

Licheng said:
Sorry to dig up this old thread, but I would like to know what's the
rationale is. Why can't a nested function rebind a variable of an
outer function?

Because the lack of variable declarations in python makes the
left-hand-side-appearance of a variable the exact distinction criteria
between inner and outer scopes. Thus it can't rebind them. What you can do
is to use mutables as container for outer variables:


def outer():
v =[1]
def increment():
a = v[0]
a += 1
v[0] = a
increment()
print v[0]


Diez
 
T

Terry Reedy

| Sorry to dig up this old thread, but I would like to know what's the
| rationale is. Why can't a nested function rebind a variable of an
| outer function?

Because it is debateble whether this is overall a good idea and because it
was not obvious exactly how to do so. (There were about 10 different
proposals.) I believe an addition is scheduled for 3.0 (and 2.6 I
suspect).
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top