rspec/rules/S5890/python/rule.adoc

70 lines
1.7 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Type hints can be used to communicate the intended type of a given variable. These are not enforced at runtime and not respecting them might not necessarily lead to runtime errors.
It is however confusing and could lead to maintainability issues.
=== 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
----
def my_function():
my_int: int = "string" # Noncompliant
----
=== 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
----
def my_function():
my_str: str = "string"
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* If the asignment value is not ``++None++`` then
** Primary: Assign to "XXX" a value of type "YYY" instead of "ZZZ" or update the type hint of "XXX".
** Secondary: Type hint.
* If the assignment value is ``++None++``
** Primary: Replace the type hint "XXX" with "Optional[XXX]" or don't assign "None" to "YYY"
** Secondary: Type hint.
=== Highlighting
* Primary: The assigned value
* Secondary: The type hint
'''
== Comments And Links
(visible only on this page)
=== on 12 May 2021, 00:45:18 Mike Heyns wrote:
This rule does not appear to be working for https://docs.python.org/3/library/dataclasses.html#init-only-variables[Dataclass Init-Only variables]:
----
@dataclass
class Book:
name: str
condition: InitVar[str] = ''
----
____Assign to "condition" a value of type "InitVar[str]" instead of "str" or update its type hint.____
In fact, most examples including the official documentation use ``++None++`` as the default for init-only arguments. Attempting to use ``++InitVar[Optional[str]]++`` has the same effect as above.
endif::env-github,rspecator-view[]