Classes as namespaces?
philip at semanchuk.com
Sat Mar 27 14:26:40 CET 2010
On Mar 27, 2010, at 8:04 AM, J. Clifford Dyer wrote:
> On Fri, Mar 26, 2010 at 02:49:02PM +0000, kj wrote regarding Classes
> as namespaces?:
>> What's the word on using "classes as namespaces"? E.g.
>> class _cfg(object):
>> spam = 1
>> jambon = 3
>> huevos = 2
>> breakfast = (_cfg.spam, _cfg.jambon, _cfg.huevos)
>> Granted, this is not the "intended use" for classes, and therefore
>> could be viewed as a misuse ("that's what dictionaries are for",
>> etc.). But other than this somewhat academic objection[*], I really
>> can see no problem with using classes in this way.
>> And yet, I've come across online murky warnings against using
>> classes as "pseudo-namespaces". Is there some problem that I'm
>> not seeing with this technique?
> I don't see anything wrong with this, except that I would clean it
> up in a couple ways. Like other posters, I would give the class a
> proper class name (Cfg).
> I also would not assign integers to spam, jambon, or huevos.
> Instead I would assign each a bare object(). That way you won't get
> unexpected interactions with other constants outside the class. An
> object() is equal only to itself.
What I like about this method is that it will break the bad habit I
see in junior programmers of making assumptions about the value of the
constant. For instance, if they see that Cfg.JAMBON = 3 and hardcode 3
in their code somewhere, that will work fine until someone re-orders
the constants. Using object() instead forces them to use Cfg.JAMBON
since the value will (probably) change with every run of the program.
It will also discourage bugs-waiting-to-happen like this:
if breakfast > Cfg.SPAM:
print "Good news, breakfast is jambon or huevos"
More information about the Python-list