Skip to content

Instantly share code, notes, and snippets.

@nkint
Forked from rik0/lazy_set.py
Created February 9, 2011 18:26
Show Gist options
  • Save nkint/818959 to your computer and use it in GitHub Desktop.
Save nkint/818959 to your computer and use it in GitHub Desktop.
import itertools as it
def setness(f):
        setness.calls = dict()
        def decorator(arg):
                seen = setness.calls.get( arg, set() )
                for i in seen: yield i
                for i in f(arg):
                        if i not in seen:
                                seen.add(i)
                                yield i
                setness.calls[arg] = seen
        return decorator
def silence_generator_already_executing(generator):
        try:
                for element in generator:
                        yield element
        except ValueError, e:
                pass
class lazy_set():
        def __init__(self, hudge_input):
                self._input = hudge_input
        @setness
        def __iter__(self):
                for i in self._input: yield i
        def update(self, iterable):
                self._input = it.chain(self._input,
                        silence_generator_already_executing(iterable))
        def add(self, obj):
                self._input = it.chain([obj], self._input)
import unittest
import lazy_set
class LazySetTest(unittest.TestCase):
def setUp(self):
self.lazy_set = lazy_set.lazy_set(xrange(1, 4))
self.starting_value = range(1, 4)
def testCreation(self):
self.assertEqual(
sorted(self.lazy_set),
self.starting_value
)
def testUpdate(self):
self.lazy_set.update(2* x for x in range(4, 10))
self.assertEqual(
sorted(self.lazy_set),
[1, 2, 3, 8, 10, 12, 14, 16, 18]
)
def testAdd(self):
self.lazy_set.add(5)
self.assertEqual(
sorted(self.lazy_set),
[1, 2, 3, 5]
)
def testUniqueness(self):
self.lazy_set.update(xrange(5))
self.lazy_set.update(xrange(3, 8))
self.assertEqual(
sorted(self.lazy_set),
range(8)
)
def testSelfUpdateWIter(self):
self.lazy_set.update(iter(self.lazy_set))
self.assertEqual(
sorted(self.lazy_set),
self.starting_value
)
def testSelfUpdateWOIter(self):
self.lazy_set.update(self.lazy_set)
self.assertEqual(
sorted(self.lazy_set),
self.starting_value
)
def testSelfUpdateNotLats(self):
self.lazy_set.update(iter(self.lazy_set))
self.lazy_set.update(xrange(5, 8))
self.assertEqual(
sorted(self.lazy_set),
range(1, 4) + range(5, 8)
)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment