2020-12-21 15:38:52 +01:00
|
|
|
Python does not check returned types by default, however some methods are expected to return a specific type otherwise builtin functions will fail.
|
2020-06-30 12:50:59 +02:00
|
|
|
|
2021-02-02 15:02:10 +01:00
|
|
|
|
2020-12-21 15:38:52 +01:00
|
|
|
This rule raises an issue when a builtin function or method:
|
2020-06-30 14:49:38 +02:00
|
|
|
|
2020-12-21 15:38:52 +01:00
|
|
|
* does not return a value of the expected type.
|
2020-06-30 12:50:59 +02:00
|
|
|
* returns a value when no value should be returned.
|
|
|
|
* returns no value when a return value is expected.
|
|
|
|
|
2020-12-21 15:38:52 +01:00
|
|
|
In such way that the resulting code would result in a runtime error.
|
|
|
|
|
2020-06-30 12:50:59 +02:00
|
|
|
== Noncompliant Code Example
|
|
|
|
|
|
|
|
----
|
|
|
|
class MyInt:
|
|
|
|
def __init__(self):
|
|
|
|
return self # Noncompliant. __init__ should return nothing. This will raise a TypeError.
|
|
|
|
|
|
|
|
def __int__(self):
|
|
|
|
return 3.0 # Noncompliant. __int__ should always return an integer
|
|
|
|
|
|
|
|
int(MyInt()) # This will fail with "TypeError: __int__ returned non-int (type float)"
|
|
|
|
----
|
|
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
|
|
|
|
----
|
|
|
|
class MyInt:
|
|
|
|
def __int__(self):
|
|
|
|
return 3
|
|
|
|
|
|
|
|
int(MyInt())
|
|
|
|
----
|
|
|
|
|
|
|
|
== See
|
|
|
|
|
|
|
|
* https://docs.python.org/3/reference/datamodel.html#special-method-names[Python documentation - Special method names]
|
2021-06-02 20:44:38 +02:00
|
|
|
|
2021-06-03 09:05:38 +02:00
|
|
|
ifdef::env-github,rspecator-view[]
|
2021-06-02 20:44:38 +02:00
|
|
|
== Comments And Links
|
|
|
|
(visible only on this page)
|
|
|
|
|
|
|
|
include::../comments-and-links.adoc[]
|
2021-06-03 09:05:38 +02:00
|
|
|
endif::env-github,rspecator-view[]
|