Skip to content

Instantly share code, notes, and snippets.

@Zeturic
Created July 25, 2022 07:49
Show Gist options
  • Save Zeturic/be0ce7be62288db9aba15c093fe45420 to your computer and use it in GitHub Desktop.
Save Zeturic/be0ce7be62288db9aba15c093fe45420 to your computer and use it in GitHub Desktop.
generator -> iterable container
def classify(fn):
class Wrapper:
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __iter__(self):
yield from fn(*self.args, **self.kwargs)
return Wrapper
# example:
@classify
def load_cities_gen(path):
with open(path, encoding="UTF-8") as handle:
for line in handle:
city, count = line.split("\t")
yield city, int(count)
def load_cities_list(path):
return list(load_cities_gen(path))
def normalize(pop):
total = sum(x for _, x in pop)
for city, count in pop:
percent = 100 * count / total
yield city, percent
data = load_cities_gen("pop.tsv")
result = normalize(data)
print(next(result))
print(next(result))
print(next(result))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment