PyMyth: Global variables are evil... WRONG!

Rick Johnson rantingrickjohnson at gmail.com
Tue Nov 12 16:05:25 CET 2013


On Tuesday, November 12, 2013 8:12:10 AM UTC-6, jongiddy wrote:

> Can you please give an example where having a module
> provide a global variable would work better than any of:
> [snip]

Well my point is that the attributes of any Python module
are "emulating" globals already. The fact that we have to
mutate them via a "psuedo" interface makes us "falsely"
believe we are using an interface -- but we aren't!

 PYTHON MADE ACCESSING GLOBAL VARIABLES MORE DIFFICULT!

As example. I could import the math module and start
fiddling with attributes. Let's say for example i can change
the value of math.pi. Most people would probably say "what's
the problem with that?", here, let me show you.

    # mod1.py
    print "mod1.py"
    import math
    math.pi = "tasty"

    # mod2.py
    print "mod2.py"
    import math
    print ' value of math.pi is:', math.pi
    radius = 10
    math.pi * radius

    #modmain.py
    import mod1
    import mod2
    print dir(mod1)
    print dir(mod2)

When you run "modmain.py" you will see that not only have we
changed the global variable "pi" to a string, but thanks to
a dumb overloading of the multiply operator, python will
happily give use the wrong answer -- but that's another
problem, let's stay focused on the "global" problem for now!

When i type "math.pi", i "feel" as though i'm accessing an
interface, BUT I'M NOT! If i was indeed accessing a TRUE
interface, the interface would have thrown a Type error for
attempting to assign a value of type string to what should
only be a float. The interface would have protected it's
internal data from corruption, but it didn't.

  BECAUSE IT'S NOT AN INTERFACE!

It's just a dumb namespace with no exposed hooks to control
it's underlying behavior.

  MY POINT IS:

Python designers act like globals are SO evil, but then they
give us modules which are containers for global variables,
and now the globals contained within those modules are
wolves in sheep's clothing. Are they just trying to fool
themselves, or fool us?

  FOOD FOR THOUGHT:

What's worse? A wolf? Or a wolf in sheep's clothing?



More information about the Python-list mailing list