Classes as namespaces?

Philip Semanchuk philip at
Fri Mar 26 16:08:35 CET 2010

On Mar 26, 2010, at 10:49 AM, kj wrote:

> 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 hope it's not problematic; I use it all the time.

A few differences about the way I do it:
- I respect PEP 8 for the class name (CamelCaps)
- If the attributes are supposed to be constants, I capitalize the  
- I often add NONE with a value of zero so that bool(MyClass.NONE)  
will evaluate to False and everything else will be True

Here's an example from my code:

class Apodization(object):
     """ Apodization constants """
     # These constants are arbitrary and may change.
     # However bool(NONE) is guaranteed to be False
     NONE = 0
     GAUSSIAN = 1


More information about the Python-list mailing list