Skip to content

Commit 8240b83

Browse files
committed
Carry Literal default values in Param D generic
For simple default types (None, int, str, bytes, bool, enum), store D = Literal[value] instead of D = ann_type, allowing real values to be extracted when converting back to inspect.Signature.
1 parent cb7005e commit 8240b83

2 files changed

Lines changed: 19 additions & 4 deletions

File tree

tests/test_type_dir.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ class Final:
205205
fin: typing.Final[int]
206206
x: tests.test_type_dir.Wrapper[int | None]
207207
ordinary: str
208-
def foo(self: Self, a: int | None, *, b: int = ...) -> dict[str, int]: ...
208+
def foo(self: Self, a: int | None, *, b: int = 0) -> dict[str, int]: ...
209209
def base[Z](self: Self, a: int | Z | None, b: ~K) -> dict[str, int | Z]: ...
210210
@classmethod
211211
def cbase(cls: type[typing.Self], a: int | None, b: ~K) -> dict[str, int]: ...
@@ -381,7 +381,7 @@ def test_type_members_func_1():
381381
typemap.typing.Param[typing.Literal['self'], tests.test_type_dir.Base[int], {PK}, typing.Never], \
382382
typemap.typing.Param[typing.Literal['a'], int | None, {PK}, typing.Never], \
383383
typemap.typing.Param[typing.Literal['b'], int, typing.Literal[\
384-
<ParamKind.KEYWORD_ONLY: 3>], int]], \
384+
<ParamKind.KEYWORD_ONLY: 3>], typing.Literal[0]]], \
385385
dict[str, int]]"
386386
)
387387

typemap/type_eval/_eval_operators.py

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import collections
22
import collections.abc
33
import contextlib
4+
import enum
45
import functools
56
import inspect
67
import itertools
@@ -409,7 +410,13 @@ def _callable_type_to_signature(callable_type: object) -> inspect.Signature:
409410
default_type = param_args[3] if len(param_args) > 3 else typing.Never
410411
default: typing.Any
411412
if default_type is not typing.Never:
412-
default = _DUMMY_DEFAULT
413+
if (
414+
_typing_inspect.is_literal(default_type)
415+
and len(default_type.__args__) == 1 # type: ignore[union-attr]
416+
):
417+
default = default_type.__args__[0] # type: ignore[union-attr]
418+
else:
419+
default = _DUMMY_DEFAULT
413420
else:
414421
default = inspect.Parameter.empty
415422

@@ -565,12 +572,20 @@ def _ann(x):
565572
quals.append(ParamKind.POSITIONAL_OR_KEYWORD)
566573
ann_type = _ann(ann)
567574
has_default = p.default is not empty
575+
if has_default:
576+
v = p.default
577+
if v is None or isinstance(v, (int, str, bytes, bool, enum.Enum)):
578+
default_type = typing.Literal[(v,)]
579+
else:
580+
default_type = ann_type
581+
else:
582+
default_type = typing.Never
568583
params.append(
569584
Param[
570585
typing.Literal[p.name],
571586
ann_type,
572587
typing.Literal[*quals],
573-
ann_type if has_default else typing.Never,
588+
default_type,
574589
]
575590
)
576591

0 commit comments

Comments
 (0)