Created
July 10, 2014 20:06
-
-
Save thomasballinger/3c227a06e59c4d4cbb63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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