pythonyield

Is it possible to yield two things at a time just like return?


def foo(choice):
    for i in limit:
        d1 = doSomeCalc()
        d2 = doSomeOtherCalc()
        if choice == "stuff":
            yield {
                d1 : "value"
            }
        else:
            yield {
                d2 : "Othervalue"
            }

I have a function that yields two types of dictionaries depending upon the user's choice

def bar():
    for i in limit:
        d1 = doSomeCalc()
        d2 = doSomeOtherCalc()
        return {d1 : "value"}, {d2 : "Othervalue"}

a,b = bar() // when function returns two dictionaries

Just like return can I use yield to give two different dictionaries at a time? How will I get each value?

I don't want to keep the if-else in my function now.


Solution

  • You can only yield a single value at a time. Iterating over the generator will yield each value in turn.

    def foo():
      yield 1
      yield 2
    
    for i in foo():
      print(i)
    

    And as always, the value can be a tuple.

    def foo():
      yield 1, 2
    
    for i in foo():
      print(i)