rspec/rules/S5655/python/rule.adoc

69 lines
1.7 KiB
Plaintext
Raw Normal View History

2023-08-08 09:08:50 +02:00
This rule raises an issue when a function or method is called with an argument of a different type than the one described in its type annotations.
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
The CPython interpreter does not check types of arguments when functions are called.
However, a function can express the type it expects for each argument in its documentation or
by using https://www.python.org/dev/peps/pep-0484/[Type Hints].
While the code may initially work as intended, not respecting the contract of an API may lead to bugs later
when its implementation evolves or when type checks are added (i.e. with `isinstance`).
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
This rule also checks argument types for built-in functions.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
[source,python,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
def func(var: str):
pass
2023-08-08 09:08:50 +02:00
func(42) # Noncompliant: 42 is not of type str.
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
round("not a number") # Noncompliant: the builtin function round requires a number as first parameter.
2021-04-28 16:49:39 +02:00
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
[source,python,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
def func(var: str):
pass
func("42")
2023-08-08 09:08:50 +02:00
round(1.2)
2021-04-28 16:49:39 +02:00
----
== Resources
2021-04-28 16:49:39 +02:00
2023-08-08 09:08:50 +02:00
=== Documentation
* Python documentation - https://docs.python.org/3/library/functions.html#built-in-funcs[builtins]
* Python documentation - https://docs.python.org/3/library/typing.html[typing — Support for type hints]
* PEP 484 - https://www.python.org/dev/peps/pep-0484/[Type Hints]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Change this argument of type XXX; Function FFF expects type YYY
=== Highlighting
Primary: the expression provided as argument
Secondary:
* location: definition of the function called
* message: "Function definition"
endif::env-github,rspecator-view[]