Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

yield

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.

like image 311
Animesh Pandey Avatar asked Jan 29 '15 01:01

Animesh Pandey


1 Answers

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
like image 132
Ignacio Vazquez-Abrams Avatar answered Sep 20 '22 15:09

Ignacio Vazquez-Abrams