facebook / facebook/pyrefly

do not specialize private members

Open
#1,126 6 comments 0 reactions 0 assignees View on GitHub
needs-discussion typechecking
Dominant language
Rust
Stars
7k
Forks
516
PR merge metrics
No merged PRs in 30d

Description

it's unsafe to specialize private members:
```py
class A[T]: # covariant
def __init__(self, t: T):
self._t = t

def get(self) -> T:
return self._t

def f(self):
a = A(1)
b: A[object] = a
b._t = "what?"
a._t + 1 # runtime error
```

this can also manifest with annotated `self`:
```py
class A[T]:
def __init__(self, t: T):
self._t = t

def get(self) -> T:
return self._t

def set(self: A[object], value: str):
self._t = value # expect error


a = A[int](1)
a.set("a string???, i hope it doesn't set `_t`")
a.get() + 1
```

this also applies to contravariant type parameters and private methods

if we instead never specialize private members, then we can only interact them safely with generic values, preventing this unsoundness

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.