473,837 Members | 1,656 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Nested scopes, and augmented assignment

Hi,

The following might be documented somewhere, but it hit me unexpectedly
and I couldn't exactly find this in the manual either.

Problem is, that I cannot use augmented assignment operators in a
nested scope, on variables from the outer scope:

PythonWin 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond (mh******@skipp inet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>def foo():
.... def nestedfunc(bar) :
.... print bar, ';', localvar
.... localvar += 1
.... localvar=0
.... nestedfunc('bar ')
....
>>foo()
bar =Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
File "<interacti ve input>", line 6, in foo
File "<interacti ve input>", line 3, in nestedfunc
UnboundLocalErr or: local variable 'localvar' referenced before
assignment
>>>
This is entirely counter-intuitive to me, and searching the manual for
nested scoping rules and for augmented assignment rules, I still feel
that I couldn't have predicted this from the docs.

Is this an implementation artifact, bug, or should it really just
follow logically from the language definition?

Regards,

--Tim

Jul 4 '06
37 2807
Antoon Pardon wrote:
On 2006-07-05, Piet van Oostrum <pi**@cs.uu.nlw rote:
>>>>>>>Antoon Pardon <ap*****@forel. vub.ac.be(AP) wrote:
>>>APOn 2006-07-05, Bruno Desthuilliers <on***@xiludom. growrote:

>Antoon Pardon wrote:
>(snip)
>
>>Well no matter what explanation you give to it, and I understand how it
>>works,
>
>I'm not sure of this.
>>>APShould I care about that?

Yes, because as long as you don't understand it, you are in for unpleasant
surprises.


Well if someone explains what is wrong about my understanding, I
certainly care about that (although I confess to sometimes being
impatient) but someone just stating he is not sure I understand?
From what you wrote, I cannot decide if you really understand Python's
lookup rules and poorly express some disagreement on it, or if you just
don't understand Python lookup rules at all.
>
>>>>>It's not about "finding a name/identifier", it's about the difference
>between (re)binding a name and mutating an object.
>>>APThe two don't contradict each other. Python has chosen that it won't
APrebind variables that are out of the local scope. So if the lefthand
APside of an assignment is a simple name it will only search in the
APlocal scope for that name. But if the lefthand side is more complicated
APif will also search the outerscopes for the name.
Now it's pretty clear you *don't* understand.

In the second case, ie:

k = [0]
def f(i):
k[0] += i

'k[0]' is *not* a name. The name is 'k'. If we rewrite this snippet
without all the syntactic sugar, we get something like:

k = [0]
def f(i):
k.__setitem_(0, k.__getitem__(0 ) + i)

Now where do you see any rebinding here ?
>
>>No. It will always use the same search order.


So if I understand you correctly in code like:

c.d = a
b = a

All three names
which ones ?
are searched for in all scopes between the local en global
one.
In this example, we're at the top level, so the local scope is the
global scope. I assert what you meant was:

c = something
a = something_else

def somefunc():
c.d = a
b = a

(NB : following observations will refer to this code)
That is what I understand with your statement that [python] always
uses the same search order.
yes.

My impression was that python will search for c and a in the total current
namespace
what is "the total current namespace" ?
but will not for b.
b is bound in the local namespace, so there's no need to look for it in
enclosing namespaces.
>
>>But a variable that is bound
inside the function (with an asignment) and is not declared global, is in
the local namespace.

Aren't we now talking about implementation details?
Certainly not. Namespaces and names lookup rules are fundamental parts
of the Python language.
Sure the compilor
can set things up so that local names are bound to the local scope and
so the same code can be used. But it seems somewhere was made the
decision that b was in the local scope without looking for that b in
the scopes higher up.
binding creates a name in the current namespace. b is bound in the local
namespace, so b is local. period.

(snip)

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 6 '06 #11
>>>>Antoon Pardon <ap*****@forel. vub.ac.be(AP) wrote:
>APWell if someone explains what is wrong about my understanding, I
APcertainly care about that (although I confess to sometimes being
APimpatient) but someone just stating he is not sure I understand?
That is just a euphemistic way of stating `I think you do not understand
it'.
>APSo if I understand you correctly in code like:
>AP c.d = a
AP b = a
>APAll three names are searched for in all scopes between the local en global
APone. That is what I understand with your statement that [python] always
APuses the same search order.
The d is different because it is an attribute. So it is looked up in the
context of the object that is bound to c. For a, b, and c it is correct.
>APMy impression was that python will search for c and a in the total current
APnamespace but will not for b.
The assignment to b inside the function (supposing the code above is part
of the function body) tells the compiler that b is a local variable. So the
search stops in the local scope. The search order is always from local to
global. First the current function, then nested function, then the module
namespace, and finally the builtins. The first match will stop the search.
Now for local variables inside a function, including the parameters, the
compiler will usually optimize the search because it knows already that it
is a local variable. But that is an implementation detail.
>>But a variable that is bound
inside the function (with an asignment) and is not declared global, is in
the local namespace.
>APAren't we now talking about implementation details? Sure the compilor
APcan set things up so that local names are bound to the local scope and
APso the same code can be used. But it seems somewhere was made the
APdecision that b was in the local scope without looking for that b in
APthe scopes higher up.
Yes, as I (and others) have already said several times: an assignment to a
variable inside a function body (but not an assignment to an attribute or
part of an object) without a global declaration makes that variable a local
variable. That is not an implementation detail; it is part of the language definition.
>APLet me explain a bit more. Suppose I'm writing a python interpreter
APin python. One implemantation detail is that I have a list of active
APscopes which are directories which map names to objects. At the
APstart of a new function the scope list is adapted and all local
APvariables are inserted to the new activated scope and mapped to
APsome "Illegal Value" object. Now I also have a SearchName function
APthat will start at the begin of a scope list and return the
APfirst scope in which that name exists. The [0] element is the
APlocal scope. Now we come to the line "b = a"
>APThis could be then executed internally as follows:
>AP LeftScope = SearchName("b", ScopeList)
AP RightScope = SearchName("a", ScopeList)
AP LeftScope["b"] = RightScope["a"]
>APBut I don't have to do it this way. I already know in which scope
AP"b" is, the local one, which has index 0. So I could just as well
APhave that line exucuted as follows:
>AP LeftScope = ScopeList[0]
AP RightScope = SearchName("a", ScopeList)
AP LeftScope["b"] = RightScope["a"]
>APAs far as I understand both "implementation s" would make for
APa correct execution of the line "b = a" and because of the
APsecond possibility, b is IMO not conceptually searched for in
APthe same way as a is searched for, although one could organise
APthings that the same code is used for both.
That is the optimization I spoke of above. But it is not the problem we
were discussing. Conceptually it is the same. It is similar to constant
folding (replacing x = 2+3 by x = 5).
>APOf course it is possible I completely misunderstood how python
APis supposed to work and the above is nonesense in which case
API would appreciate it if you correct me.
>APPython could have chosen an approach with a "nested" keyword, to allow
APrebinding a name in an intermediate scope. It is not that big a deal
APthat it hasn't, but I keep finding the result strange and somewhat
APcounterintui tive.
>>>
Maybe it would have been nice if variables could have been declared as
nested, but I think it shows that nested variables have to be used with
care, similar to globals. Especially not allowing rebinding in intermediate
scopes is a sound principle (`Nested variables considered harmful').
If you need to modify the objects which are bound to names in intermediate
scopes, use methods and give these objects as parameters.
>APBut shouldn't we just do programming in general with care? And if
APNested variables are harmfull, what is then the big difference
APbetween rebinding them and mutating them that we should forbid
APthe first and allow the second?
There is no big difference I think. Only Python doesn't have syntax for the
former. Older versions of Python didn't even have nested scopes. maybe it
was a mistake to add them. I think an important reason was the use in
lambda expressions, which Guido also regrets IIRC.
>API understand that python evolved and that this sometimes results
APin things that in hindsight could have been done better. But
API sometimes have the impression that the defenders try to defend
APthose results as a design decision. With your remark above I have
APto wonder if someone really thought this through at design time
APand came to the conclusion that nested variables are harmfull
APand thus may not be rebound but not that harmfull so mutation
APis allowed and if so how he came to that conclusion.
I don't think that was the reasoning. On the other hand I think nested
scopes were mainly added for read-only access (to the namespace that is,
not to the values) . But then Python doesn't forbid you to change mutable
objects once you have access to them.
--
Piet van Oostrum <pi**@cs.uu.n l>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C 4]
Private email: pi**@vanoostrum .org
Jul 6 '06 #12
On 2006-07-06, Piet van Oostrum <pi**@cs.uu.nlw rote:
>>APAren't we now talking about implementation details? Sure the compilor
APcan set things up so that local names are bound to the local scope and
APso the same code can be used. But it seems somewhere was made the
APdecision that b was in the local scope without looking for that b in
APthe scopes higher up.

