Suppose an api returns a python generator that yields Person objects
# Example person class
# p = Person()
# p.name = "Jane Doe"
# p.age = 25
people = api.get_people() # returns generator
for person in people:
print(person.name)
But my consuming code wants an iterator of names.
Is it possible to convert or wrap the original generator into a new generator that yields an attribute of the object rather than the object itself? That is, yields name strings rather than person objects? If so, how?
names = name_getter(api.get_people()) # somehow wrap into a new generator?
for name in names:
print(name)
Turns out it's easy, this makes a new generator that wraps the original one:
def get_names():
for person in api.get_people():
yield person.name
Can also be achieved with Generator expressions (aka generator comprehensions):
# (<expression> for <var> in <iterable> if <condition>)
names = (p.name for p in api.get_people())