This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: typing.get_type_hints() returns Optional[Any] if the default value of the argument is None
Type: enhancement Stage: resolved
Components: Library (Lib) Versions: Python 3.10, Python 3.9, Python 3.8
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: gvanrossum, levkivskyi, tkomiya
Priority: normal Keywords:

Created on 2020-11-08 04:51 by tkomiya, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg380532 - (view) Author: Komiya Takeshi (tkomiya) * Date: 2020-11-08 04:51
I noticed `typing.get_type_hints()` returns Optional[Any] as a type hints if the default value of the argument is None:

```
$ python
Python 3.9.0 (default, Oct 24 2020, 15:41:29)
[Clang 11.0.3 (clang-1103.0.32.59)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from typing import Any, get_type_hints
>>> def hello(name: Any = None):
...     pass
...
>>> get_type_hints(hello)
{'name': typing.Optional[typing.Any]}
```

I know typing.get_type_hints() wraps the user's type annotation with Optional when the default value of the argument is None. But it is needless to wrap Any with Optional because Any already contains None. It would be better not to wrap it with Optional when the user's annotation is Any.
msg380562 - (view) Author: Guido van Rossum (gvanrossum) * (Python committer) Date: 2020-11-08 22:07
There is actually a difference between Any and Optional[Any]. Try the following using e.g. mypy:

def f(a: Optional[Any]):
    a+1

def g(a: Any):
    a+1

You'll get an error in f but not in g.

So this behavior is not a bug.
msg380660 - (view) Author: Komiya Takeshi (tkomiya) * Date: 2020-11-10 13:27
Wow, I don't know that behavior. Thank you for your wisdom!
History
Date User Action Args
2022-04-11 14:59:37adminsetgithub: 86454
2020-11-10 13:27:37tkomiyasetmessages: + msg380660
2020-11-08 22:07:34gvanrossumsetstatus: open -> closed
resolution: not a bug
messages: + msg380562

stage: resolved
2020-11-08 07:01:44serhiy.storchakasetnosy: + gvanrossum, levkivskyi

type: enhancement
components: + Library (Lib)
versions: - Python 3.6, Python 3.7
2020-11-08 04:51:22tkomiyacreate