Yes, as I (and others) have already said several times: an assignment to a
variable inside a function body (but not an assignment to an attribute or
part of an object) without a global declaration makes that variable a local
variable. That is not an implementation detail; it is part of the language definition.
You seem to think I didn't understand this. Maybe I'm not very good
at explaining what I mean, but you really haven't told me anything
here I didn't already know.
>>AP[ ... ]
APNow we come to the line "b = a"
>>APThis could be then executed internally as follows:
>>AP LeftScope = SearchName("b", ScopeList)
AP RightScope = SearchName("a", ScopeList)
AP LeftScope["b"] = RightScope["a"]
>>APBut I don't have to do it this way. I already know in which scope
AP"b" is, the local one, which has index 0. So I could just as well
APhave that line exucuted as follows:
>>AP LeftScope = ScopeList[0]
AP RightScope = SearchName("a", ScopeList)
AP LeftScope["b"] = RightScope["a"]
>>APAs far as I understand both "implementation s" would make for
APa correct execution of the line "b = a" and because of the
APsecond possibility, b is IMO not conceptually searched for in
APthe same way as a is searched for, although one could organise
APthings that the same code is used for both.

That is the optimization I spoke of above. But it is not the problem we
were discussing.
Could you maybe clarify what problem we are discussing? All I wrote
was that with an assignment the search for the lefthand variable
depends on whether the lefthand side is a simple variable or
more complicated. Sure people may prefer to speak about (re)binding
vs mutating variables, but just because I didn't use the prefered terms,
starting to doubt my understanding of the language, seems a bit
premature IMO. I'm sure there are areas where my understanding of
the language is shaky, metaclasses being one of them, but understanding
how names are searched doesn't seem to be one of them.

