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.

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 ...

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!

You can make it less likely to get global errors by assigning a recognizable namespace to all globals ...

# 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

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!

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.