DetachHead / basedpyright

pyright fork with various type checking improvements, improved vscode support and pylance features built into the language server
http://docs.basedpyright.com/
Other
601 stars 12 forks source link

pyright incorrectly synthesizes a `__dataclass_fields__` attribute for classes inheriting from `typing.NamedTuple` #426

Closed DetachHead closed 2 weeks ago

DetachHead commented 2 weeks ago

these reportUninitializedInstanceVariable are a new upstream bug which breaks NamedTuple (https://github.com/microsoft/pyright/issues/8152). for now i will revert that commit (since it was a fix for a far less common issue than the one it introduced), and raise a new issue to fix the original issue some other way

Originally posted by @DetachHead in https://github.com/DetachHead/basedpyright/issues/425#issuecomment-2177354067

original issue (https://github.com/microsoft/pyright/issues/8152):

Describe the bug It's in the title; pyright synthesizes a __dataclass_fields__ attribute on a subclass of typing.NamedTuple, which doesn't actually happen at runtime as far as I can tell.

Code or Screenshots

from typing import NamedTuple
from typing_extensions import reveal_type

class Example(NamedTuple):
    a: int
    b: str

reveal_type(Example.__dataclass_fields__)  # Type of "Example.__dataclass_fields__" is "dict[str, Any]"

This fails at runtime with this traceback: (note, python version is 3.11.9)

Traceback (most recent call last):
  File "c:\Users\name\Projects\personal\winreg-list\test.py", line 8, in <module>
    reveal_type(Example.__dataclass_fields__)  # Type of "Example.__dataclass_fields__" is "dict[str, Any]"
                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Example' has no attribute '__dataclass_fields__'

VS Code extension or command-line Reproducible with Pylance (version v2024.06.100 (prelease)) in VSCode as well as the pyright command line (version 1.1.367).

Extra I wanted to find where this behavior was coming from, and it seems to be from a lack of a if (!isNamedTuple) {...} guard around the lines of code linked below. Not trying to be prescriptive; I was just curious. Hope it's helpful!

https://github.com/microsoft/pyright/blob/5f47007df346c0db1cf8f567ec50250bad07856f/packages/pyright-internal/src/analyzer/dataClasses.ts#L662-L665

DetachHead commented 2 weeks ago

ok i guess that commit wasn't the cause. not sure what it was so i just made my own fix