Skip to content

dict Literal key type is not a compatible 'subtype' of str key type #2893

@mrckzgl

Description

@mrckzgl

Describe the Bug

Consider this example:

def fun1() -> str:
    a:Literal['cosine', 'dot', 'euclidean', 'manhattan'] = 'cosine'
    return a

def fun2() -> dict[str, str]:
    a:Literal['cosine', 'dot', 'euclidean', 'manhattan'] = 'cosine'
    b = {}
    b[a] = 'test'
    return b

fun2 errors with:

Returned type dict[Literal['cosine', 'dot', 'euclidean', 'manhattan'], str] is not assignable to declared return type dict[str, str]

In fun1 the Literal type is considered a compatible 'subtype' of str as a is always a str. In fun2 it isn't. I would assume fun2 to be ok as the returned dict just contains str keys.

EDIT: Explicitly declaring b: dict[str,str] = {} removes the error.

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN0AZCAxiVUUADropmGGDpgArugAUASjoBaAHx04DSoil0TdVIiEixUANoByAMa44rGHYA0dO5lwMPXmEUHKAhZDH87GgwAC1QGBnCAXToAXi8nF3Q3Y1NKGAZFSnQzKRk5BWV1LV1MCAcGG31KTybEo2LTc0tRcXsM1wifP087QODQmHCRqPRY%2BKTU9OcBnJNsReAAX1W6bBtUZLS7EX07HbyCot2QdxAyPLAoUkIGWigKAGI6AAVSB6e9BgcAQ6E50JA2IU4hBcOhCFIvgBlGAwOjReLEOCIAD02PuciehF4bGxMHQ2J8Djg2LBEKhDBh5IUvDMADdUNBUNhYKDYXSxAzYXRcMRBeg4PD0GQGNFYZpWaIXEK0hIQABmQgARgATKqpDZRNRKHBElJlFweHwYJhNLU8vUIArFnYIGx0Lxsuh3QxNHkAI6KCB5G0AaxgpE0qAcDngcGdAHdUEUzugQJtblGGQqAGLQGAUNBYPBEMhpoA

(Only applicable for extension issues) IDE Information

Pyrefly vscode extension version: 0.58.0

Metadata

Metadata

Assignees

No one assigned

    Type

    No fields configured for Bug.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions