Skip to content

Incorrect type inference when NewType used with Any #16021

Closed as not planned
Closed as not planned
@Hnasar

Description

@Hnasar

Bug Report

I created two NewTypes from a third party class which didn't have stubs. When using these NewTypes with a generic function, mypy infers the wrong result type, mixing up the two NewTypes.

To Reproduce

from some_pkg import SomeCls

Right = NewType("Right", SomeCls)
Wrong = NewType("Wrong", SomeCls)
T = TypeVar("T", Right, Wrong)

def generic_fn(data_type: type[T]) -> T: ...
assert_type(generic_fn(Right), Right)  # error: Expression is of type "Wrong", not "Right"

https://mypy-play.net/?mypy=master&python=3.11&gist=adc223e9872d9a7cae12ada10634c014

Expected Behavior

Mypy should allow for NewTypes made from Any and treat them as separate types, like other NewTypes are. (pyright handles this correctly)

Since 3.11, mypy should treat Any as subclassable, and therefore usable with NewType. (Some past discussion here: #12840 (comment))

Actual Behavior

Mypy mixes up the NewTypes made from Any.

Your Environment

  • Mypy version used: 1.2, 1.5.1, master
  • Mypy command-line flags: N/A
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.10, 3.11

Non-solutions
In #12757 (comment) it was suggested to use NewType with object, but

Right = NewType("Right", cast(object, SomeCls)) gives a misc mypy error, and also even if you do
Right = NewType("Right", object) then although the generic typechecking will work, subsequent usages of the NewType instances lose all their attributes, when they should be usable like Any.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions