473,545 Members | 1,471 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with global variables

I'm having a vexing problem with global variables in Python. Please
consider the following Python code:

#! /usr/bin/env python

def tiny():
bar = []
for tmp in foo:
bar.append(tmp)
foo = bar

if __name__ == "__main__":
foo = ['hello', 'world']
tiny()

When I try to run this, I get:

Traceback (most recent call last):
File "./xtalk.py", line 11, in ?
tiny()
File "./xtalk.py", line 5, in tiny
for tmp in foo:
UnboundLocalErr or: local variable 'foo' referenced before assignment

For some reason, Python can't see the global variable "foo" in the
function tiny(). Why is that?

If I change the code to this:

#! /usr/bin/env python

def tiny():
for tmp in foo:
print tmp

if __name__ == "__main__":
foo = ['hello', 'world']
tiny()

I get this:

hello
world

All of a sudden, tiny() can see the global variable "foo". Very
confusing! Why is it that tiny() sometimes can, and sometimes can't,
see the global variable "foo"?

If anyone can enlighten me about what's going on with Python and
global variables, I would appreciate it!
Apr 2 '07 #1
9 2999
hg
Ed Jensen wrote:
#! /usr/bin/env python

def tiny():
bar = []
for tmp in foo:
bar.append(tmp)
foo = bar

if __name__ == "__main__":
foo = ['hello', 'world']
tiny()

Like this ?

#! /usr/bin/env python

def tiny():
* * bar = []
gobal foo
* * for tmp in foo:
* * * * bar.append(tmp)
* * foo = bar

if __name__ == "__main__":
* * foo = ['hello', 'world']
* * tiny()
hg

Apr 2 '07 #2
Ed Jensen a écrit :
I'm having a vexing problem with global variables in Python. Please
consider the following Python code:

#! /usr/bin/env python

def tiny():
bar = []
for tmp in foo:
bar.append(tmp)
foo = bar

if __name__ == "__main__":
foo = ['hello', 'world']
tiny()

When I try to run this, I get:

Traceback (most recent call last):
File "./xtalk.py", line 11, in ?
tiny()
File "./xtalk.py", line 5, in tiny
for tmp in foo:
UnboundLocalErr or: local variable 'foo' referenced before assignment

For some reason, Python can't see the global variable "foo" in the
function tiny(). Why is that?

If I change the code to this:

#! /usr/bin/env python

def tiny():
for tmp in foo:
print tmp

if __name__ == "__main__":
foo = ['hello', 'world']
tiny()

I get this:

hello
world

All of a sudden, tiny() can see the global variable "foo". Very
confusing! Why is it that tiny() sometimes can, and sometimes can't,
see the global variable "foo"?

If anyone can enlighten me about what's going on with Python and
global variables, I would appreciate it!
To complete hg reply, Python compile your tiny function which contains a
foo assignment. As foo is not defined "global", it is considered to be
local. So the error when you tries to iterate throught foo before
assigning it. And so the solution to add "global foo" before using it.

A+

Laurent.
Apr 2 '07 #3
Laurent Pointal wrote:
And so the solution to add "global foo" before using it.
Didn't you read his final question?

| All of a sudden, tiny() can see the global variable "foo". Very
| confusing! Why is it that tiny() sometimes can, and sometimes
| can't, see the global variable "foo"?

I have no explanation for this, but I'm interested in one, too.

Regards,
Björn

--
BOFH excuse #422:

Someone else stole your IP address, call the Internet detectives!

Apr 2 '07 #4
Bjoern Schliessmann wrote:
Laurent Pointal wrote:
>And so the solution to add "global foo" before using it.

Didn't you read his final question?

| All of a sudden, tiny() can see the global variable "foo". Very
| confusing! Why is it that tiny() sometimes can, and sometimes
| can't, see the global variable "foo"?

I have no explanation for this, but I'm interested in one, too.
It doesn't happen "all of a sudden", it happens when the assignment to
foo is removed from the function definition. The interpreter therefore
no longer regards foo as a local variable.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings http://holdenweb.blogspot.com

Apr 2 '07 #5
Bjoern Schliessmann schreef:
Laurent Pointal wrote:
>And so the solution to add "global foo" before using it.

Didn't you read his final question?

| All of a sudden, tiny() can see the global variable "foo". Very
| confusing! Why is it that tiny() sometimes can, and sometimes
| can't, see the global variable "foo"?

I have no explanation for this, but I'm interested in one, too.
Within functions Python can read from global variables, even without a
'global' statement. Complications only arise when you try to write to
it: in that case Python assumes it is a local variable instead of a global.

It surprised me a bit when I first found out about this: I would have
thought that Python would threat it as a local throughout the function
until the function assigns something to it. That's not what happens: if
the function assigns to it, *all* mentions of the variable are
considered local.

--
If I have been able to see further, it was only because I stood
on the shoulders of giants. -- Isaac Newton

Roel Schroeven
Apr 2 '07 #6
On Apr 2, 5:29 pm, Bjoern Schliessmann <usenet-
mail-0306.20.chr0n.. .@spamgourmet.c omwrote:
Laurent Pointal wrote:
And so the solution to add "global foo" before using it.

Didn't you read his final question?

| All of a sudden, tiny() can see the global variable "foo". Very
| confusing! Why is it that tiny() sometimes can, and sometimes
| can't, see the global variable "foo"?

I have no explanation for this, but I'm interested in one, too.

Regards,

