473,569 Members | 2,789 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can local function access local variables in main program?

I am confused by the following program:

def f():
print x
x=12345
f()

result is:
>>>
12345

however:
def f():
print x
x=0

x=12345
f()

result is:
Traceback (most recent call last):
File "...\test.p y", line 5, in ?
f()
File "...\test.p y", line 2, in f
print x
UnboundLocalErr or: local variable 'x' referenced before assignment
I am using
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
on win32
I also tested it on python 2.5, which gives the same result.

Nov 3 '07 #1
8 3870
On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:
def f():
print x
x=0

x=12345
f()

result is:
Traceback (most recent call last):
File "...\test.p y", line 5, in ?
f()
File "...\test.p y", line 2, in f
print x
UnboundLocalErr or: local variable 'x' referenced before assignment

When Python compiles your function f(), it sees that you have assigned to
x, and that there is no line "global x", so it knows that x is a local
variable.

But when you call f(), you try to print x before the local x has a value
assigned to it. Hence the (accurate but hardly user-friendly) error
message.

You can also do this:
>>help(UnboundL ocalError)
Help on class UnboundLocalErr or in module exceptions:

class UnboundLocalErr or(NameError)
| Local name referenced but not bound to a value.

As far as I know, there is no way to read the value of global x if and
only if local x doesn't exist.

--
Steven
Nov 3 '07 #2
On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:
I am confused by the following program:

def f():
print x
x=12345
f()

result is:
>>>>
12345
If python can't discover x in your current scope and you do not bind to
it there, it will automatically access that global name x.
however:
def f():
print x
x=0

x=12345
f()

result is:
Traceback (most recent call last):
File "...\test.p y", line 5, in ?
f()
File "...\test.p y", line 2, in f
print x
UnboundLocalErr or: local variable 'x' referenced before assignment
Here, you *do* assign to x in this scope so this is essentially the same
as the following (without any function scope)::

print x
x = 12345

This can't work since you haven't used x when you try to print it.

You can make this work using the `global` statement::
>>def foo():
... global x
... print x
... x = 0
...
>>x = 12345
print x
12345
>>foo()
12345
>>print x
0

