Browse Source

Support iterator protocol in Serializer

tags/nilmdb-1.8.3^0
Jim Paris 8 years ago
parent
commit
6cd28b67b1
2 changed files with 43 additions and 0 deletions
  1. +14
    -0
      nilmdb/utils/serializer.py
  2. +29
    -0
      tests/test_serializer.py

+ 14
- 0
nilmdb/utils/serializer.py View File

@@ -91,6 +91,20 @@ def serializer_proxy(obj_or_type):
r = SerializerCallProxy(self.__call_queue, attr, self)
return r

# For an interable object, on __iter__(), save the object's
# iterator and return this proxy. On next(), call the object's
# iterator through this proxy.
def __iter__(self):
attr = getattr(self.__object, "__iter__")
self.__iter = SerializerCallProxy(self.__call_queue, attr, self)()
return self
def next(self):
return SerializerCallProxy(self.__call_queue,
self.__iter.next, self)()

def __getitem__(self, key):
return self.__getattr__("__getitem__")(key)

def __call__(self, *args, **kwargs):
"""Call this to instantiate the type, if a type was passed
to serializer_proxy. Otherwise, pass the call through."""


+ 29
- 0
tests/test_serializer.py View File

@@ -62,6 +62,28 @@ class Base(object):
eq_(self.foo.val, 20)
eq_(self.foo.init_thread, self.foo.test_thread)

class ListLike(object):
def __init__(self):
self.thread = threading.current_thread().name
self.foo = 0

def __iter__(self):
eq_(threading.current_thread().name, self.thread)
self.foo = 0
return self

def __getitem__(self, key):
eq_(threading.current_thread().name, self.thread)
return key

def next(self):
eq_(threading.current_thread().name, self.thread)
if self.foo < 5:
self.foo += 1
return self.foo
else:
raise StopIteration

class TestUnserialized(Base):
def setUp(self):
self.foo = Foo()
@@ -84,3 +106,10 @@ class TestSerializer(Base):
sp(sp(Foo("x"))).t()
sp(sp(Foo)("x")).t()
sp(sp(Foo))("x").t()

def test_iter(self):
sp = nilmdb.utils.serializer_proxy
i = sp(ListLike)()
print iter(i)
eq_(list(i), [1,2,3,4,5])
eq_(i[3], 3)

Loading…
Cancel
Save