microsoft / microsoft/pyright

Setting attributes of class instance in `__new__` method included in `__slots__` causes those attributes to be inferred as `Unbound`

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

Description

**Describe the bug**
When a class defines a `__new__` method rather than `__init__` and uses `__slots__` (e.g. for immutable objects with a fixed structure), the attributes set on the return object, even if known to be an instance of that class, in its body, are not recognized to have been 'bound' if not re-set elsewhere, and are revealed to be `Unbound` when accessed in other methods of the class.

**Code or Screenshots**

```python
from _thread import LockType
from typing import reveal_type
class Foo:
__slots__ = '_spam', '_ham'
def __new__(cls, tup: tuple[int, LockType]):
self = super().__new__(cls)
self._spam, self._ham = tup
return self
def bar(self): reveal_type(self._spam) # no diagnostic produced
# when I hover over the attribute, it says 'Unbound'
def baz(self):
with self._ham: # ERROR!
self.bar()
```

The error shown in the above case is twofold:

```md
Object of type "Unbound" cannot be used with "with" because it does not correctly implement __enter__ Pylance[reportGeneralTypeIssues](https://github.com/microsoft/pylance-release/blob/main/docs/diagnostics/reportGeneralTypeIssues.md)
Object of type "Unbound" cannot be used with "with" because it does not correctly implement __exit__ Pylance[reportGeneralTypeIssues](https://github.com/microsoft/pylance-release/blob/main/docs/diagnostics/reportGeneralTypeIssues.md)
```

**VS Code extension or command-line**
VS Code extension; preview (v2026.2.100).
I have seen analogs of this issue in previous versions as well.

Contributor guide

Open the contributing guide

Research direction

Start with the minimal Python reproduction using __new__ and __slots__, then trace how instance attributes assigned in __new__ are inferred when accessed by bar and baz. Add a regression test covering the _spam and _ham assignments, and verify that the attributes are no longer revealed as Unbound and can be used with the context manager.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.