Typing, how come that :int is not ensuring int parameter?
> On 11 Jun 2020, at 21:51, zljubisic at gmail.com wrote:
> If I run this code:
> class Property:
> def __init__(self, var: int):
> self.a: int = var
> def a(self):
> return self.__a
> def a(self, var: int):
> if var > 0 and var % 2 == 0:
> self.__a = var
> self.__a = 2
> if __name__ == '__main__':
> x = Property(1.5)
> I am getting 2.
> How come, if I have created a class with :int in order to ensure that "a" property must be an integer, that I can create an instance with float (1.5)?
The : int is a type *hint* that isn not enforced by python.
If you use a checker program like mypy it will use the type hints and report problems to your.
You can install myy with pip.
$ python3 -m pip install mypy
I put your code in a.py and then checked it:
$ /Library/Frameworks/Python.framework/Versions/3.8/bin/mypy a.py
a.py:18: error: Argument 1 to "Property" has incompatible type "float"; expected "int"
Found 1 error in 1 file (checked 1 source file)
As you can see it found the problem.