Ok, so couple of issues to resolve here first.
1. Unpacking does not work on individual values, it tries to exhaust the iterable and unpack everything at once.
def func():
# ..do something...
yield 1, 2
yield 3
yield 4
a, b = func() #ValueError: too many values to unpack (expected 2)
a, b, c, d = func() #ValueError: not enough values to unpack (expected 4, got 3)
a, b, c = func() #Works
print(a) # (1,2)
2.Yield stops the execution wherever encountered.
def func():
yield 1, 2
raise Exception
func_gen = func()
print(func_gen) #<generator object func at 0x000000ACB5A5EBF8>
val1, val2 = next(func_gen) #assigns values
next(func_gen) #raises exception only on next pass
3.A compromise has to be made (this should answer what you asked)
func_gen = func()
print(func_gen) #<generator object func at 0x000000ACB5A5EBF8>
for _ in func_gen:
res = _
#raises Exception but res = (1, 2)
4.A suggestion instead (please do not use exceptions, it is really a job for if-conditions)
def func():
var1 = 0
var2 = 1
flag = not var1 > var2
yield var1, var2, flag #just add a flag during yield
#instead of your exception
# if not var1 > var2:
# raise Exception(var1,var2)
#stuff
yield 'something else'
func_gen = func()
print(func_gen) #<generator object func at 0x000000ACB5A5EBF8>
for _ in func_gen:
res = _
*values, flag = res
if flag:
break
var1,var2 = values #0, 1
- Last but not least, make sure you really need the yield, as it stands, i suspect the function is both tough to read and perhaps deserves breaking into smaller modules. I highly recommend taking a second look at the code, and consider breaking it further if possible.