Global Variables in OOP and Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Dec 30 22:56:53 EST 2005


On Fri, 30 Dec 2005 20:00:51 -0500, Mike Meyer wrote:


>> The other way I thought of is to create a separate class that consists
>> of the variables and to use the
>>
>> from <file name> import *
>>
>> in all of the files (namespaces) where it is needed.
> 
> Except for one detail, this is a Pythonesque method. The detail is
> that "from <module> import *" is generally considered a bad
> idea. There are two reasons for this:

Agree about from module import * being bad, but it is still generally poor
practice for the same reason using global variables is generally poor
practice.


> 1) Blindly adding everything in a module to your namespace is liable
> to cause collisions. If the module you're doing this to is stable,
> this isn't much of a problem.

How does stability come in to it? If I have a module spam with an object
parrot, and it imports another module with an object parrot, there will be
a namespace collision regardless of whether the two modules are 0.1 alpha
versions or 3.2 stable versions. If the collision is subtle enough, the
bug might take years to discover.

If you mean that namespace collisions are less likely to have remained
undetected by the time the modules reach stability, then I will cautiously
agree with you. But if you mean what you say, that collisions are not a
problem for stable modules, then I disagree strongly.



> 2) It makes finding where a variable came from harder. Having to
> search extra modules for globals is a pain. If the exported names have
> a prefix on them to identify the module, that goes away. But in that
> case, you might as well do "import <module> as <prefix>", and leave
> the prefix off the variable names in the module.

Agreed.


> A better way to do this is to give your module a name that denotes
> it's function ("config", for instances, or maybe even "globals") and
> use that.

And an even better way is to use the absolute minimum number of global
variables possible. In general, that means global functions and classes
Good, global instances and other data Bad.

In other words, any time you feel the need to put "global name" in a
function or method, think twice, have a cold shower, do fifty push-ups,
and then re-write the function to not use globals. 99 times out of a 100,
you'll end up with better code.


-- 
Steven.




More information about the Python-list mailing list