Global Variables in OOP and Python

Mike Meyer mwm at mired.org
Fri Dec 30 20:00:51 EST 2005


"newbie" <solaris_1234 at yahoo.com> writes:
> So far, I have approached the problem by making the variables
> attributes of one class and passing instances of the class as variables
> to the other class' methods.

That's the standard way to do it in OO languages.

> 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:

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.

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.

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.

> Are the two ideas presented above acceptable? If so, is one better than
> the other from an OOP POV?

With the one change, they are. From an OO point of view, they're
almost identical. In Python, a module is an object, so the difference
is whether you want to instantiate a custom class to hold your
globals, or use the builtin module type for that purpose.

         <mike

-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list