Get current class namespace.

Fredrik Lundh fredrik at pythonware.com
Wed Jul 16 08:07:42 EDT 2008


Robert Rawlins wrote:

> What’s the simplest way to access a classes namespace from within 
> itself. I want to use it in a custom __repr__() method so it prints the 
> current namespace for the class like package.module.class.

Name or namespace?  You can access the class name from an instance via 
the __class__ attribute:

 >>> class foo:
...     def __repr__(self):
...         return "<%s instance at %x>" % (
...             self.__class__.__name__, id(self)
...             )
...
 >>> foo()
<foo instance at c714e0>

The module the class was defined in is also available:

 >>> class foo:
...     def __repr__(self):
...         return "<%s.%s instance at %x>" % (
...             self.__class__.__module__, self.__class__.__name__,
...             id(self)
...         )
...
 >>> foo()
<__main__.foo instance at c9fbc0>

To get the namespace (that is, the collection of (name, value)
pairs that make up the class' contents), use vars(self.__class__)
(or vars(self), if you want the full instance).

</F>




More information about the Python-list mailing list