python / typing_extensions

Backported and experimental type hints for Python
Other
445 stars 109 forks source link

Fix `Union[..., NoneType]` injection by `get_type_hints` if a `None` default value is used. #482

Open Daraan opened 1 month ago

Daraan commented 1 month ago

Fixes #310

This PR reverts injection of Union[..., NoneType] by typing.get_type_hints in Python <3.11 if a function uses a None default value.

JelleZijlstra commented 1 month ago

I haven't thought too hard about examples that might break things, but I'm concerned about using == to check whether the two annotations are the same; I don't know if we can rely on equality of annotation objects working reliably for this.

Daraan commented 1 month ago

I haven't thought too hard about examples that might break things, but I'm concerned about using == to check whether the two annotations are the same; I don't know if we can rely on equality of annotation objects working reliably for this.

Do you refer to assertEqual here, or also for the ones in typing_extensions.py?

import typing
from typing import List
a = List["str"]

print(typing._eval_type(a, None, None) is typing._eval_type(a, None, None))  # False

typing._eval_type uses _GenericAlias.copy_with or in some cases creates a new GenericAlias which do not make use of the caches.