Welcome, guest | Sign In | My Account | Store | Cart

A very simple, attribute-based namespace type (and one offspring). Everyone's written one of these...

Python, 19 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class SimpleNamespace:
    """A simple attribute-based namespace."""
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)
    def __repr__(self):
        keys = sorted(k for k in self.__dict__ if not k.startswith('_'))
        content = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
        return "{}({})".format(type(self).__name__, ", ".join(content))


class Namespace(SimpleNamespace):
    def __dir__(self):
        return sorted(k for k in self.__dict__ if not k.startswith('_'))
    def __eq__(self, other):
        return self.__dict__ == other.__dict__
    def __ne__(self, other):
        return self.__dict__ != other.__dict__
    def __contains__(self, name):
        return name in self.__dict__

In recipe 577887 you'll find a much more comprehensive namespace type. In contrast, this one will likely be more suitable to most use cases.

(In Python 3.3 and up, check out types.SimpleNamespace.)

Created by Eric Snow on Tue, 22 May 2012 (MIT)
Python recipes (4591)
Eric Snow's recipes (39)

Required Modules

  • (none specified)

Other Information and Tasks