facebook / facebook/pyrefly

Writes to attributes should not use the narrowed type

Open
#4,478 5 comments 0 reactions 1 assignee Claimed by @cakeni View on GitHub
narrowing typechecking
Dominant language
Rust
Stars
7k
Forks
516
PR merge metrics
No merged PRs in 30d

Description

### Describe the Bug

The following code is written defensively, with a redundant None check. The pattern was found in the sphinx project

Pyrefly narrows the attribute to Never from the None check & subsequently prevents assignments to it, which is wrong since the attribute has a type annotation and should allow assignments consistent with the annotation.

This has implications for narrowing too, since the narrowed type will no longer be valid after the assignment and therefore will need to be cleared.

```
class Container: pass
class Env:
def __init__(self) -> None:
self.domains: Container = Container()

def setup(self) -> None:
if self.domains is None: # narrows to Never
self.domains = Container() # false positive
```

### Sandbox Link

https://pyrefly.org/sandbox/?project=v2.fVRBDsMgDPtKJO7Lvdd9YA_YBa2omzQRBLT7_lygbLSiNxQUExzbvcjMVrmKjXjF-KGwVRxkl557unYZZZ0XjqyY-E8958VuiAHKc104SOUfsQo-3yqyGlx_AkXJsfzr3A_TTnBcqKJbLlDhBlEGJUwzAhMbvtytQlYaesbowsC8tYuf2Fge5RG46WBatasX_Uox3MKRJAEGwJ4oyXkDelIJVOn5HZMcznb8BQ

### (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.