59 lines
1.3 KiB
Plaintext
59 lines
1.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Python does not check returned types by default, however some methods are expected to return a specific type otherwise builtin functions will fail.
|
|
|
|
|
|
This rule raises an issue when a builtin function or method:
|
|
|
|
* does not return a value of the expected type.
|
|
* returns a value when no value should be returned.
|
|
* returns no value when a return value is expected.
|
|
|
|
In such way that the resulting code would result in a runtime error.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,python]
|
|
----
|
|
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
|
|
|
|
[source,python]
|
|
----
|
|
class MyInt:
|
|
def __int__(self):
|
|
return 3
|
|
|
|
int(MyInt())
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://docs.python.org/3/reference/datamodel.html#special-method-names[Python documentation - Special method names]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::message.adoc[]
|
|
|
|
include::highlighting.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|