[pypy-commit] lang-scheme default: Turn W_Nil and W_Boolean into singleton classes

boemmels noreply at buildbot.pypy.org
Sat Dec 3 18:22:02 CET 2011


Author: Juergen Boemmels <boemmels at web.de>
Branch: 
Changeset: r27:d86450ba30f6
Date: 2011-12-03 15:37 +0100
http://bitbucket.org/pypy/lang-scheme/changeset/d86450ba30f6/

Log:	Turn W_Nil and W_Boolean into singleton classes

diff --git a/scheme/object.py b/scheme/object.py
--- a/scheme/object.py
+++ b/scheme/object.py
@@ -102,25 +102,49 @@
 w_ellipsis = symbol("...")
 
 class W_Boolean(W_Root):
+    def __new__(cls, val):
+        if val:
+            return w_true
+        else:
+            return w_false
+
     def __init__(self, val):
-        self.boolval = bool(val)
+        pass
+            
+class W_True(W_Boolean):
+    _w_true = None
+    def __new__(cls, val):
+        if cls._w_true is None:
+            cls._w_true = W_Root.__new__(cls)
+        return cls._w_true
+
+    def __init__(self, val):
+        assert val
 
     def to_repr(self):
-        if self.boolval:
-            return "#t"
+        return "#t"
+    to_string = to_repr
+
+w_true = W_True(True)
+
+class W_False(W_Boolean):
+    _w_false = None
+    def __new__(cls, val):
+        if cls._w_false is None:
+            cls._w_false = W_Root.__new__(cls)
+        return cls._w_false
+
+    def __init__(self, val):
+        assert not val
+
+    def to_repr(self):
         return "#f"
-
     to_string = to_repr
 
     def to_boolean(self):
-        return self.boolval
+        return False
 
-    def eqv(self, w_obj):
-        if isinstance(w_obj, W_Boolean):
-            return self.boolval is w_obj.boolval
-        return False
-    eq = eqv
-    equal = eqv
+w_false = W_False(False)
 
 class W_String(W_Root):
     def __init__(self, val):
@@ -267,6 +291,12 @@
     pass
 
 class W_Nil(W_List):
+    _w_nil = None
+    def __new__(cls):
+        if cls._w_nil is None:
+            cls._w_nil = W_Root.__new__(cls)
+        return cls._w_nil
+    
     def __repr__(self):
         return "<W_Nil ()>"
 
diff --git a/scheme/test/test_object.py b/scheme/test/test_object.py
--- a/scheme/test/test_object.py
+++ b/scheme/test/test_object.py
@@ -68,6 +68,8 @@
     w_nil = W_Nil()
     assert w_nil.to_boolean() is True # this is Scheme not LISP
     assert w_nil.to_repr() == "()"
+    w_nil2 = W_Nil()
+    assert w_nil is w_nil2
 
 def test_pair():
     c1 = W_Integer(1)
diff --git a/scheme/test/test_parser.py b/scheme/test/test_parser.py
--- a/scheme/test/test_parser.py
+++ b/scheme/test/test_parser.py
@@ -21,7 +21,7 @@
     elif isinstance(w_obj, W_Character):
         return w_obj.chrval
     elif isinstance(w_obj, W_Boolean):
-        return w_obj.boolval
+        return w_obj.to_boolean()
     elif isinstance(w_obj, W_Pair):
         result = []
         while not isinstance(w_obj, W_Nil):


More information about the pypy-commit mailing list