rspec/rules/S935/python/rule.adoc

57 lines
1.7 KiB
Plaintext
Raw Normal View History

2020-06-30 12:50:59 +02:00
Python does not check returned types by default, however some methods are expected to return a specific type otherwise builtin functions will fail. Developers can also use type hints to specify which types they expect. Not following these type hints will most probably result in a runtime error.
This rule raises an issue when a function or method:
* does not return or yield a value of the expected type.
* returns a value when no value should be returned.
* returns no value when a return value is expected.
== 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)"
def hello() -> str:
return 42 # Noncompliant. Function's type hint asks for a string return value
def should_return_a_string(condition) -> str:
if condition:
return "a string"
# Noncompliant. The function returns None if the condition is not met
def generator_noncompliant() -> Generator[int, float, str]:
sent = yield '42' # Noncompliant
return 42 # Noncompliant
----
== Compliant Solution
----
class MyInt:
def __int__(self):
return 3
int(MyInt())
def hello() -> str:
return "Hello"
def should_return_a_string() -> str:
return "a string"
def generator_ok() -> Generator[int, float, str]:
sent = yield 42
return '42'
----
== See
* 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]