Skip to content

stubgen cannot infer precise literal string types from docstring #13996

@DimLight1998

Description

@DimLight1998

Bug Report

I'm using stubgen to generate pyi files for a python c extension module.
Some functions take arguments of type Literal["xxx", "yyy"]; such constraints are written in the docstring of those functions.
After stubgen, these annotations are missing; however this only happens when the arguments of Literal contain str or bytes type.
This problem can be reproduced using infer_sig_from_docstring (see below).

To Reproduce

from mypy.stubdoc import infer_sig_from_docstring

# literal int and bool works as expected
print(infer_sig_from_docstring("f(x: Literal[42]) -> None", "f"))
print(infer_sig_from_docstring("f(x: Literal[False]) -> None", "f"))

# doesn't work
print(infer_sig_from_docstring("f(x: Literal['4_2']) -> None", "f"))
print(infer_sig_from_docstring('f(x: Literal["4_2"]) -> None', "f"))
print(infer_sig_from_docstring("f(x: Literal[b'4_2']) -> None", "f"))
print(infer_sig_from_docstring('f(x: Literal[b"4_2"]) -> None', "f"))

Expected Behavior

[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[42]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[False]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal["4_2"]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal["4_2"]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[b"4_2"]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[b"4_2"]', default=False)], ret_type='None')]

Actual Behavior

[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[42]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type='Literal[False]', default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type=None, default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type=None, default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type=None, default=False)], ret_type='None')]
[FunctionSig(name='f', args=[ArgSig(name='x', type=None, default=False)], ret_type='None')]

Your Environment

  • Mypy version used: 0.982
  • Python version used: 3.10.8

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions