Skip to content

str not compatible with StrOrLiteralStr #15848

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
solaluset opened this issue Aug 11, 2023 · 2 comments
Open

str not compatible with StrOrLiteralStr #15848

solaluset opened this issue Aug 11, 2023 · 2 comments
Labels
bug mypy got something wrong

Comments

@solaluset
Copy link

Bug Report

mypy doesn't accept str for StrOrLiteralStr

To Reproduce

from string import Formatter
from typing import Iterable, Tuple

class MyFormatter(Formatter):
    def parse(self, s: str) -> Iterable[Tuple[str, str, str, str]]:
        for text, field, spec, conversion in super().parse(s):
            yield "a", "b", "c", "d"

(playground)

Actual Behavior

error: Return type "Iterable[tuple[str, str, str, str]]" of "parse" incompatible with return type "Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]" in supertype "Formatter" [override]

Details

I've asked a question on SO about this and didn't get an answer (yet). As indicated in the comments:

this code passes type checking in mypy 0.971, and fails in mypy 0.981 through 1.5.0

Perhaps it's related to mypy lack of support for LiteralStr #12554

@solaluset solaluset added the bug mypy got something wrong label Aug 11, 2023
@erictraut
Copy link

The error is because you're overriding the Formatter.parse method in an incompatible way. The Formatter base class defines the return type using a constrained TypeVar and includes unions with None, but your override does not. Your override also uses an incompatible parameter name (s versus format_string) and parameter type.

@solaluset
Copy link
Author

Perhaps you're right about TypeVar - this code passes the check:

from string import Formatter
from typing import Iterable, Tuple, TypeVar

Str = TypeVar("Str", str, str)

class MyFormatter(Formatter):
    def parse(self, s: Str) -> Iterable[Tuple[Str, Str, Str, Str]]:
        for text, field, spec, conversion in super().parse(s):
            yield "a", "b", "c", "d"

However, why doesn't mypy display error about argument type in the first example? It's also StrOrLiteralStr in the superclass.

And, more importantly, where can I get (import?) StrOrLiteralStr? StrOrLiteralStr = TypeVar("StrOrLiteralStr", str, str) doesn't look like a clean solution in my opinion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants