pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Recognition of typevars obtained by attribute-access imported modules

Open migeed-z opened this issue 8 months ago • 2 comments

class A:
    pass

instance = A()
B = type("B", (), {"i": instance})

expected: typechecks got:

ERROR 5:5-9: No matching overload found for function `type.__new__`, reporting errors for closest overload: `(Unknown, object) -> type` [no-matching-overload]
ERROR 5:15-17: Expected 2 positional arguments, got 4 in function `type.__new__` [bad-argument-type]

migeed-z avatar Apr 22 '25 02:04 migeed-z

There's an easier repro for this. At least 2 files are required (one of them can be in typeshed but I'm using 2 files here just for illustration purpose):

# test2.py
from typing import TypeVar
T = TypeVar("T")

# test.py
import test2
def foo(x: test2.T) -> test2.T:
  return x
foo(42)

Expected: No error Actual: Error on foo(42): Argument Literal[42] is not assignable to parameter x with type TypeVar(T, invariant) in function foo [bad-argument-type]

The problem seems to be the recognition of typevars obtained by attribute-access imported modules.

grievejia avatar Apr 25 '25 20:04 grievejia

@grievejia Is that comment meant for another bug?

I also ran into this type(name, bases, attrs) issue on my codebase:

def main() -> None:
    Foo = type("Foo", (), {'foo': 'bar'})
    x = Foo()

'''
./dbg_type.py:2:11-15: No matching overload found for function `type.__new__`, reporting errors for closest overload: `(Unknown, object) -> type` [no-matching-overload]
./dbg_type.py:2:23-25: Expected 2 positional arguments, got 4 in function `type.__new__` [bad-argument-type]
'''

https://pyrefly.org/sandbox/?code=CYUwZgBAtghglgOwBQEoIFoB8EByB7BEALgCgJyIAxPPCAXggBcBPABxCQCJq9OAaCKgEBvAORgaoohFEAjGACdRAXxRkKAD3pUaqEiTiQA%20kYQwoIE-QacTsRCc6kK0eMhRA

lost-theory avatar May 19 '25 03:05 lost-theory

This is fixed by https://github.com/facebook/pyrefly/commit/51ee0dcfb803896d79c4bc821a6b3bf360cf1fe9, which will be in today's release (0.34.0). @lost-theory the TypeVar issue that Jia described is the root cause of this bug.

rchen152 avatar Sep 22 '25 17:09 rchen152