473,390 Members | 1,360 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,390 software developers and data experts.

LEGB rule, totally confused ...

hello,

I've thought many times I finally understood the import / namespace rules,
but again I'm totally lost :-(

This is my library file

# Module lib_test.py

X = 1

def Init():
global X
X = 3
print 'Init', X

def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1
print ' Run', X

And this my main program in another file:

import lib_test
lib_test.Init()
print lib_test.X

lib_test.Run()
print lib_test.X

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
Now if I remove "X = X + 1" I don't get an error ???
Is this a problem of the traceback procedure or the IDE,
or is Python not completely an interpreter, that reads line by line ???

Please explain this to me.

thanks,
Stef Mientki
Aug 14 '07 #1
6 1991
stef mientki wrote:
hello,

I've thought many times I finally understood the import / namespace rules,
but again I'm totally lost :-(

This is my library file

# Module lib_test.py

X = 1

def Init():
global X
X = 3
print 'Init', X

def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1
print ' Run', X

And this my main program in another file:

import lib_test
lib_test.Init()
print lib_test.X

lib_test.Run()
print lib_test.X

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
Now if I remove "X = X + 1" I don't get an error ???
Is this a problem of the traceback procedure or the IDE,
or is Python not completely an interpreter, that reads line by line ???

Please explain this to me.
This are the scoping-rules of python. A variable name on the left side of an
name-binding/assignment operator (including augmented assignments, vulgo:
+= and brothers) will make the variable name a function-local.

So

x = 10
def foo():
print x
x = 100

makes x a local variable to foo, which of course can't be accessed in

print x

Diez
Aug 14 '07 #2
stef mientki a écrit :
hello,

I've thought many times I finally understood the import / namespace rules,
but again I'm totally lost :-(

This is my library file

# Module lib_test.py

X = 1

def Init():
global X
X = 3
print 'Init', X

def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1
print ' Run', X

And this my main program in another file:

import lib_test
lib_test.Init()
print lib_test.X

lib_test.Run()
print lib_test.X

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
If you use a global to *modify* it, you MUST declare "global X", either
Python consider using a local.
So for your error: at compile time, in Run(), it see that it must use a
local X (because you set it) and generate ad-hoc bytecode, but when
running X is not defined locally, so the error.
Now if I remove "X = X + 1" I don't get an error ???
If you remove the "X =..." statement, then the compiler dont know
a-priori if its local or global, so it search X in both namespaces.
Is this a problem of the traceback procedure or the IDE,
or is Python not completely an interpreter, that reads line by line ???
Its compiled to buyte-code then interpreted from the byte-code.
>
Please explain this to me.

thanks,
Stef Mientki
A+

Laurent.
Aug 14 '07 #3
On 2007-08-14, stef mientki <st**********@gmail.comwrote:
I've thought many times I finally understood the import /
namespace rules, but again I'm totally lost :-(

This is my library file

# Module lib_test.py

X = 1

def Init():
global X
X = 3
print 'Init', X

def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1
print ' Run', X
From _Python Language Reference Manual_ see: '4.1 Naming and
Binding' and '6.13 The global statement'.

If a name is bound [assigned] in a block, it is a local
variable of that block.

...

The global statement is a declaration which holds for the
entire current code block. It means that the listed identifiers
are to be interpreted as globals. It would be impossible to
assign to a global variable without global, although free
variables may refer to globals without being declared global.

Since your Init and Run functions both assign (bind) a value to
X, X is assumed to be a local variable unless you say otherwise
with a global statement.

Note that the global statement in Init applies only in Init's
code block. Run must have it's own 'global X' statement, if
applicable.

--
Neil Cerutti
Aug 14 '07 #4
stef mientki <st**********@gmail.comwrote:
def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
Now if I remove "X = X + 1" I don't get an error ???
Several people have already explained the scoping rules acting
here, but let's just look at how that error message is telling
you everything you need to know to fix the problem.

"local variable 'X' referenced before assignment"

"local variable 'X'" immediately tells you that the 'X' in
question is not your global 'X'.

"referenced before assignment": well, 'print X' is surely a
reference to 'X', and 'X = X + 1' is an assignment to it,
and 'print X' appears before 'X = X + 1'. That this is the
key you have confirmed experimentally.

The question to ask here is "Why does Python think 'X' is
local?" Everything else is answered by the error message.

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Aug 14 '07 #5
Sion Arrowsmith wrote:
stef mientki <st**********@gmail.comwrote:
> def Run ():
print X <=== UnboundLocalError: local variable
'X' referenced before assignment
X = X + 1

Why do I get the error ?
Printing isn't assigning anything or am I missing something.
Now if I remove "X = X + 1" I don't get an error ???

Several people have already explained the scoping rules acting
here, but let's just look at how that error message is telling
you everything you need to know to fix the problem.

"local variable 'X' referenced before assignment"

"local variable 'X'" immediately tells you that the 'X' in
question is not your global 'X'.

"referenced before assignment": well, 'print X' is surely a
reference to 'X', and 'X = X + 1' is an assignment to it,
and 'print X' appears before 'X = X + 1'. That this is the
key you have confirmed experimentally.

The question to ask here is "Why does Python think 'X' is
local?" Everything else is answered by the error message.

Thanks guys, I beginning to see the light again,
and if X is mutual the story is completely different,
I still have to get used to these differences.

cheers,
Stef Mientki

Aug 14 '07 #6
Thanks guys, I beginning to see the light again,
and if X is mutual the story is completely different,
I still have to get used to these differences.
<nitpicking-for-the-sake-of-the-casual-reader>

That's supposed to be "mutable", not "mutual".

</nitpicking-for-the-sake-of-the-casual-reader>

Diez
Aug 14 '07 #7

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

Similar topics

11
by: James Gregory | last post by:
I'm pretty sure this is non-totally-trivial enough and standard-C++ enough to post here, however much it may initially look like a "how do I make a computer game?" question, though I may be wrong....
10
by: Lauren Wilson | last post by:
Ok I have searched the MS website for info on this. I am totally confused. If I want to deploy an Access 2003 app and allow my users to run it using Access 2003 Runtime, where do I get the...
145
by: Sidney Cadot | last post by:
Hi all, In a discussion with Tak-Shing Chan the question came up whether the as-if rule can cover I/O functions. Basically, he maintains it can, and I think it doesn't. Consider two...
7
by: chad | last post by:
let's say I'm transferring a large file like 100MB over to a folder. The program detects when the file arrives. However, I can't figure out how to know when the file is totally transferred over....
6
by: Sam Malone | last post by:
Am I just totally missing something here? I'm just new to VS.NET 2005 (using VB.NET) and ADO.NET. I get the impression that ADO.NET can't do what I'm used to doing with ADO (previous ADO...
33
by: Snis Pilbor | last post by:
With the "as if" rule in play, doesn't that effectively render the "register" keyword completely useless? Example: I make a silly compiler which creates code that goes out of its way to take a...
6
by: solargovind | last post by:
Hi, I need to accept in my Textbox ONLY 5 Alphaphetic 4 numeric and 1 Alphaperic. So, Totally 10 characters only should accept. And there should not be any space.. How can i Set validation rule...
3
by: Keith Willis | last post by:
A few people have been asking about variants of this recently, and I'm still not totally clear. A class Base declares, amongst other things, a method called func(). Because derived classes might...
2
by: Lee J | last post by:
Gang, I am self taught in C and fairly proficient for last 20 years. Don't program much, just little utilities for work. Been wanting to create windows forms and found MS VC++ Express. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
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...
0
marktang
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,...
0
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...
0
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,...
0
jinu1996
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 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.