Permalink
Browse files

http://stackoverflow.com/questions/11036815/implicitely-bound-callabl…

  • Loading branch information...
1 parent 6357edc commit d3d1ef94db1975bddd1d9fe63ff6a2ae5b613552 @albertz committed Jun 14, 2012
Showing with 40 additions and 0 deletions.
  1. +40 −0 py-test-bounded-func.py
View
@@ -0,0 +1,40 @@
+#!/usr/bin/python
+
+# discussion: http://stackoverflow.com/questions/11036815/implicitely-bound-callable-objects-to-instance
+
+import itertools
+
+def bound(f):
+ def dummy(*args, **kwargs):
+ return f(*args, **kwargs)
+ return dummy
+
+class LFSeq: # lazy infinite sequence with new elements from func
+ def __init__(self, func):
+ self.evaluated = []
+ self.func = func
+ @bound
+ class __iter__:
+ def __init__(self, seq):
+ self.index = 0
+ self.seq = seq
+ def next(self):
+ if self.index >= len(self.seq.evaluated):
+ self.seq.evaluated += [self.seq.func()]
+ self.index += 1
+ return self.seq.evaluated[self.index - 1]
+
+def test():
+ f = itertools.count(0).next
+ s = LFSeq(f)
+ print s.__iter__
+ # LFSeq.__iter__(s) == s.__iter__() ?
+ i = iter(s)
+ #i = s.__iter__()
+ #i = LFSeq.__iter__(s)
+ print i
+ for c in range(10):
+ print next(i)
+
+if __name__ == '__main__':
+ test()

0 comments on commit d3d1ef9

Please sign in to comment.