Classes as namespaces?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat Mar 27 19:40:07 EDT 2010


kj wrote:
> What's the word on using "classes as namespaces"?

My only concern would be that classes do magical things with certain
types when you retrieve them as attributes (e.g. functions, property
descriptors), so you can't use one as a completely general purpose
transparent container. But for enum constants and the like this
isn't a problem.

If you're up for a bit of hackery, the following code tricks the
class statement into producing a module instead of a class:

from types import ModuleType

class MetaNamespace(ModuleType):

   def __init__(self, name, bases, dict):
     ModuleType.__init__(self, name)
     self.__file__ = __file__
     self.__dict__.update(dict)

Namespace = MetaNamespace.__new__(MetaNamespace)

class Foo(Namespace):

   ford = 42
   arthur = 88

print Foo
print Foo.__dict__

-- 
Greg



More information about the Python-list mailing list