[Python] Pyparsing ParseResults attributes type hinting

Discussão em 'Python' iniciado por Stack, Setembro 2, 2025.

  1. Stack

    Stack Membro Participativo

    I'm using Pyparsing and I'm getting a reportArgumentType error from Pyparse:

    from dataclasses import dataclass
    import pyparsing as pp

    @dataclass
    class Foo:
    value: int


    def parse_foo(line: str) -> Foo:
    grammar = pp.Keyword("FOO") + pp.common.integer("value") + pp.StringEnd()
    parsed = grammar.parse_string(line, parse_all=True)
    return Foo(value=parsed.value) # Error on this line


    The error is

    Argument of type "Any | list[Any] | Unknown | ParseResults | Literal['']" cannot be assigned to parameter "value" of type "int" in function "__init__"
    Type "Any | list[Any] | Unknown | ParseResults | Literal['']" is not assignable to type "int"
    "Literal['']" is not assignable to "int"


    My current solution is quiet pyright with # pyright: ignore[reportArgumentType]:

    return Foo(value=parsed.value) # pyright: ignore[reportArgumentType]


    I don't like that. I'd rather fix the underlying issue with the types of the ParseResults attributes I get from parse_string. Is there a way to set the types? I was kind of expecting pp.common.integer would set the type hint to int and make Pyright happy, but it obviously isn't.

    Continue reading...

Compartilhe esta Página