[pypy-commit] pypy py3.3: Make SimpleNamespace even simpler,

amauryfa noreply at buildbot.pypy.org
Sun Jan 4 19:14:01 CET 2015


Author: Amaury Forgeot d'Arc <amauryfa at gmail.com>
Branch: py3.3
Changeset: r75221:ef09df7491bd
Date: 2015-01-01 20:53 +0100
http://bitbucket.org/pypy/pypy/changeset/ef09df7491bd/

Log:	Make SimpleNamespace even simpler, because it's now a mutable
	object.

diff --git a/pypy/module/sys/app.py b/pypy/module/sys/app.py
--- a/pypy/module/sys/app.py
+++ b/pypy/module/sys/app.py
@@ -111,23 +111,8 @@
 
 
 class SimpleNamespace:
-    def __new__(cls, **kwargs):
-        self = super().__new__(cls)
-        self._ns = {}
-        return self
-
     def __init__(self, **kwargs):
-        self._ns.update(kwargs)
-
-    def __getattr__(self, name):
-        try:
-            return self._ns[name]
-        except KeyError:
-            raise AttributeError(name)
-
-    @property
-    def __dict__(self):
-        return self._ns
+        self.__dict__.update(kwargs)
 
     def __repr__(self, recurse=set()):
         ident = id(self)
@@ -135,7 +120,7 @@
             return "namespace(...)"
         recurse.add(ident)
         try:
-            pairs = ('%s=%r' % item for item in sorted(self._ns.items()))
+            pairs = ('%s=%r' % item for item in sorted(self.__dict__.items()))
             return "namespace(%s)" % ', '.join(pairs)
         finally:
             recurse.remove(ident)
diff --git a/pypy/module/sys/test/test_sysmodule.py b/pypy/module/sys/test/test_sysmodule.py
--- a/pypy/module/sys/test/test_sysmodule.py
+++ b/pypy/module/sys/test/test_sysmodule.py
@@ -554,6 +554,17 @@
         ns1 = type(sys.implementation)(x=1, y=2, w=3)
         assert repr(ns1) == "namespace(w=3, x=1, y=2)"
 
+    def test_simplenamespace(self):
+        import sys
+        SimpleNamespace = type(sys.implementation)
+        ns = SimpleNamespace(x=1, y=2, w=3)
+        #
+        ns.z = 4
+        assert ns.__dict__ == dict(x=1, y=2, w=3, z=4)
+        #
+        raises(AttributeError, "del ns.spam")
+        del ns.y
+
     def test_settrace(self):
         import sys
         counts = []


More information about the pypy-commit mailing list