69 lines
1.7 KiB
Plaintext
69 lines
1.7 KiB
Plaintext
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.
|
|
|
|
== Why is this an issue?
|
|
|
|
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`).
|
|
|
|
This rule also checks argument types for built-in functions.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,python,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
def func(var: str):
|
|
pass
|
|
|
|
func(42) # Noncompliant: 42 is not of type str.
|
|
|
|
round("not a number") # Noncompliant: the builtin function round requires a number as first parameter.
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,python,diff-id=1,diff-type=compliant]
|
|
----
|
|
def func(var: str):
|
|
pass
|
|
|
|
func("42")
|
|
|
|
round(1.2)
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
=== 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[]
|