[issue46195] Annotated and Optional get_type_hints buggy interaction

Nikita Sobolev report at bugs.python.org
Thu Dec 30 05:38:57 EST 2021


Nikita Sobolev <mail at sobolevn.me> added the comment:

As Guido said, the root cause of this problem is because `None` default automatically adds `Optional` to the resulting type.

Source: https://github.com/python/cpython/blob/8d7644fa64213207b8dc6f555cb8a02bfabeced2/Lib/typing.py#L1854-L1856

So, what happens there:
- correct `value` is passed to `_eval_type`, correct result `typing.Annotated[typing.Optional[str], 'd']` is returned at this point
- then `if name in defaults and defaults[name] is None:` adds extra `Optional` annotation on top of `Annotated`

> in the past a default of None automatically caused an Optional
to be added, but we changed our minds

Guido, are you talking about https://github.com/python/typing/issues/275 ?

Now all type-checkers (AFAIK) support something similar to `--no-implicit-optional` mode.

Having this in mind, I see different solutions to the current problem:
1. Remove `Optional` inference with `None` default. This is going to be a some-what breaking change. The only positive side of this is that we can really simplify our code (mainly because the other solution is to complicate our code even more).
2. Or we can change this place to explicitly check for `Annotated` type and its internal type. This should be the easiest to write and backport. But, it still has some complexity to it. I think that this is a better solution: we don't break existing behavior, change is local and pretty trivial.

Also caused by this:
- https://bugs.python.org/issue42921
- https://bugs.python.org/issue42288

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46195>
_______________________________________


More information about the Python-bugs-list mailing list