Итак, я возился с генераторами и обнаружил, что у генераторов есть объект typing
(т.е. у генераторов есть псевдоним)
Затем я наткнулся на документацию для объекта typing.Generator
на https://docs.python.org/3/library/typing.html#typing.Генератор, и вот что должны сказать документы:
A generator can be annotated by the generic type
Generator[YieldType, SendType, ReturnType]
.
Что заставило меня задуматься о том, как модифицировать SendType
и ReturnType
штучки.
Документы предложили это в качестве примера:
def echo_round() -> Generator[int, float, str]:
sent = yield 0
while sent >= 0:
sent = yield round(sent)
return 'Done'
Я предполагаю, что второе объявление sent
определяет SendType
, но yield 0
возвращает None
(или вообще ничего не возвращает), и, следовательно, вызывает TypeError: '>=' not supported between instances of 'NoneType' and 'int'
Как работает SendType
, как его изменить и в каких случаях полезны SendType
и ReturnType
?
generator.send(value)
Resumes the execution and “sends” a value into the generator function. The value argument becomes the result of the current yield expression. The
send()
method returns the next value yielded by the generator, or raisesStopIteration
if the generator exits without yielding another value. Whensend()
is called to start the generator, it must be called withNone
as the argument, because there is no yield expression that could receive the value.
См. также Какова цель функции «отправить» в генераторах Python?
Итак, с вашим генератором вы можете сделать это:
it = echo_round()
print(next(it)) # 0 -- we could also have printed: it.send(None)
print(it.send(1.1)) # 1
print(it.send(2.5)) # 2
print(it.send(-1.8)) # StopIteration: Done
...but yield 0 returns None
... если только мы не вызовем send
после того, как был сделан первый выход, как в приведенном выше сценарии. Здесь yield 0
вернет 1.1
Здесь мы видим все три типа:
it.send(1.1)
принимает значение Тип отправки (в данном случае float
) и возвращает значение Тип доходности (в данном случае int
) или вызывает ошибку StopIteration
со значением Тип возврата (в данном случае str
).
Благодарю вас! Я узнал больше о генераторах в python