Skip to content

Instantly share code, notes, and snippets.

@thomasballinger
Created July 10, 2014 20:06
Show Gist options
  • Save thomasballinger/3c227a06e59c4d4cbb63 to your computer and use it in GitHub Desktop.
Save thomasballinger/3c227a06e59c4d4cbb63 to your computer and use it in GitHub Desktop.
class LazyLength(object):
def __init__(self, data):
self.data = data
def __iter__(self):
len = 0
for x in self.data:
yield x
len += 1
self.len = len
def __len__(self):
if hasattr(self, 'len'):
return self.len
raise ValueError("IDK")
l = LazyLength(range(10))
len(l)
### Traceback (most recent call last):
### File "<input>", line 1, in <module>
### File "<input>", line 13, in __len__
### ValueError: IDK
for i in l:
print i
### 0
### 1
### 2
### 3
### 4
### 5
### 6
### 7
### 8
### 9
len(l)
### 10
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment