Python handles globals badly.

Michael Torrie torriem at gmail.com
Tue Dec 2 22:13:25 EST 2014


On 12/02/2014 07:27 PM, Skybuck Flying wrote:
> Excuse is: "bad programming style".
> 
> I don't need snot telling me how to program after 20 years of programming 
> experience.
> 
> This is so far the only thing pissing me off in python.
> 
> Now I have to declare "global" in front of these variables every where I 
> want to use em:

Only if you want to overwrite them, though.  Python has support for any
number of programming paradigms.  That many global variables is
screaming for some kind of organization and Python has good mechanisms
for doing this in a much neater way. Might I suggest you use a namespace
instead?  Put all your "globals" in a module, and refer to them via the
module.  For example (converting to pep8 which looks better to me):

import globals as g

def some_func():
   g.ship_ability_distribute_shield_power = 5

A whole lot cleaner than trying to use the global keyword everywhere.

If you've really been programming for 20 years, surely you're familiar
with programming patterns.  The fact that you have 6 variables all
prefixed with "ShipAbility" should suggest something to you. Like maybe
all of these attributes could be encapsulated in one "ship" object.
Python is very flexible in how you use objects.  You can program in
strict java-style if you want, or adopt a more freeform approach:

ship = object()
ship.ability = object()
ship.ability.distribute_shield_power = 5
etc.





More information about the Python-list mailing list