--
Antoon Pardon
Jul 6 '06 #13
On 2006-07-06, Bruno Desthuilliers <on***@xiludom. growrote:
Antoon Pardon wrote:
>On 2006-07-05, Piet van Oostrum <pi**@cs.uu.nlw rote:
>>>>>>It's not about "finding a name/identifier", it's about the difference
>>between (re)binding a name and mutating an object.

APThe two don't contradict each other. Python has chosen that it won't
APrebind variables that are out of the local scope. So if the lefthand
APside of an assignment is a simple name it will only search in the
APlocal scope for that name. But if the lefthand side is more complicated
APif will also search the outerscopes for the name.

Now it's pretty clear you *don't* understand.

In the second case, ie:

k = [0]
def f(i):
k[0] += i

'k[0]' is *not* a name. The name is 'k'. If we rewrite this snippet
without all the syntactic sugar, we get something like:

k = [0]
def f(i):
k.__setitem_(0, k.__getitem__(0 ) + i)

Now where do you see any rebinding here ?
What point do you want to make? As far as I can see, I
didn't write anything that implied I expected k to
be rebound in code like

k[0] += i

So why are you trying so hard to show me this?
>>
>>>No. It will always use the same search order.


So if I understand you correctly in code like:

c.d = a
b = a

All three names

which ones ?
>are searched for in all scopes between the local en global
one.

In this example, we're at the top level, so the local scope is the
global scope. I assert what you meant was:
I'm sorry I should have been more clear. I meant it to be
a piece of function code.
c = something
a = something_else

def somefunc():
c.d = a
b = a

