basedpyright icon indicating copy to clipboard operation
basedpyright copied to clipboard

`Literal` accepted as `type[T]`, and is inconsistent

Open superlopuh opened this issue 2 years ago • 5 comments

from typing import Literal, TypeGuard, TypeVar

T = TypeVar("T")


def isa_literal(obj: object, t: type[T]) -> TypeGuard[T]:
    assert False


a = isa_literal("string", Literal["string"]) # Argument of type "type[Literal['string']]" cannot be assigned to parameter "t" of type "type[T@isa_literal]" in function "isa_literal"basedpyright[reportArgumentType](https://github.com/detachhead/basedpyright/blob/main/docs/configuration.md#reportArgumentType)
a = isa_literal("string", Literal["string", "other_string"])

The first one fails, although, to my knowledge, it's a valid construct.

Edit

When the value goes through a generic function, it has a different type than just the direct assignment:

from typing import Literal

def f[T](t: T) -> T: ...
c: type[int]
c = Literal[1, 2]  # Expression of type "type[Literal[1, 2]]" cannot be assigned to declared type "type[int]"
c = f(Literal[1, 2])

superlopuh avatar Apr 22 '24 15:04 superlopuh

Neither Literal["a"] nor Literal["a", "b"] are values of type type[T] ('classes'). They are TypeForms, which are undenotable in Python.

Both should show an error here.

def f[T](t: type[T]):
    t.mro()
f(Literal[1, "a"])

KotlinIsland avatar Apr 22 '24 21:04 KotlinIsland

i think neither should be an error and type should work with all types. maybe this can be addressed as part of #123

DetachHead avatar Apr 22 '24 22:04 DetachHead

An instance of _LiteralGenericAlias is not a class (type)

KotlinIsland avatar Apr 22 '24 23:04 KotlinIsland

Does basedpyright support TypeForm? Maybe with some flag?

superlopuh avatar Apr 23 '24 05:04 superlopuh

No, unfortunately not, see #123

KotlinIsland avatar Apr 23 '24 05:04 KotlinIsland