-1

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)
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
User
  • 62,498
  • 72
  • 186
  • 247
  • 1
    Is `Person` a class? What is the original generator? – tovicheung Sep 03 '22 at 03:48
  • @Pto: Person is just an arbitrary example. The original generator comes from a call to a 3rd party api. The api returns a generator that yields objects. – User Sep 03 '22 at 05:45
  • 1
    Do you actually know how to write a generator? Wrapping another generator and handling attributes seems incidental to the problem. – MisterMiyagi Sep 03 '22 at 06:43
  • 1
    @User I would merely like to find out what more is needed than "create a generator by using generator syntax". – MisterMiyagi Sep 03 '22 at 06:56
  • Does this answer your question? [What does "list comprehension" and similar mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-and-similar-mean-how-does-it-work-and-how-can-i) – MisterMiyagi Sep 03 '22 at 07:05

1 Answers1

0

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()) 
User
  • 62,498
  • 72
  • 186
  • 247