Python handles globals badly.

Michael Torrie torriem at gmail.com
Fri Sep 4 02:06:50 CEST 2015


On 09/03/2015 01:05 PM, tdev at freenet.de wrote:
> And a compiler can surely recognize if a defined var xxx outside is
> not a var yyy inside a function.

At issue here is the idea of Python namespaces and how Python uses them
in a consistent way with your code.  The consistency is that binding of
a name to an object within a function is in the function's namespace.
Makes things fast and simple.  To facilitate writing to the module's
namespace the global keyword is an elegant way of preserving
consistency. But this has been said a few times I'm sure so we're going
in circles here.

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

Not sure I follow you here.  What do the names programmers choose have
to do with it?  If I'm looking at a function, which should never be more
than a screen of code long, if I see a reference to a variable that has
never been assigned, I know it's defined in a parent scope.  If I see as
assignment, then I know it's local.  If I see the word global then I
know that any assignments are to the global namespace. Doesn't matter
what the name is.  It's consistent and explicit, which is one of
Python's mantras, so I feel justified in defending this
quirk/foible/feature of the language.

> My answer is clear: remove it.

But the global keyword serves a purpose.  It's just different from the
purpose you think you need.  I get the impression you'd rather bend
Python to your will, rather than work with it and learn the powerful
Python idioms, which is just going to end in frustration.  I don't think
anyone would support a PEP to change python as you suggest (and it
couldn't be done anytime soon until Python 4000 anyway). Seems a rather
Quixote-esque quest you are on here. Spend some time to understand how
Python variables differ from variables in other languages (most python
"variables" are names bound to immutable objects like numbers).

> [The same e.g. with switch statement: add it]

Switch is a nice-to-have thing, but definitely not essential. A PEP here
(probably already has been several) would at least be read anyway.
However, there are several idiomatic ways of accomplishing the same
thing that are often good enough and familiar to any Python programmer
out there.  Since functions are first-class objects, often a dispatch
table is the best way to go here.




More information about the Python-list mailing list