(NB : following observations will refer to this code)
>That is what I understand with your statement that [python] always
uses the same search order.

yes.
>My impression was that python will search for c and a in the total current
namespace

what is "the total current namespace" ?
>but will not for b.

b is bound in the local namespace, so there's no need to look for it in
enclosing namespaces.
Now could you clarify please. First you agree with the statement that python
always uses the same search order, then you state here there is no need
to look for b because it is bound to local namespace. That seems to
imply that the search order for b is different.

AFAIR my original statement was that the search for b was different than
the search for a; meaning that the search for b was limited to the local
scope and this could be determined from just viewing a line like "b = a"
within a function. The search for a (or c in a line like: "c.d = a")
is not limited to the local scope.

I may see some interpretation where you may say that the search order
for b is the same as for a and c but I still am not comfortable with
it.
>>>But a variable that is bound
inside the function (with an asignment) and is not declared global, is in
the local namespace.

Aren't we now talking about implementation details?

Certainly not. Namespaces and names lookup rules are fundamental parts
of the Python language.
I don't see the contradiction. That Namespaces and names lookup are
fundamentel parts of the Python language, doesn't mean that
the right behaviour can't be implemented in multiple ways and
doesn't contradict that a specific explanation depend on a specific
implementation instead of just on language definition.
>Sure the compilor
can set things up so that local names are bound to the local scope and
so the same code can be used. But it seems somewhere was made the
decision that b was in the local scope without looking for that b in
the scopes higher up.

binding creates a name in the current namespace. b is bound in the local
namespace, so b is local. period.
I wrote nothing that contradicts that.

--
Antoon Pardon
Jul 6 '06 #14

"Antoon Pardon" <ap*****@forel. vub.ac.bewrote in message
news:sl******** ************@rc pc42.vub.ac.be. ..
And if Nested variables are harmfull,
I don't know if anyone said that they were, but Guido obviously does not
think so, or he would not have added them. So skip that.
what is then the big difference between rebinding them and mutating them
A variable is a name. Name can be rebound (or maybe not) but they cannot
be mutated. Only objects (with mutation methods) can be mutated. In other
words, binding is a namespace action and mutation is an objectspace action.
In Python, at least, the difference is fundamental.

Or, in other other words, do not be fooled by the convenient but incorrect
abbreviated phrase 'mutate a nested variable'.
that we should forbid the first and allow the second?
Rebinding nested names is not forbidden; it has just not yet been added
(see below).

Being able to mutate a mutable object is automatic once you have a
reference to it. In other words, it you can read the value, you can mutate
it (if it is mutable).
I understand that python evolved and that this sometimes results
in things that in hindsight could have been done better.
So does Guido. That is one explicit reason he gave for not choosing any of
the nunerous proposals for the syntax and semantics of nested scope write
access. In the face of anti-consensus among the developers and no
particular personal preference, he decided, "Better to wait than roll the
dice and make the wrong, hard to reverse, choice now". (Paraphrased quote)
>I have to wonder if someone really thought this through at design time
Giving the actual history of, if anything, too many people thinking too
many different thoughts, this is almost funny.

Recently however, Guido has rejected most proposals to focus attention on
just a few variations and possibly gain a consensus. So I think there is
at least half a chance that some sort of nested scope write access will
appear in 2.6 or 3.0.

Terry Jan Reedy