Björn
Laurent Pointal did explain this. "foo" is considered to be a local
variable (scope limited to the function) if it's being assigned to in
a function and there's no "global foo" statement. So even the "foo"
before the actual assignment will refer to the local variable. But the
local variable hasn't been assigned yet at that point and an exception
is thrown. Yes, one could have a perfectly working function, then add
an innocent-looking assignment statement at the very end of the
function, and suddenly you'd get an exception thrown at the beginning
of the function where that variable is used - Far away from the place
where the modification was made.

Why does it work like this? Couldn't it be somehow more uniform or
less surprising?

Well, if one had to define "global foo" even when one were to just
read the variable foo, that'd be a pain in the ass. You'd have to use
"global math" to use math module in a function and "global
anotherFunction " to call anotherFunction , and so on. There's plenty of
stuff in the global scope that you don't normally assign to.

Another option would be to scrap "global" keyword and let "foo = bar"
do an assignment to the global variable if a global variable named
"foo" exists, but create (or assign) to a function local variable if
it doesn't exist. That'd work but programming would be horrible. Now
you'd have to know all the symbols that exist at the global scope,
because if you accidentally accessed a global variable instead of
local, your function would probably have undesirable side-effects.

Now, name clashes could be solved with a naming convention (which
could be enforced at the language level). It could be possible that
all accesses to global scope would have to be prefixed by some symbol
like $. E.g. "$foo = 4; foo = 6" where former assigns to global foo,
latter to local foo. That's one option that might work and be somewhat
readable.. But not a good tradeoff IMO, considering how rarely global
assignment is needed and how often global variables are read.

A remaining option is to use different operator for assignment and
initialization. So you'd have to do e.g. "a := 4; a = 7". I'm not sure
Pythonistas would prefer this either, although many other languages
choose this route (through lets or declarations typically).

Apr 2 '07 #7
Ed Jensen <ej*****@visi.c omwrote:
I'm having a vexing problem with global variables in Python.
<SNIP>

Thanks to everyone who replied. The peculiar way Python handles
global variables in functions now makes sense to me.
Apr 2 '07 #8
Bjoern Schliessmann wrote:
Laurent Pointal wrote:
>And so the solution to add "global foo" before using it.

Didn't you read his final question?
Yes, and i replies: "which contains a foo assignment. As foo is not
defined "global", it is considered to be local. "

Maybe my explanation was not clear enough with variable foo to be considered
local because there is an *assignment* to foo.

A+

Laurent.
Apr 2 '07 #9
Laurent Pointal wrote:
Yes, and i replies: "which contains a foo assignment. As foo is
not defined "global", it is considered to be local. "

Maybe my explanation was not clear enough with variable foo to be
considered local because there is an *assignment* to foo.
Yep, thanks for the clarification. After four replies and despite
weird conjugations, I've definitely got it now ... ;)

Regards,
Björn

--
BOFH excuse #113:

Root nameservers are out of sync

Apr 2 '07 #10

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

Similar topics

3
2804
by: Gary | last post by:
I am having a strange problem that I cannot solve. I have an asp page that I use for a user to login and gain access to other pages. When the user logs in I set a couple of session variables like Session("UserType") = "Sales". Then based on the Session("UserType") I use response.redirect to take the user to a specific page. The logic and...
10
17836
by: Matt | last post by:
Greetings, What are people's thoughts on global variables in C++? Why are we taught not to use them in programming? Is it true that if you are running two copies of the C program one copy can overwrite another copies global variable? I know that you could overwrite a value in a global variable from a function, but you could also do that if...
4
24163
by: Andrew V. Romero | last post by:
I have been working on a function which makes it easier for me to pull variables from the URL. So far I have: <script language="JavaScript"> var variablesInUrl; var vArray = new Array(); function loadUrlVariables() { varString = location.search;
2
2167
by: Anand Subramanian | last post by:
Hi, Can someone explain the differences(setup, pre-main() setup/initialization) between global variables in a C++ and a C program? The global variables I used are uninitialized. I have a test.o which declares a global int " int xxx;". Now I link test.o to a FreeBSD kernel module which then tries to access xxx. If test.o was compiled from C...
2
5173
by: Bryan Parkoff | last post by:
….I would like to know which is the best optimization to use global variable or global struct. I always tell C/C++ Compiler to turn on optimization. ….I use underscore between first name and second name for better readable. After optimization, global variables might be misaligned because each global variables must be converted to 32 bits,...
2
4432
by: ajikoe | last post by:
Hi, I tried to follow the example in swig homepage. I found error which I don't understand. I use bcc32, I already include directory where my python.h exist in bcc32.cfg. /* File : example.c */ #include <time.h>
4
2331
by: Harry | last post by:
Good Day, I am writing a code for the H.264 Video codec.I am using VC++ compiler,but programming is in c only.I have grouped the related global variables under one structure in a header file called global.h.Like this i have two three structures in global.h. To initialise the structure members in global.h,I declared structure variables...
2
3140
by: sorobor | last post by:
dear sir .. i am using cakephp freamwork ..By the way i m begener in php and javascript .. My probs r bellow I made a javascript calender ..there is a close button ..when i press close button then the calender gone actually i want if i click outside off the calender then it should me removed ..How kan i do this ... Pls inform me as early...
3
1627
by: =?Utf-8?B?dGhlamFja29mYWxs?= | last post by:
I have a few global variables and a function that gets called multiple times to complete a single transaction and uses the variables. The function gets different notifications. When the function receives a final notification, that where I need to release the global variables. I don't have control over when the function gets called because...
2
225
by: Anthony Kuhlman | last post by:
Pythoners, I'm having trouble understanding the behavior of global variables in a code I'm writing. I have a file, test.py, with the following contents foo = def goo(): global foo foo = foo.append(2)
0
7465
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7398
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
7805
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
7416
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...
1
5325
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
3449
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
3441
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1878
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
1
1013
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.