microsoft / microsoft/pyright

Strange inference behavior when using replace on dataclasses in asynchronous functions

Open
#11,095 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

I apologize I can't pin-point a specific issue, but there is a class of unintuitive/weird behaviors happening in this example.

In the following snippet the repeated use of replace seems to unexpectedly change the type, which causes pyright to complain. Then there are even more unintuitive "fixes" (as described in the comments). Even if the "solution" is to simply add an annotation to `_a` in the init, that some of the fixes work may suggest there is a deeper issue going on.

`pyright 1.1.407` `python 3.12.7`

``` python
from dataclasses import dataclass, replace

@dataclass
class A:
value: str

_a = A(value='hi')
#_a = replace(_a, value='bye') # Uncomment this to "fix" error

class MyClass:
def __init__(self):
self._a = A(value='hello') # Type with :A to fix error.

async def later(self): # Remove async OR add return type A to "fix" error

for _ in range(2): # Remove for loop to "fix" error
self._a = replace(self._a, value='banana') # < --- ERROR: Type of _a is partially unknown
self._a = replace(self._a, value='apple') # Comment this or replace apple with banana to "fix" error

return self._a # Remove return to "fix" error.

```

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No repository file or test is named. Reproduce the snippet with pyright 1.1.407 on Python 3.12.7, then trace how dataclasses.replace is inferred through the async method and loop; done means the reported partial-unknown behavior is understood and addressed without the listed workarounds.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.