[Python] python- yield and raise exception

Discussão em 'Python' iniciado por Stack, Janeiro 31, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to write a function that yields two variables and also raises an exception based on a condition. Here is a minimal example:

    def func():
    var1 = 0
    var2 = 1
    yield var1, var2
    if not var1 > var2:
    raise Exception(var1,var2)
    var1, var2 = (1,1)
    var1,var2 = func()


    This structure currently doesn't yield var1, var2 and raises an exception. I need it to yield and raise an exception within this function itself so that other modules can directly use this function without additional code. If the yield statement is not a good idea then what is?

    tried - [_ for _ in func()] but var1 and var2 value doesn't change as expected from yield.
    tried - var1, var2 = next(func()) this yields but doesnt raise an exception.

    Continue reading...

Compartilhe esta Página