suggestions for functional style (singleton pattern?)

Michael Torrie torriem at gmail.com
Mon Mar 2 10:59:12 EST 2015


On 03/02/2015 03:19 AM, Fabien wrote:
> On 01.03.2015 06:05, Michael Torrie wrote:
>>   A module*is*  a singleton pattern, particularly one
>> that maintains state.  I use sometimes use this feature for sharing
>> config and other data between other modules (global state when it's
>> required).
> 
> I do this too, after some helping recommendations I got from this 
> discussion group. I find it neat to use a module for sharing config 
> states, but I always wondered: does this pattern fall into the "globals 
> are devil" category?

In traditional languages, globals were considered evil in part because
of the ambiguity they raised (a problem of scope, really).  In a
function if you see a reference to a variable, and if globals were used,
you then have confusion over whether the variable is local or global
(could be both if one covers the other).  And globals could be set from
anywhere.  Debugging and logical patterns become a lot harder with this
ambiguity and errors are introduced.

Modules don't have the same problems when used as a store for globals
for several reasons.  First, because they have a namespace associated
with them.  You can tell at a glance which name in your function is a
reference to this "global" module.  Now if you did do a "from module
import *" then you can't tell as easily what is coming from the module
and what is locally defined.  But the cool thing here is if you rebind a
variable imported from a module in your local namespace, it actually
doesn't change the "global" variable (attribute).  Instead it just
rebinds your local name.  So if you want to change an attribute in the
module, you have to refer to it via the module.attribute path.

Secondly, one should rarely write to a module's namespace from outside
that module (though you can).  Instead treat the module in an OOP
fashion, and write business methods to alter the module's state in a
specific way.  This encapsulation protects and insulates the module's
users from implementation details that could change from time to time.
Now I don't know of any way of implementing class-style properties on a
module as you can do in a class, but if that were needed you would write
a standard class and instantiate a singleton inside the module itself
perhaps.

As with all broad statements, saying globals are evil is simply not
always true.



More information about the Python-list mailing list