#🔒 Pyright: Weird typing with union set operator with dicts

17 messages · Page 1 of 1 (latest)

sly elk
#
type Foo = Literal["foo"]

bar1: dict[Foo, int] = {'foo': 1}
bar2: dict[Foo, int] = {k: v for k, v in bar1.items()}

baz3: dict[Foo, int] = bar1 | bar2
baz4: dict[Foo, int] = bar1 | {k: v for k, v in bar1.items()}  # error
Pyright: Type "dict[str, int]" is not assignable to declared type "dict[Foo, int]"
  "dict[str, int]" is not assignable to "dict[Foo, int]"
    Type parameter "_KT@dict" is invariant, but "str" is not the same as "Foo
turbid brookBOT
#

@sly elk

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

sly elk
#

@steady hamlet
@spark swan
Idk if you two wanted to look at it, but it seems to be some silly pyright issue

#

i presume there's not much I can do about this, other than just make an in-between variable

steady hamlet
#

What's the inferred type of baz2?

sly elk
#

if I remove the type annotation for bar2, I get the same error for baz3 as well. Let me renumber the variables for clarity

#
type Foo = Literal["foo"]

bar1: dict[Foo, int] = {'foo': 1}
bar2 = {k: v for k, v in bar1.items()}  # note the missing type annotation here in this new code block

baz1: dict[Foo, int] = bar1 | bar2  # error x
baz2: dict[Foo, int] = bar1 | {k: v for k, v in bar1.items()}  # also error x (mentioned in OP)
#

the inferred type is correct

#

Then when I add type annotations, it types it correctly, and no type warnings/errors for invalid type casting stuff

#

it might be a bit unclear with this many images. I can write it out as code block if that helps

spark swan
steady hamlet
#

Yeah, seems like pyright is unable to stick to the type with a dict comp

#

Perhaps there is already an issue open on their GitHub

turbid brookBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.