954,549 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Global Variables in Functions

With the ease of argument passing to and from functions in Python, why would anyone want to use global variables. Isn't that an open invitation for mistakes to happen? Yet, I see code in threads here that abound with globals. I am a little confused here.

sneekula
Nearly a Posting Maven
2,427 posts since Oct 2006
Reputation Points: 961
Solved Threads: 212
 

Yes, I would say avoid globals like a pest! They are used by folks familiar with C/C++ programming, where passing arguments, particularly multiple arguments are a possible pointer nightmare.

Here is an example where a global might be useful ...
[php]x = 0

def incr_x() :
"""here x changes, so declare as global, or get an error"""
global x
x += 1
return x

print incr_x() # 1
print incr_x() # 2
print incr_x() # 3

# should x change within the program you can get surprises
# here x is inadvertently used in a loop
for x in range(78):
y = x + x

# later, you might expect 4
print incr_x() # 78 oops!
[/php]You can make it less likely to get global errors by assigning a recognizable namespace to all globals ...
[php]# a class to the rescue, to give all global variables a namespace
class Global(object):
"""declare all global variables here"""
x = 0
z = False

# now you can give all global variables a namespace (the class instance)
# use something like ww (from WorldWide) for a recognizable namespace for global variables
ww = Global()

print ww.x # 0
print ww.z # False

def incr_wwx() :
"""here ww.x changes, but does not have to be declared global"""
ww.x += 1
return ww.x

print incr_wwx() # 1
print incr_wwx() # 2
print incr_wwx() # 3
[/php]

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I am studying C++ right now in school (not my choice), and being used to Python the endless type declarations, memory allocations, and pointer this, and pointer that, to achieve very simple stuff, is cumbersome at best. Function arguments are handled with such elegance in Python!

bumsfeld
Nearly a Posting Virtuoso
1,445 posts since Jul 2005
Reputation Points: 404
Solved Threads: 184
 
They are used by folks familiar with C/C++ programming, where passing arguments, particularly multiple arguments are a possible pointer nightmare.

Although, I was taught to avoid globals when I learned C back last century.

Jeff

jrcagle
Practically a Master Poster
608 posts since Jul 2006
Reputation Points: 92
Solved Threads: 156
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You