[Python-checkins] r54656 - sandbox/trunk/abc/abc.py sandbox/trunk/abc/test_abc.py
guido.van.rossum
python-checkins at python.org
Mon Apr 2 17:21:37 CEST 2007
Author: guido.van.rossum
Date: Mon Apr 2 17:21:36 2007
New Revision: 54656
Modified:
sandbox/trunk/abc/abc.py
sandbox/trunk/abc/test_abc.py
Log:
Experiment with adapters.
Modified: sandbox/trunk/abc/abc.py
==============================================================================
--- sandbox/trunk/abc/abc.py (original)
+++ sandbox/trunk/abc/abc.py Mon Apr 2 17:21:36 2007
@@ -288,6 +288,9 @@
class _MappingView:
+ def __new__(cls, *args):
+ return object.__new__(cls)
+
def __init__(self, mapping):
self._mapping = mapping
@@ -544,3 +547,39 @@
if h == -1:
h = -2
return h
+
+
+### ADAPTERS ###
+
+
+class AdaptToSequence(Sequence):
+
+ def __new__(cls, *args):
+ return Sequence.__new__(cls)
+
+ def __init__(self, adaptee):
+ self.adaptee = adaptee
+
+ def __getitem__(self, index):
+ return self.adaptee[index]
+
+ def __len__(self):
+ return len(self.adaptee)
+
+
+class AdaptToMapping(SizeableMapping):
+
+ def __new__(cls, *args):
+ return SizeableMapping.__new__(cls)
+
+ def __init__(self, adaptee):
+ self.adaptee = adaptee
+
+ def __getitem__(self, index):
+ return self.adaptee[index]
+
+ def __len__(self):
+ return len(self.adaptee)
+
+ def __iter__(self):
+ return iter(self.adaptee)
Modified: sandbox/trunk/abc/test_abc.py
==============================================================================
--- sandbox/trunk/abc/test_abc.py (original)
+++ sandbox/trunk/abc/test_abc.py Mon Apr 2 17:21:36 2007
@@ -38,6 +38,33 @@
htl = hash(tuple(l))
self.assertEqual(hcl, htl, repr((l, hcl, htl)))
+ def test_adapt_to_sequence(self):
+ a = abc.AdaptToSequence(range(10))
+ self.assertEqual(len(a), 10)
+ self.assertEqual(a[0], 0)
+ self.assertEqual(a[9], 9)
+ self.assertEqual(a[-1], 9)
+ self.assertEqual(list(a), range(10))
+ #self.assertEqual(a, range(10))
+ # Slicing isn't implemented correctly
+
+ def test_adapt_to_mapping(self):
+ a = abc.AdaptToMapping({1: 10, 2: 20})
+ self.assertEqual(len(a), 2)
+ self.assertEqual(a[1], 10)
+ self.assertEqual(a.get(2), 20)
+ self.assertEqual(a.get(3), None)
+ self.assertEqual(a.get(4, 42), 42)
+ self.assertEqual(1 in a, True)
+ self.assertEqual(2 in a, True)
+ self.assertEqual(3 in a, False)
+ self.assertEqual(set(a.keys()), {1, 2})
+ self.assertEqual(set(a.items()), {(1, 10), (2, 20)})
+ self.assertEqual(set(a.values()), {10, 20})
+ #self.assertEqual(a.keys(), {1, 2})
+ #self.assertEqual(a.items(), {(1, 10), (2, 20)})
+ #self.assertEqual(a.values(), {10, 20})
+
if __name__ == "__main__":
unittest.main()
More information about the Python-checkins
mailing list