PyMyth: Global variables are evil... WRONG!

Tim Chase python.list at tim.thechases.com
Tue Nov 12 18:45:09 CET 2013


On 2013-11-12 09:00, Rick Johnson wrote:
> Because the constant PI should never change. Sure we can
> argue about granularity of PI, but that argument has no
> weight on the fact that PI should be a constant.
> 
> By placing PI in the module "math", we are creating a pseudo
> interface. We (the creators) are "assuming" that PI will be a
> constant and never change, and the caller is assuming that
> pi will remain static,  but not only can it be mutated, it
> can be mutated globally.

But the module-scoping of "globals" is perfectly valid:

 >>> print(math.PI)
 3.1415926535897932
 >>> print(Magnum.PI)
 "Tom Selleck"

As an example from the stdlib of setting globals via a protocol,
locale.setlocale() does exactly this.  So I'm not sure why you have
your knickers in a knot.  Module-level items can be accessed
globally (though often a bad idea, or at least you have to beware of
side-effects where other things might break), and if you don't like
the "modules are not objects", someone in this thread already showed
you that you can insert objects/classes into the sys.modules and get
full getter/setter functionality with minimal trouble.

Finally, we're all (mostly) consenting adults here.  If I want to be
an idiot and

  math.PI = 3.14

and suddenly stuff breaks, I get to keep all the pieces my breakage
caused.

-tkc






More information about the Python-list mailing list