Typing, how come that :int is not ensuring int parameter?

DL Neil PythonList at DancesWithMice.info
Thu Jun 11 17:13:52 EDT 2020


On 12/06/20 8:51 AM, zljubisic at gmail.com wrote:
> Hi,
> 
> If I run this code:
> class Property:
> 
>      def __init__(self, var: int):
>          self.a: int = var
> 
>      @property
>      def a(self):
>          return self.__a
> 
>      @a.setter
>      def a(self, var: int):
>          if var > 0 and var % 2 == 0:
>              self.__a = var
>          else:
>              self.__a = 2
> 
> if __name__ == '__main__':
>      x = Property(1.5)
>      print(x.a)
> 
> 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)?


You may be confusing Python with some other programming language 
previously-learned. We need to 're-wire' the way your mind is working 
because whilst you are not-wrong for that-language, you are not-right 
for Python.

So, I'm not going to answer your question directly, but to offer you a 
learning-path:-

What did mypy (or...) say, when you ran tests against the source-code?
(Typing is no use without such a testing regime!)

Have you read the docs for Typing?
- and for extra bonus-points, the numerous PEPs (proposals and accepted) 
related to how Python implements Typing?
(that done, you will likely answer your own question, and accumulate 
some useful learning about Python - at both the practical and 
philosophical/idiomatic levels)
-- 
Regards =dn


More information about the Python-list mailing list