2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
As soon as the ``++yield++`` keyword is used the enclosing method or function becomes a generator. Thus ``++yield++`` should never be used in a function or method which is not intended to be a generator.
This rule raises an issue when ``++yield++`` or ``++yield from++`` are used in a function or method which is not a generator because:
* the function/method's return type annotation is not [``++typing.Generator[...]++``|https://docs.python.org/3/library/typing.html#typing.Generator]
* it is a special method which can never be a generator (ex: ``++__init__++``).
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A:
def __init__(self, value):
self.value = value
yield value # Noncompliant
def mylist2() -> List[str]:
yield ['string'] # Noncompliant. Return should be used instead of yield
def generator_ok() -> Generator[int, float, str]:
sent = yield 42
return '42'
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,python]
2021-04-28 16:49:39 +02:00
----
class A:
def __init__(self, value):
self.value = value
def mylist2() -> List[str]:
return ['string']
def generator_ok() -> Generator[int, float, str]:
sent = yield 42
return '42'
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
* https://docs.python.org/3/library/typing.html[Python documentation - Support for type hints]
* https://docs.python.org/3/reference/datamodel.html#special-method-names[Python documentation - Special method names]
2021-04-28 18:08:03 +02:00
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
* Remove this "yield" statement
* Replace this "yield" keyword with "return" or change the return type annotation.
=== Highlighting
Primary: the "yield" keyword
Secondary: function/method's return type annotation if there is one
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== is related to: S2734
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]