Classes as namespaces?

J. Clifford Dyer jcd at sdf.lonestar.org
Sat Mar 27 08:04:59 EDT 2010


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?
> 
> ~K

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.

I would also not rule out letting your "pseudo-namespace" grow into a full-fledged class.  If you've got a method that makes sense with your class, use it.

class Cfg(object):
    spam = object()
	jambon = object()
    huevos = object()

	def get_animal(self, meat):
	    if meat == self.jambon:
			return 'pig'
		elif meat == self.huevos:
		    return 'chicken'
		elif meat = self.spam:
		    return 'spamalope'

Later, perhaps, you might refactor so that each meat type (OK so huevos aren't a meat) gets its own subclass, with a simple, one-line get_animal method.

Cheers,
Cliff



More information about the Python-list mailing list