Created
December 28, 2015 14:01
-
-
Save andreisoriga/74a506d3cab5c0aa32d7 to your computer and use it in GitHub Desktop.
Generators
This file contains hidden or 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
| # return a generator instead of a list | |
| def interesting_lines(file): | |
| for fline in file: | |
| fline = fline.strip() | |
| if fline.startswith('#'): | |
| continue | |
| if not fline: | |
| continue | |
| yield fline | |
| with open('file.ini') as file: | |
| for line in interesting_lines(file): | |
| print(line) | |
| # Make an object iterable | |
| class ToDoList: | |
| def __init__(self): | |
| self.tasks = [] | |
| def __iter__(self): | |
| return iter(self.tasks) | |
| todo = ToDoList() | |
| for task in todo: | |
| print(task) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment