38 lines
1.1 KiB
Plaintext
38 lines
1.1 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Being a dynamically typed language, the Python interpreter only does type checking during runtime. Getting the typing right is important as certain operations may result in a `TypeError`.
|
|
|
|
Type hints can be used to clarify the expected return type of a function, enabling developers to better document its contract. Applying them consistently makes the code easier to read and understand.
|
|
|
|
In addition, type hints allow some development environments to offer better autocompletion and improve the precision of static analysis tools.
|
|
|
|
== How to fix it
|
|
|
|
Add a type hint to the function definition.
|
|
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,python]
|
|
----
|
|
def hello(name):
|
|
return 'Hello ' + name
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,python]
|
|
----
|
|
def hello(name) -> str:
|
|
return 'Hello ' + name
|
|
----
|
|
|
|
== Resources
|
|
=== Documentation
|
|
|
|
* https://docs.python.org/3/library/typing.html[Python3 documentation on type hints]
|
|
* https://peps.python.org/pep-0484[PEP-484 - Type Hints]
|
|
* https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html[Cheat sheet on type annotations as part of the mypy documentation]
|