1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] how to catch throw and other exceptions in coroutine with 1 yield?

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    I have var DICTIONARY, which is a dictionary where the keys are English letters and the values are words that start with the corresponding letter. The initial filling of DICTIONARY looks like this:

    DICTIONARY = {
    'a': 'apple',
    'b': 'banana',
    'c': 'cat',
    'd': 'dog',
    }


    My code has 2 while loops, since higher try-except would end the entire generator loop:

    def alphabet():
    while True:
    try:
    letter = yield #waiting for first input from send
    while True:
    try:
    letter = yield DICTIONARY[letter]
    except KeyError:
    letter = yield 'default' # return 'default', if key is not found
    except Exception:
    letter = yield 'default'
    except KeyError:
    letter = yield 'default'
    except Exception:
    letter = yield 'default'


    However for the input:

    coro = alphabet()
    next(coro)
    print(coro.send('apple'))
    print(coro.send('banana'))
    print(coro.throw(KeyError))
    print(coro.send('dog'))
    print(coro.send('d'))


    expected output:

    default
    default
    default
    default
    dog


    But I don't catch last default - it's None:

    default
    default
    default
    None
    dog


    What is wrong?

    Continue reading...

Compartilhe esta Página