Python handles globals badly.

Steven D'Aprano steve at
Fri Sep 4 04:27:01 CEST 2015

On Fri, 4 Sep 2015 05:05 am, tdev at wrote:

> Or does anyone really name a global var xxx and a function var xxx?
> I am sure no one at all will do it. I dont want read such a code.

You should reflect on the purpose of namespaces and local variables.

Some programming languages do not distinguish local and global variables.
There are only variables, and they are shared by the entire program. That
is terrible for encapsulation, because every time you use a variable, you
have to stop and think whether that name is already being used *anywhere*

def function(x):
    y = x + 1

What if y is being used somewhere else? You have just over-written the value
of y that another part of the program relies on.

Instead, most languages over the last 40 or 50 years have separate
namespaces for variables. Each function's local variables are separate from
every other function's locals: writing "y = x + 1" inside a function
*cannot possibly* affect another function, if y is a local variable.

So when writing a function, and creating local variables, you do not need to
care whether the names you use have been used elsewhere. There is no need
for every name in the entire program to be unique. The only time you need
care is to avoid using the same name for a local and a global *that you
intend to use*. If you don't intend to use it, there is no possible harm.

Think about a program where last week I have written a function:

def function(x):
    y = x + 1

y here is local to the function.

Most commercial programs have dozens or hundreds of developers working on
them (for something big like Microsoft Windows). Open source software might
have thousands of developers. So today you come along and work on the same
program as me, and you add a global variable:

y = 999

What do you expect to happen? Do you think it is a good idea for your change
*outside* of the function to suddenly change the meaning of the line 
"y = x + 1" *inside* the function?

Fortunately, in Python, nothing changes. My function continues to work as
before. You adding a global variable that happens to have the same name as
one of my local variables does not break my function. Local variables are
completely isolated to the function they are in.

Which is exactly the way it should be. Worrying about local variables using
the same name as globals is silly. The only time that is harmful is if you
intend to use the global in a function but have a local of the same name.


More information about the Python-list mailing list