bpo-46195: Do not add Optional
in get_type_hints
(GH-30304) · python/cpython@20a1c8e (original) (raw)
`@@ -1879,26 +1879,6 @@ def cast(typ, val):
`
1879
1879
`return val
`
1880
1880
``
1881
1881
``
1882
``
`-
def _get_defaults(func):
`
1883
``
`-
"""Internal helper to extract the default arguments, by name."""
`
1884
``
`-
try:
`
1885
``
`-
code = func.code
`
1886
``
`-
except AttributeError:
`
1887
``
`-
Some built-in functions don't have code, defaults, etc.
`
1888
``
`-
return {}
`
1889
``
`-
pos_count = code.co_argcount
`
1890
``
`-
arg_names = code.co_varnames
`
1891
``
`-
arg_names = arg_names[:pos_count]
`
1892
``
`-
defaults = func.defaults or ()
`
1893
``
`-
kwdefaults = func.kwdefaults
`
1894
``
`-
res = dict(kwdefaults) if kwdefaults else {}
`
1895
``
`-
pos_offset = pos_count - len(defaults)
`
1896
``
`-
for name, value in zip(arg_names[pos_offset:], defaults):
`
1897
``
`-
assert name not in res
`
1898
``
`-
res[name] = value
`
1899
``
`-
return res
`
1900
``
-
1901
``
-
1902
1882
`_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
`
1903
1883
`types.MethodType, types.ModuleType,
`
1904
1884
`WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
`
`@@ -1908,8 +1888,7 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
`
1908
1888
`"""Return type hints for an object.
`
1909
1889
``
1910
1890
` This is often the same as obj.annotations, but it handles
`
1911
``
`-
forward references encoded as string literals, adds Optional[t] if a
`
1912
``
`-
default value equal to None is set and recursively replaces all
`
``
1891
`+
forward references encoded as string literals and recursively replaces all
`
1913
1892
` 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
`
1914
1893
``
1915
1894
` The argument may be a module, class, method, or function. The annotations
`
`@@ -1989,7 +1968,6 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
`
1989
1968
`else:
`
1990
1969
`raise TypeError('{!r} is not a module, class, method, '
`
1991
1970
`'or function.'.format(obj))
`
1992
``
`-
defaults = _get_defaults(obj)
`
1993
1971
`hints = dict(hints)
`
1994
1972
`for name, value in hints.items():
`
1995
1973
`if value is None:
`
`@@ -2002,10 +1980,7 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
`
2002
1980
`is_argument=not isinstance(obj, types.ModuleType),
`
2003
1981
`is_class=False,
`
2004
1982
` )
`
2005
``
`-
value = _eval_type(value, globalns, localns)
`
2006
``
`-
if name in defaults and defaults[name] is None:
`
2007
``
`-
value = Optional[value]
`
2008
``
`-
hints[name] = value
`
``
1983
`+
hints[name] = _eval_type(value, globalns, localns)
`
2009
1984
`return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
`
2010
1985
``
2011
1986
``