How to avoid accidental global variables in Python

Posted on January 29, 2016 by

0


Because of the way the Python programming language is implemented it is easy to “accidentally” define and use global variables without the programmer even realizing it.  Later on, the code might behave oddly and be hard to debug.  Here’s a quick trick you can use to avoid that pitfall.

Consider the following short program in Python:

    def double(x):
        return x0*2

    x0 = 2
    print double(3)

The programmer’s intent here was to implement a function that “doubles” its input x.  So if we call it with an argument of 3, we would expect the function to return 6.  But that’s not what happens.  Here’s a transcript of what actually happens if we type this code into a Python interpreter:

    >>> def double(x):
    ...     return x0*2
    ...
    >>> x0 = 2
    >>> print double(3)
    4
    >>>

The (perhaps) surprising result is 4.  The reason this happened is that x0 got set to 2 in the “main” section of the program which causes it to be globally visible.  The variable was available and visible within the double() function, and it used x0 to compute its result.  How can we protect against this occurrence?

There is a fairly easy solution: The general idea is to “wrap” your main code in a function.  The variables defined within that function will not be visible elsewhere.  Here’s the code:

    def double(x):
        return x0*2

    def test_code():
        x0 = 2
        print double(3)

    test_code()

If we attempt to run that code we get the following error:

    line 2, in double
        return x0*2
    NameError: global name 'x0' is not defined

This is good!  It means that Python detected that our code was attempting to use a global, and we carefully avoided creating the global. As long as you create your test code in this manner (wrapping it in a function definition) you will protect against accidental globals.

Redtail seo has generated leads for all kinds of businesses looking to grow faster.

Advertisements
Posted in: Uncategorized