2023-06-30 09:16:17 +02:00
This rule raises an issue when the ``++__init__++`` method of a class contains a `return` or a `yield` statement.
2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-30 09:16:17 +02:00
By contract, every Python function returns something, even if it is the ``++None++`` value, which can be returned implicitly by omitting the ``++return++`` statement, or explicitly.
2021-04-28 16:49:39 +02:00
2023-06-30 09:16:17 +02:00
The ``++__init__++`` method is required to return ``++None++``. A ``++TypeError++`` will be raised if the ``++__init__++`` method either yields or returns any expression other than ``++None++``. While explicitly returning an expression that evaluates to ``++None++`` will not raise an error, it is considered bad practice.
2021-04-28 16:49:39 +02:00
2023-06-30 09:16:17 +02:00
To fix this issue, make sure that the ``++__init__++`` method does not contain any return statement.
2021-04-28 16:49:39 +02:00
2023-06-30 09:16:17 +02:00
=== Code examples
2021-04-28 18:08:03 +02:00
2023-06-30 09:16:17 +02:00
==== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-06-30 09:16:17 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
class MyClass(object):
def __init__(self):
self.message = 'Hello'
2023-06-30 09:16:17 +02:00
return self # Noncompliant: a TypeError will be raised
2021-04-28 16:49:39 +02:00
----
2021-04-28 18:08:03 +02:00
2023-06-30 09:16:17 +02:00
==== Compliant solution
2021-04-28 16:49:39 +02:00
2023-06-30 09:16:17 +02:00
[source,python,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
class MyClass(object):
def __init__(self):
self.message = 'Hello'
----
2021-04-28 18:08:03 +02:00
2023-06-30 09:16:17 +02:00
== Resources
=== Documentation
* https://docs.python.org/3/reference/datamodel.html#object.++__init__++[The ``++__init__++`` method]
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.
* Remove this return value.
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
=== relates to: S5654
=== on 18 Mar 2015, 17:55:42 Ann Campbell wrote:
-E0100: __init__ method is a generator
-E0101: Explicit return in __init__
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]