facebook / facebook/pyrefly

Feature request: implement `method-assign` from `mypy`

Open
#4,161 3 comments 0 reactions 1 assignee Claimed by @WilliamK112 View on GitHub
help wanted typechecking
Dominant language
Rust
Stars
7k
Forks
516
PR merge metrics
No merged PRs in 30d

Description

### Describe the Bug

`mypy` [explains it adequately](https://mypy.readthedocs.io/en/stable/error_code_list.html#check-that-assignment-target-is-not-a-method-method-assign):

> In general, assigning to a method on class object or instance (a.k.a. monkey-patching) is ambiguous in terms of types, since Python’s static type system cannot express the difference between bound and unbound callable types.

This would be a useful feature to explicitly disallow any monkey patching, which significantly obfuscates code.

```
class A:
def f(self) -> None: pass
def g(self) -> None: pass

def h(self: A) -> None: pass

A.f = A.g
```

For reference, `mypy` returns:
```
$ mypy --strict example.py
example.py:7: error: Cannot assign to a method [method-assign]
```

Tests often do this for mocking unless they use `mock.patch`, so it probably shouldn't be on by default unless there is special handling for `Mock`, etc.

### Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeSIAxlKnHAAQCCiAOuvR-ZjGPWABRwYUMAEp6AWgB89AHK50MRPWK04bTlx70A5oOFjJM%2BYuWq6bNt14ALfSOWNx0uQqUq1l9I0K8AvEyEOmwgADQgZABOPFCkhAAuuAC2UBQAxPQACqTRYLH0aFh4%2BPSUCpA6AK6RqPEQCoRsGQDKMDD0NvHxxHCIAPR9UTFxuJE6fTDofZi4lHB9ZegV1bX1U3yj9KgAbqjQqNiwpeUQVTV1CvS4xBfocI3oZPE2ChLbMJFwa-QBLCAAzIQAIwAJj%2BbGI0SE8R%2B9D%2BqCgUD%2BIAAvuFUJQ6u8AGLQGAUQo4AgkcgooA

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