type annotation vs working code

Chris Angelico rosuav at gmail.com
Sun Oct 1 08:21:00 EDT 2023


On Sun, 1 Oct 2023 at 22:58, Karsten Hilbert via Python-list
<python-list at python.org> wrote:
>
> Sorry for having conflated the core of the matter with all
> the Borg shenanigans, that's where I found the problem in my
> real code, so there :-)
>
> Consider this:
>
> #----------------------------------------------------
> class Surprise:
>         def __init__(self, with_type_annotation=False):
>                 if with_type_annotation:
>                         try:
>                                 self.does_not_exist:bool
>                                 print('does_not_exist does exist')
>                         except AttributeError:
>                                 print('does_not_exist does not exist')
>                         return
>
>                 try:
>                         self.does_not_exist
>                         print('does_not_exist does exist')
>                 except AttributeError:
>                         print('does_not_exist does not exist')
>
> Surprise(with_type_annotation = False)
> Surprise(with_type_annotation = True)
> #----------------------------------------------------
>
> Is this how it is supposed to be ?

The class isn't even significant here. What you're seeing is simply
that an annotation does not evaluate the expression.

https://peps.python.org/pep-0526/

It's basically a coincidence that your two versions appear nearly
identical. They are quite different semantically. Note that annotating
the expression "self.does_not_exist" is not particularly meaningful to
Python, and I've no idea what different type checkers will do with it;
you normally only annotate variables that you own - so, in a function,
that's function-local variables. Instead, class and instance
attributes should be annotated at the class level, which would remove
this apparent similarity.

This is a very good reason NOT to arbitrarily add type hints to code.
Type hints do not inherently improve code, and making changes just for
the sake of adding them risks making semantic changes that you didn't
intend. Python uses a system of gradual typing for very good reason;
you should be able to add hints only to the places where they're
actually useful, leaving the rest of the code untouched.

ChrisA


More information about the Python-list mailing list