473,761 Members | 8,011 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 2789
Antoon Pardon wrote:
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
>>>betwee n (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
Please re-read your own writing above.
>
k[0] += i

So why are you trying so hard to show me this?
I was just expecting to be of any help, but it seems you just *refuse*
to understand.
>>>>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" ?
I still wait your explanation on this...
>>>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,
Yes : local namespace, then enclosing namespaces.
then you state here there is no need
to look for b because it is bound to local namespace.
Yes. b being bound in the local namespace, it's found in the local
namespace, so lookup stops here. Pretty simple.
That seems to
imply that the search order for b is different.
cf above.

AFAIR my original statement was that the search for b was different than
the search for a;
And it's plain wrong, as anyone taking a few minutes reading the doc and
doing some tests would know.
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.
Please repeat after me :
1/ binding in the local namespace makes the name local
2/ search order is local namespace first, then enclosing namespaces.
I may see some interpretation where you may say that the search order
for b is the same as for a and c
There's nothing to "interpret" here.
but I still am not comfortable with
it.
Too bad for you. But whether you are "comfortabl e" with reality is none
of my concern.
>
>>>>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.
So go and get yourself some glasses.
That Namespaces and names lookup are
fundamentel parts of the Python language, doesn't mean that
the right behaviour
define "right behaviour" ?
can't be implemented in multiple ways
I don't give a damn about how it's implemented.
and
doesn't contradict that a specific explanation depend on a specific
implementation instead of just on language definition.
This is totally meaningless.
>>>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.
I give up. You're a crank.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 7 '06 #21
Piet van Oostrum wrote:
(snip)
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.
Certainly not. Nested scopes allow closures, which allow decorators and
lot of *very* useful things. Remove this from Python, and you'll see a
*lot* of experimented programmers switch to another language.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 7 '06 #22
Antoon Pardon wrote:
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.
And he's right, cf below.

(snip)
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.
You're obviously clueless. Which would not be a problem if you did not
refuse to first aknowledge the fact then take appropriate actions.
Sure people may prefer to speak about (re)binding
vs mutating variables, but just because I didn't use the prefered terms,
If you refuse to understand that there are pretty good reasons to use
the appropriate semantic, that's your problem, but then no one can help
you.
starting to doubt my understanding of the language, seems a bit
premature IMO.
I do not 'doubt', I'm 111% confident.
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.
It is, obviously.

And you're definitively a crank.

--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 7 '06 #23
Bruno Desthuilliers wrote:
Certainly not. Nested scopes allow closures, which allow decorators and
lot of *very* useful things.
decorators can be trivially implemented as classes, of course. it's a
bit unfortunate that many people seem to think that decorators *have* to
be implemented as nested functions, rather than arbitrary callables.

</F>

Jul 7 '06 #24
On 2006-07-07, Piet van Oostrum <pi**@cs.uu.nlw rote:
>>>>>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'?
The name on the left side of an assignment that refers to a variable,
as opposed to names that are attributes.
>>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?
I don't rule out that I gained some understanding without noticing it.
Maybe my choice of words was poor then.

--
Antoon Pardon
Jul 7 '06 #25
On 2006-07-07, Fredrik Lundh <fr*****@python ware.comwrote:
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
implementati on instead of just on language definition.

the behaviour *is* defined in the language definition, and has nothing
to do with a specific implementation.
As far as I can see I didn't write anything that contradicts this.
It is possible that at some point my choice of wording was bad
and that I gave the impression that i somehow wanted to contradict
this. If that happened my appologies.
have you even read the language
reference ? do you even know that it exists ?
You mean this, I suppose:

http://docs.python.org/ref/naming.html

--
Antoon Pardon
Jul 7 '06 #26
On 2006-07-07, Fredrik Lundh <fr*****@python ware.comwrote:
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.
May be I misunderstand, maybe I sometimes have difficulties making my self
clear. If you already made up your mind which is it, that is fine by me.
I just don't see the point of just posting a response that just
boils down to: You are wrong. Even if you have given up on me, others
might be helped if you took the trouble of explainig what was wrong.

Well, that was just what I was thinking.

--
Antoon Pardon
Jul 7 '06 #27
Fredrik Lundh wrote:
Bruno Desthuilliers wrote:
>Certainly not. Nested scopes allow closures, which allow decorators and
lot of *very* useful things.


decorators can be trivially implemented as classes, of course. it's a
bit unfortunate that many people seem to think that decorators *have* to
be implemented as nested functions, rather than arbitrary callables.
Your of course right - and I should know better since AFAIK (IOW please
correct me if I'm wrong), closures and classes are somewhat
interchangeable .

OTHO, using closures can make things far more simple - just like having
functions being objects is not absolutely necessary for having HOF-like
features, but can make HOF much more simple. If you take back all these
kind of features from Python, you end up with something that's not
really better than Java - and then me run away screaming !-)

Thanks for the correction anyway.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Jul 7 '06 #28

"Antoon Pardon" <ap*****@forel. vub.ac.bewrote in message
news:sl******** ************@rc pc42.vub.ac.be. ..
others might be helped if you took the trouble of explaining
what was wrong.
Aside from F., I tried to explain what I think you said wrong. Did you
read it? Did it help any?

tjr


Jul 7 '06 #29
>>>>Antoon Pardon <ap*****@forel. vub.ac.be(AP) wrote:
>APOn 2006-07-07, Piet van Oostrum <pi**@cs.uu.nlw rote:
>>>>>>>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'?
>APThe name on the left side of an assignment that refers to a variable,
APas opposed to names that are attributes.
So let me get it clear:
In a.b = c, a is the lefthand variable, but b is not?

If that is what you mean then I interpret your statement
>AP`with an assignment the search for the lefthand variable
APdepends on whether the lefthand side is a simple variable or
APmore complicated'
as meaning that the search for `a' in `a.b = c' would be different than the
search for `a' in `a = b'. Well, it is not. But I can understand the
confusion. Namely, `a = b' introduces a binding for `a' in the local scope,
unless `a' was declared global. So the search will find `a' in the local
scope and it stops there. On the other hand `a.b = c' will not introduce a
binding for `a'. So the search for `a' may stop in the local space (if
there was another binding for `a' in the local scope) or it may need to
continue to outer scopes. The difference, however is not the
complicatedness of the lefthand side but whether the local scope contains a
binding for the variable.

--
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 #30

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

Similar topics

6
2040
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
2343
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
2569
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
1807
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
1529
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
9376
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,...
0
10136
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9923
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
9811
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...
1
7358
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
6640
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
5266
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...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2788
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.