rspec/rules/S5864/python/rule.adoc

42 lines
1.8 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Checking that variable X has type T with https://docs.python.org/3/library/typing.html[type annotations] implies that X's value is of type T or a subtype of T. After such a check, it is a good practice to limit actions on X to those allowed by type T, even if a subclass of T allows different actions. Doing otherwise will confuse your fellow developers.
Just to be clear, it is common in python to perform an action without checking first if it is possible (see https://docs.python.org/3/glossary.html#term-eafp["Easier to ask for forgiveness than permission."]). However when type checks are performed, they should not contradict the following actions.
This rule raises an issue when an action performed on a variable might be possible, but it contradicts a previous type check. The list of checked actions corresponds to rules S2159, S3403, S5607, S5756, S5644, S3862, S5797, S5795 and S5632. These other rules only detect cases where the type of a variable is certain, i.e. it cannot be a subclass.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
----
def add_the_answer(param: str):
return param + 42 # Noncompliant. Fix this "+" operation; Type annotation on "param" suggest that operands have incompatible types.
# Note: In practice it is possible to create a class inheriting from both "str" and "int", but this would be a very confusing design.
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
----
def add_the_answer(param: str):
return param + "42"
----
2021-04-28 16:49:39 +02:00
== See
* https://docs.python.org/3/library/functions.html#isinstance[Python documentation - ``++isinstance++`` function]
* https://docs.python.org/3/glossary.html#term-eafp[Python glossary - "Easier to ask for forgiveness than permission."]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::highlighting.adoc[]
endif::env-github,rspecator-view[]