org.sonar.l10n.py.rules.python.S5864.html Maven / Gradle / Ivy
Why is this an issue?
Checking that variable X has type T with 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 "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 {rule:python:S2159}, {rule:python:S3403}, {rule:python:S5607}, {rule:python:S5756}, {rule:python:S5644},
{rule:python:S3862}, {rule:python:S5797}, {rule:python:S5795} and {rule:python:S5632}. These other rules only detect cases where the type of a
variable is certain, i.e. it cannot be a subclass.
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.
Compliant solution
def add_the_answer(param: str):
return param + "42"
Resources