facebook / facebook/pyrefly

Singleton pattern

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

Description

### Describe the Bug

Something like this should not raise any errors, given that we have attribute narrowing.
```
from typing import assert_type

class Test:
_instance = None

@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance

assert_type(Test.instance(), Test)
```

The fix is probably related to https://github.com/facebook/pyrefly/issues/226, but I'm not sure if that solves all of it. Maybe https://github.com/facebook/pyrefly/issues/1159 is required as well.

What's happening here is the "else" branch of `if cls._instance is None` ends up narrowing `cls._instance` to `Never` because the inferred type is `None`.

Likewise, the `cls._instance = cls()` is not valid here, because the inferred type is `None`. However, the type of `cls._instance` is not affected by the assignment, which seems questionable to me. I think we should have the assignment change the type (at least locally).

### Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcROgOZ0Q3G6UN2o4cGHwD6TYjAA66GQGMoguHQAq8Bohl1tdUazgMMcmHQC8dAHK5002eh10AAgqU0YDABa5MWnZhhgnOgGRjAAFApwAJSa9g46EIGRhHrBhujGnMpWNrHx%2BXTJqSEZJuaRYVG%2B%2BZTuAK6U9kX66cYyMkoiDOLM4WoGhC2hlQA0qupRICMgZLVgUKSEDLRQFADEdAAKpHMLdGhYePiF1pBsDagMENaEMhsAyjAmHgwMxHCIAPSfswELhLw2J8YOhPphcHI4J85KcIOdKJdrqC6GBeAIAG6oaCobCwE7oM4XK7WOi4YjE4K3dBkTzWAC06JEcCRZjoUhAAGZCABGABM7JkIAAvtNUHIroyAGLQGAUA44AgkchCoA

### (Only applicable for extension issues) IDE Information

_No response_

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.