See more in the `lexical reference about the global statement <http://
docs.python.org/ref/global.html>.

HTH,
Stargaming
Nov 3 '07 #3
Sullivan WxPyQtKinter wrote:
UnboundLocalErr or: local variable 'x' referenced before assignment
For your reference:

http://groups.google.de/groups?q=gro...oundLocalError

Regards,
Björn

--
BOFH excuse #12:

dry joints on cable plug

Nov 3 '07 #4
Actually I am quite satisfied with and error, which is my expectation.
But the implicit global variable access seems quite uncomfortable to
me. Why is that necessary?

On Nov 3, 3:39 am, Stargaming <stargam...@gma il.comwrote:
On Sat, 03 Nov 2007 07:18:17 +0000, Sullivan WxPyQtKinter wrote:
I am confused by the following program:
def f():
print x
x=12345
f()
result is:
12345

If python can't discover x in your current scope and you do not bind to
it there, it will automatically access that global name x.
Nov 3 '07 #5
Stargaming wrote:
You can make this work using the `global` statement::
>>def foo():
... global x
... print x
... x = 0
Is there any way to disable global for x? Something like that:
>>x = 12345
def foo():
.... global x
.... print x
.... noglobal(x) # ???
.... x = 0 # now this is local x
>>foo()
12345
>>print x
12345

--
In pariete - manus et crus cerebrumque

Nov 3 '07 #6
On Nov 3, 2007, at 5:32 PM, Pawel wrote:
Stargaming wrote:
>You can make this work using the `global` statement::
>>>>def foo():
... global x
... print x
... x = 0

Is there any way to disable global for x? Something like that:
>>>x = 12345
def foo():
... global x
... print x
... noglobal(x) # ???
... x = 0 # now this is local x
>>>foo()
12345
>>>print x
12345
Why would you need to do that? It would be confusing. Just use a
different variable name for the local.

Erik Jones

Software Developer | Emma®
er**@myemma.com
800.595.4401 or 615.292.5888
615.292.0777 (fax)

Emma helps organizations everywhere communicate & market in style.
Visit us online at http://www.myemma.com
Nov 3 '07 #7
Pawel wrote:
Is there any way to disable global for x? Something like that:
>>>x = 12345
def foo():
... global x
... print x
... noglobal(x) # ???
... x = 0 # now this is local x
Not really. Why don't you choose meaningful variable names? You
practically save nothing by using fewer names.

Regards,
Björn

--
BOFH excuse #423:

It's not RFC-822 compliant.

Nov 4 '07 #8
On 2007-11-03, Dennis Lee Bieber <wl*****@ix.net com.comwrote:
On Sat, 03 Nov 2007 17:30:45 -0000, Sullivan WxPyQtKinter
<su*********** @gmail.comdecla imed the following in comp.lang.pytho n:
>Actually I am quite satisfied with and error, which is my expectation.
But the implicit global variable access seems quite uncomfortable to
me. Why is that necessary?

Would you want to have to write things like:
Well it would be explicit and explicit is better than implicit.
import os
import os.path
import sys

def dFunc(more):
return "The full path of the item is: %s" % more

def aFunc(something ):
global os.path
global sys
global dFunc
sys.stdout.writ e(dFunc(os.path .join("nonsense ", something)))

Your "variable" follows the same logic used for name look ups of all
items -- "read" access will, after exhausting the local scope, search
the module level names (note that you don't need "global" to modify a
mutable object in module level -- it is only the rebinding of the name
itself that needs "global")
--
Antoon Pardon
Nov 8 '07 #9

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

Similar topics

15
401
by: John Doe | last post by:
Hi all, I know the standard doesn't care about threads (wrongly :-) But in current compilers implementation, is the "list" which holds count of the occupied and free heap addresses SHARED among various threads or not? I don't know if I was clear: Case1: the list which holds count of what is free and what is occupied is SHARED among all...
12
3264
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
2
4190
by: Paul M | last post by:
Hi, This is on an AS/400 which can be a little strange but I think the basic question is portable. I have a (non-C) program that needs to make series of calls to some C programs/functions. The problem is that I need to initialise certain variables within the first C program called and then use them in subsequent calls to other C...
15
1622
by: MackS | last post by:
The system I am working on supports a subset of C99, among which "standard-compliant VLAs". I've already learnt that VLAs can't have global scope. My question is whether I can safely declare a (local) VLA to have as its dimension a global variable of type int: short dim; int main(void)
23
3978
by: Timothy Madden | last post by:
Hello all. I program C++ since a lot of time now and I still don't know this simple thing: what's the problem with local functions so they are not part of C++ ? There surely are many people who will find them very helpfull. gcc has them as a non-standard option, but only when compiling C language code, so I'm afraid there might be some...
7
2326
bvdet
by: bvdet | last post by:
I provide shop drawings to structural steel fabricators with SDS/2 software (http://sds2.com) by Design Data (DD). I am not a programmer by education or trade and started writing scripts about 5 years ago. DD has a script interface with Python in the 3D model which is very useful in production. Part of the Python interface includes a dialog box...
1
1444
by: coolindienc | last post by:
I converted this program from using global variables to local variables. When I did that my while loop stopped working in my main function(module). Anyone, any idea why? I underlined the area where I think the problem occured after my changes. Old Code working FINE from math import * def menu(): global menuSel print "\nSlect...
1
1780
by: coolindienc | last post by:
I converted this program from using global variables to local variables. When I did that my while loop stopped working in my main function(module). Anyone, any idea why? I underlined the area where I think the problem occured after my changes. Old Code working FINE from math import * def menu(): global menuSel print "\nSlect...
55
6174
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in C# in some way? Or maybe no, because it is similar to a global variable (with its scope restricted) which C# is dead against? Zytan
0
7612
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...
0
8120
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7672
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...
0
7968
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...
1
5512
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...
0
5219
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...
0
3653
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...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
937
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...

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.