microsoft / microsoft/pyright

type[] can be used in a contravariant manner, which is unsound

Open
#11,007 4 comments 2 reactions 0 assignees View on GitHub
enhancement request
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

**Describe the bug**
`type[X]` is covariant. However, unbound methods on `X` act in a contravariant manner. Hence, using such an unbound method causes unsound behavior.

**Code or Screenshots**
If possible, provide a minimal, self-contained code sample (surrounded by triple back ticks) to demonstrate the issue. The code should define or import all referenced symbols.

```python
from typing import reveal_type

class Foo:
def foo(self) -> int:
return 1

class Bar(Foo):
def __init__(self, data: int):
self.data = data

def foo(self):
return self.data

class Baz(Foo):
def __init__(self, data: str):
self.data = data

def foo(self):
return len(self.data)

def bad_func(typ: type[Foo], val: Foo) -> int:
# typ.foo here is contravariant, which allows arbitrary class substitution from among any Foo's subclasses. If typ and val come from different subtyping branches, this is unsound.
return typ.foo(val)

baz = Baz("something")
reveal_type(bad_func(Bar, baz)) # revealed: int, runtime: str
```

**VS Code extension or command-line**
CLI, version 1.1.405

Contributor guide

Open the contributing guide

Research direction

Start by running the self-contained Python sample with the CLI at version 1.1.405 and compare the revealed type with the runtime result. The issue names no repository files or tests; done means the checker no longer permits this unsound use of type[Foo] and the sample's static and runtime behavior agree.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.