test: type hints in Python tests
Summary:
Support for type hints was introduced in Python 3.5. Type hints make it easier to read and review code in my opinion. Also an IDE may discover a potential bug sooner. Yet, as PEP 484 says: "It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention."
Mypy is used to do the type checking. The package is standard so there is little chance that it will be abandoned. Mypy checks that type hints in source code are correct when they are not, it fails with an error.
Useful resources:
Note: Core still depended on python 3.5 when this was merged, so they had to use old style "type comments". With Python 3.6, it becomes possible to use the typehint syntax for variables and attributes. Unfortunately Postponed Evaluation of Annotations is only available starting from python 3.7, so for now e have to use quotes when annotating types (classes) that are only defined later in a module.
This is a backport of core#18210
Depends on D9270
Test Plan:
ninja check-functional
sudo arc liberate arc lint --trace
Add an intentional tyephint mistake:
diff --git a/test/functional/test_framework/script.py b/test/functional/test_framework/script.py index c3d39d8bd..76179e742 100644 --- a/test/functional/test_framework/script.py +++ b/test/functional/test_framework/script.py @@ -23,7 +23,7 @@ from .messages import ( ) -MAX_SCRIPT_ELEMENT_SIZE = 520 +MAX_SCRIPT_ELEMENT_SIZE: bool = 520 OPCODE_NAMES: Dict["CScriptOp", str] = {}
Run arc lint and check that it catches the problem:
>>> Lint for test/functional/test_framework/script.py: Error () mypy found an issue: Incompatible types in assignment (expression has type "int", variable has type "bool") 23 ) 24 25 >>> 26 MAX_SCRIPT_ELEMENT_SIZE: bool = 520 ^ 27 OPCODE_NAMES: Dict["CScriptOp", str] = {} 28 29
Reviewers: #bitcoin_abc, majcosta
Reviewed By: #bitcoin_abc, majcosta
Differential Revision: https://reviews.bitcoinabc.org/D9273