Jul 7 '06 #15
>>>>Antoon Pardon <ap*****@forel. vub.ac.be(AP) wrote:
>APCould you maybe clarify what problem we are discussing? All I wrote
APwas that with an assignment the search for the lefthand variable
APdepends on whether the lefthand side is a simple variable or
APmore complicated.
What do you mean with `the lefthand variable'? Especially when talking
about `complicated lefthand sides'?
>APSure people may prefer to speak about (re)binding
APvs mutating variables, but just because I didn't use the prefered terms,
APstarting to doubt my understanding of the language, seems a bit
APpremature IMO. I'm sure there are areas where my understanding of
APthe language is shaky, metaclasses being one of them, but understanding
APhow names are searched doesn't seem to be one of them.
You didn't understand it in your OP. Maybe your understanding has gained in
the meantime?
--
Piet van Oostrum <pi**@cs.uu.n l>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C 4]
Private email: pi**@vanoostrum .org
Jul 7 '06 #16
>>>>"Terry Reedy" <tj*****@udel.e du(TR) wrote:
>TR"Antoon Pardon" <ap*****@forel. vub.ac.bewrote in message
TRnews:sl***** *************** @rcpc42.vub.ac. be...
>>And if Nested variables are harmfull,
>TRI don't know if anyone said that they were, but Guido obviously does not
TRthink so, or he would not have added them. So skip that.
I used that phrase (with correct spelling). I had supposed that it would
be recognised as a variation of 'Global variables considered harmful',
(William Wulf and Mary Shaw, ACM SIGPLAN Notices, 1973, 8 (2) pp. 28--34).
I think nested variables have the same troubles as global variables, so
they should be used with care.
--
Piet van Oostrum <pi**@cs.uu.n l>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C 4]
Private email: pi**@vanoostrum .org
Jul 7 '06 #17
Antoon Pardon wrote:
>have any of your "my mental model of how Python works is more important
than how it actually works" ever had a point ?

Be free to correct me. But just suggesting that I'm wrong doesn't help
me in changing my mental model.
over the years, enough people have wasted enough time on trying to get
you to understand how Python works, in various aspects. if you really
were interested in learning, you would have learned something by now,
and you wouldn't keep repeating the same old misunderstandin gs over and
over again.

</F>

Jul 7 '06 #18
Antoon "I'm no nincompoop, but I play one on the internet" Pardon wrote:
I don't see the contradiction. That Namespaces and names lookup are
fundamentel parts of the Python language, doesn't mean that
the right behaviour can't be implemented in multiple ways and
doesn't contradict that a specific explanation depend on a specific
implementation instead of just on language definition.
the behaviour *is* defined in the language definition, and has nothing
to do with a specific implementation. have you even read the language
reference ? do you even know that it exists ?

</F>

Jul 7 '06 #19
Piet van Oostrum wrote:
There is no big difference I think. Only Python doesn't have syntax for the
former. Older versions of Python didn't even have nested scopes.
arbitrarily nested scopes, at least. the old local/global/builtin
approach (the LGB rule) is of course a kind of nesting; the new thing is
support for "enclosing scopes" in Python 2.1/2.2 (the LEGB rule). for
some background, see:

http://www.python.org/dev/peps/pep-0227/

the section "Rebinding names in enclosing scopes" discusses the 2.X-
specific thinking; this may be revised in 3.0 (see current python-dev
discussions).

</F>

Jul 7 '06 #20

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

Similar topics

6
2044
by: Doug Tolton | last post by:
I have a function that returns a tuple: def checkdoc(self, document): blen = document bates = document normal, truncated, semicolon = 0,0,0 for bat in bates: if len(bat) == 2 * blen: semicolon += 1
3
2349
by: Nils Grimsmo | last post by:
hi, i'm having some trouble nesting functions. consider the following: def h(): x = 1 def g(): print x # ok, x is taken from h g()
6
2572
by: Andy Baker | last post by:
Hi there, I'm learning Python at the moment and trying to grok the thinking behind it's scoping and nesting rules. I was googling for nested functions and found this Guido quote: (http://www.python.org/search/hypermail/python-1993/0343.html) "This is because nested function definitions don't have access to the local variables of the surrounding block -- only to the globals of the
5
1814
by: Dave Benjamin | last post by:
I ran into an odd little edge case while experimenting with functions that create classes on the fly (don't ask me why): >>> def f(x): ... class C(object): ... x = x ... print C.x ... >>> f(5) Traceback (most recent call last):
4
1535
by: Pierre Barbier de Reuille | last post by:
Hello, a discussion began on python-dev about this. It began by a bug report, but is shifted and it now belongs to this discussion group. The problem I find with augmented assignment is it's too complex, it's badly explained, it's error-prone. And most of all, I don't see any use-case for it ! The most common error is to consider that :
0
9685
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
1
10634
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10277
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9413
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 project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7817
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7007
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5674
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4479
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
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.