[Python] What is the Python rule about "unpacking" a generator

Discussão em 'Python' iniciado por Stack, Maio 5, 2025.

  1. Stack

    Stack Membro Participativo

    Here's a simple bounded generator.

    def bounded_naturals(limit):
    num = 1
    while num <= limit:
    yield num
    num += 1


    If I write

    bn_gen = bounded_naturals(3)



    bn_gen will be a generator object as expected.

    But if I write

    (a, b, c) = bounded_naturals(3)



    a, b, and c will be 1, 2, and 3 respectively. That strikes me as strange since there seems to be nothing in the code that asks the generator to produce values. Is there a place in the Python specification that requires this interpretation?

    Even more striking, if I write

    bn_gen = (a, b, c) = bounded_naturals(3)



    I get both results! bn_gen will be a generator object, and a, b, and c will be 1, 2, and 3. How should I understand what's going on?

    Finally, if I write

    (a, b) = bounded_naturals(3)



    I get: ValueError: too many values to unpack (expected 2).

    If the compiler is clever enough to do these other tricks, why isn't it clever enough to ask the generator for only as many elements as needed in this case?

    Is there a section in the Python documentation that explains all this?

    Thanks.

    Continue reading...

Compartilhe esta Página