pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

TypedDict `extra_items` produces different results with constants, upper case `Literal` variables, upper case non-`Literal` variables and lower case variables

Open gbelouze opened this issue 2 months ago • 1 comments

Describe the Bug

Consider the following

class A(TypedDict, extra_items=int):
    a: str

def quux(a: A):
    assert "b" in a 
    return a["b"]

It should be clear that quux's return type should be int and indeed pyrefly correctly infers it. Now replace "b" with one of the following variable defined at top-level

ABC = "b"
ABC_NOT_LITERAL: str = "b"
abc = "b"
abc_not_literal: str = "b"

e.g.

ABC = "b"  # infered as Literal["b"]
def quux(a: A):
    assert ABC in a 
    return a[ABC]

For Literal["b"] (i.e., ABC and abc), the return type should be the same. For str (i.e., ABC_NOT_LITERAL and abc_not_literal), the return type should be int | str). Interestingly, pyrefly fails to infer it correctly for all but abc_not_literal.

# abc
reveal_type(...) # not ok, return type is Never, should be int

# abc_not_literal
reveal_type(...) # ok, return type is str | int

# ABC
reveal_type(...) # not ok, return type is Never, should be int

# ABC_NOT_LITERAL
reveal_type(...) # not ok, return type is str, should be int | str

This shows that both extra_items and top level constants (upper case variables) are mishandled by pyrefly in some way.

Just to make my point, notice that ABC_NOT_LITERAL and abc_not_literal are handled differently, even though they only differ by their variable names (upper case module level variables are considered constants in python, but this is only a convention and should especially not impact their types).

Sandbox Link

https://pyrefly.org/sandbox/?project=v2.pVZNS8NAEP0rAzkkXty74CGKB6GoSG8WwsaGVixZzYeU_nrfTjZxst0NSI-Zmfd2Om_nbf9hmcKkJgP0vCe_u-cuS9siPoqn53Wxelw_vOYr3s2_rHUl-VHgVxeHgdcrHRc3z0QL1bFrdMHy30L28eJqZwFulYzJEMmnLPsosSNCaaew28A3hCGQxZW6ieBkmxEOWTLxnUJ8dlyWgzwSxB3wuz9GgHK0MRJZMxGGGXnUQR7OsH1uaiF3Bn6smReRJ3pZTOY8ImfFuy3zUO-KEkIJmU9717gjm2KTG57Gdm_6w5ZKxOpujoeKFh_AohR-yhdlDjhddCDUWsDjOA8d6sEKFO_63HQSehkC5PYXzy3catfjUYcLXW_qBO95Rfuu-2pvlBrhptmpqlZb896qGUJhaxrSP_qD_yrM6ciwSbagvcTt0sHs0iWvS63VoWLRvn4B

(Only applicable for extension issues) IDE Information

No response

gbelouze avatar Sep 10 '26 16:09 gbelouze

I should add that

  • mypy does not yet support extra_items
  • ty infers Unknown for all return types
  • pyright infers Unknown for all cases but the "b" and ABC which are both correctly typed as returning an int.

gbelouze avatar Sep 10 '26 16:09 gbelouze