Skip to content

Apply metaclass data descriptors when metaclass is type - #12036

Open
crypt0lith wants to merge 9 commits into
microsoft:mainfrom
crypt0lith:fix/bound-member-type-metaclass-descriptor
Open

crypt0lith wants to merge 9 commits into
microsoft:mainfrom
crypt0lith:fix/bound-member-type-metaclass-descriptor

Conversation

@crypt0lith

@crypt0lith crypt0lith commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

python/typeshed#16674 declares type's read-only attributes as getter-only properties, reverting the Final declarations that 4975f45 brought in. Under those stubs, type.__mro__ evaluates to property, and C.__mro__ evaluates to C's own __mro__ when its class body defines one.

Member access on a class object doesn't follow the descriptor protocol:

  • A data descriptor on type is never applied.
  • With any metaclass, a class attribute shadows a metaclass data descriptor on assignment and deletion, and on reads when the descriptor's __get__ returns something other than the descriptor through the class, or when it defines __delete__ but not __set__.
  • A metaclass attribute whose union is only partly data descriptors evaluates to the class attribute when the class body shadows it.
  • An assignment to a descriptor attribute on the class object that holds it is checked against the descriptor's __set__ instead of the descriptor's type.
  • An assignment through a data descriptor that lacks __set__ is checked against the descriptor's own type, and a deletion through one that lacks __delete__ isn't reported.
  • When an attribute's declared type is a union of descriptors, the assigned value is evaluated with the union as its expected type rather than __set__'s value type.

An assignment through an instance to a dataclass field with a converter is checked against the converter's input type only when pyright synthesizes __init__ for the class.

Root cause

getTypeOfBoundMember skips the metaclass data descriptor lookup when the metaclass is type, and when the metaclass is the class itself, which only type is. The comment on the check says type has no attributes that are descriptors, but object.__class__ is a property in type's MRO, and so is each of type's read-only attributes whenever the stub declares it as one. The lookup also runs only for reads, and it tests the metaclass member after applying its __get__ (typeEvaluator.ts:1811-1830), requiring a __set__. CPython treats a descriptor that defines __set__ or __delete__ as a data descriptor, and for assignment and deletion it doesn't require __get__. A union counts only if every subtype is a data descriptor (typeUtils.ts:1406-1412).

The lookup on the class itself applies a class member's descriptor (typeEvaluator.ts:4805-4816) on assignment and deletion through the class object too, though CPython consults only the metaclass for those. When the descriptor has no __set__ or __delete__, the error is reported only for properties (typeEvaluator.ts:5007-5020). The declared type for an assignment (typeEvaluator.ts:2177-2186) is __set__'s value type only when the declared type is a single class instance, and the descriptor's own type when __set__ is missing.

Dataclass synthesis replaces a converter field's symbol (dataClasses.ts:709-728) with an instance of a synthesized descriptor class whose __set__ takes the converter's input type, and does so only while synthesizing __init__ (dataClasses.ts:686-689).

Fix

For member access on a class object:

  • Run the metaclass lookup for every metaclass, and for assignment and deletion as well as reads.
  • Test the metaclass member's declared type for a class-level __set__ or __delete__, and for __get__ on reads.
  • When only some subtypes of the metaclass attribute are data descriptors, combine the class attribute with the lookup restricted to those subtypes.
  • Apply a class's own descriptor on assignment or deletion only through an instance.
  • Take the expected type of an assigned value from a metaclass data descriptor's __set__.

For assignment and deletion through a descriptor:

  • Report an assignment or deletion through a data descriptor that lacks __set__ or __delete__.
  • Take __set__'s value type for each subtype of the declared type, with no expected type when a data descriptor lacks __set__, or when the value types of several descriptors are the same class with different type arguments.

For a dataclass field with a converter:

  • Keep the field's declared symbol, and record the converter's input type on its dataclass entry.
  • Check an assignment through an instance against that input type, and take the assigned value's expected type from it.
  • Don't narrow on assignment when the input type differs from the declared type.

Update the bundled typeshed stdlib/builtins.pyi to python/typeshed@8024194 for the stub change.

Test

Cases added to memberAccess23.py
Case Expected Description
ClassB.__mro__ property on type wins over class attribute
ClassB().__mro__ instance access sees class attribute
type.__mro__ type as its own metaclass
ClassC1.get shadowed metaclass non-data descriptor yields to class attribute
ClassC1.getset shadowed metaclass data descriptor, __get__ doesn't return the descriptor
ClassC1.getdelete shadowed metaclass descriptor with __get__ and __delete__ only
ClassC1.getsetdelete shadowed metaclass data descriptor, __get__ returns the descriptor
func1 writable attribute on type
func2 error write and delete through getter-only property on type
func3 write through shadowed metaclass __set__
func4 write and delete on class attribute shadowing non-data descriptor
func5 error wrong value type for shadowed metaclass __set__
func6 error write through shadowed metaclass descriptor without __set__
func7 delete through shadowed metaclass __delete__
func8 error delete through shadowed metaclass descriptor without __delete__
func9 delete through metaclass __delete__
func10 error delete through metaclass descriptor without __delete__
func11 error write through metaclass descriptor without __set__
ClassD.attr1 shadowed metaclass union of data descriptor and non-descriptor
func12 error wrong value type for __set__ in shadowed metaclass union
func13 error delete through shadowed metaclass union member without __delete__
func14 error write through shadowed metaclass union member without __set__
ClassE.attr1 metaclass descriptor with instance-level __set__/__delete__ yields to class attribute
func15 write and delete on class attribute shadowing metaclass descriptor with instance-level __set__/__delete__
func16 empty list inferred from shadowed metaclass __set__, not class attribute
func17 error wrong value type for shadowed metaclass __set__, list literal
Cases added and changed in dataclassConverter2.py
Case Expected Description
DC1.asymmetric = "2" error class-object write of converter input type, not declared type
DC1.asymmetric = 2 class-object write of declared type
func1 instance write of converter input type to init=False field
func2 error instance write of declared type to init=False field
func3 instance write of converter input type with custom __init__
func4 error instance write of declared type with custom __init__
func5 empty list inferred from converter input type, not declared type
func6 error list literal of declared element type to converter field
Cases added to descriptor8.py
Case Expected Description
func1 write through __set__
func2 delete through __delete__
func3 error delete through data descriptor without __delete__
func4 error write through data descriptor without __set__
func5 class-object write replaces descriptor
func6 class-object delete removes descriptor
func7 error class-object write of __set__ value type, not descriptor type
func8 error write through annotated data descriptor without __set__ reports missing __set__
func9 error write through data descriptor without __set__ in annotated union reports missing __set__
func10 empty list through union of descriptors whose __set__ value types differ in type argument
func11 error list literal satisfying only one __set__ in union of descriptors
Cases changed in memberAccess10.py and property11.py
Case Expected Description
X.number_cls = "hi" error class-object write skips metaclass __set__ of class-valued attribute
Class1.prop1 = "hi" error class-object write replaces class property without calling setter

@crypt0lith
crypt0lith marked this pull request as ready for review November 18, 2026 16:49
@bschnurr

Copy link
Copy Markdown
Member

Reviewed 201defb58 against ff00b031. The 29 focused member-access tests and tsc --noEmit passed. The added probes confirm that C.__mro__ resolves to tuple[type, ...] even when the class body defines __mro__ = "instance", while C().__mro__ still resolves to str. Returning C.__mro__ from a function annotated -> str now produces reportReturnType. A custom metaclass's non-data descriptor still yields to the class attribute.

One pre-existing gap, not a regression in this read fix: when the class body defines __mro__, both revisions accept assignment to and deletion of C.__mro__; CPython 3.14.7 raises AttributeError for both. Without that class-body attribute, both revisions reject the write and delete. I didn't measure the cost of the new lookup on ordinary class reads.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

The write and delete gap isn't specific to type. It happens for any metaclass data descriptor shadowed by a class attribute of the same name, because getTypeOfBoundMember consults the metaclass first only when usage.method === 'get'. A set or delete goes straight to the class lookup, finds the class attribute, and is accepted. The metaclass is consulted only when the class doesn't define the name, which is why the write and delete are rejected without the class attribute. With a custom metaclass, on main and this PR alike:

class Meta(type):
    @property
    def x(cls) -> int:
        return 0


class C(metaclass=Meta):
    x = "class body"


reveal_type(C.x)
C.x = "other"
del C.x
:11:13 - information: Type of "C.x" is "int"
0 errors, 0 warnings, 1 information

The read already honors Meta.x. The assignment and the del raise AttributeError at runtime, and pyright reports neither. Before this PR, type couldn't show this gap because the get path skipped type too.

On the cost of the new lookup: I measured it before opening the PR, comparing ff00b03 against 73a7b69. Each run was pyright --stats over 14 CPython 3.14 stdlib packages (asyncio, email, unittest, logging, http, importlib, xml, concurrent, multiprocessing, ctypes, tkinter, json, collections, pathlib). That is 528 files parsed and 194 checked, with identical diagnostics on both builds. I did 8 runs per build, interleaved:

Type-checking time ff00b03 73a7b69
Median 18.65 s 19.86 s
Mean 19.93 s 19.99 s
Range 17.57–24.54 s 17.87–23.67 s
Fastest run 17.57 s 17.87 s

Runs 8 to 12 were slowed by other load for both builds. The means differ by 0.06 s, and the fastest runs by 0.3 s (1.7%), so the difference is within noise.

@heejaechang

Heejae Chang (heejaechang) commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

🔴 Pyright CLI QA — 07076bd6 — verdict: red

Automated CLI checks compared this change with its base revision.
25 focused check(s) completed.

Needs review: reportArgumentType no longer reported

The base reports reportArgumentType for this example; the PR does not. Is this change intended?

Reproduction and observed results

Create these files in an empty directory:

main.py

from typing import Any, Callable, Protocol, dataclass_transform
reveal_type(0)
def field(*, converter: Callable[..., Any]) -> Any: ...
@dataclass_transform(field_specifiers=(field,))
class Model: ...
def parse(value: str) -> int:
    return int(value.strip())
class Converted(Model):
    x: int = field(converter=parse)
class Writer(Protocol):
    x: int

def replace(obj: Writer) -> None:
    obj.x = 123

def unsafe(obj: Converted) -> None:
    replace(obj)

pyrightconfig.json

{
  "include": [
    "main.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base ff00b031cf9c7ea1d59f3c12387ba4415c017fe0

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Converted\" cannot be assigned to parameter \"obj\" of type \"Writer\" in function \"replace\"\n  \"Converted\" is incompatible with protocol \"Writer\"\n    \"x\" is invariant because it is mutable\n    \"x\" is an incompatible type\n      \"__converterDescriptor_x\" is not assignable to \"int\"",
      "range": {
        "start": [
          16,
          12
        ],
        "end": [
          16,
          15
        ]
      }
    },
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 07076bd64058ac8b723ce698df78928c080730fc

{
  "exit_code": 0,
  "diagnostics": [
    {
      "file": "main.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

Additional reproduction: reportArgumentType no longer reported

The base reports reportArgumentType for this example; the PR does not. Is this change intended?

Create these files in an empty directory:

frozen.py

from typing import Any, Callable, dataclass_transform
reveal_type(0)
def field(*, converter: Callable[..., Any]) -> Any: ...
@dataclass_transform(field_specifiers=(field,))
class Model:
    def __init_subclass__(cls, *, frozen: bool = False) -> None: pass
def parse(value: str) -> int: return int(value)
class Frozen(Model, frozen=True):
    x: int = field(converter=parse)
def invalid(obj: Frozen) -> None:
    obj.x = "12"  # E:reportAttributeAccessIssue

negative.py

from typing import Any, Callable, Protocol, dataclass_transform
reveal_type(0)
def field(*, converter: Callable[..., Any]) -> Any: ...
@dataclass_transform(field_specifiers=(field,))
class Model: ...
def parse(value: str) -> int: return int(value.strip())
class Base(Model):
    x: int = field(converter=parse)
class Child(Base): pass
class Writer(Protocol):
    x: int
def mutate(obj: Writer) -> None: obj.x = 12
def inherited(obj: Child) -> None:
    mutate(obj)  # E:reportArgumentType

def convert[T](value: list[T]) -> set[T]: return set(value)
class Container[T](Model):
    x: set[T] = field(converter=convert)
class SetWriter(Protocol):
    x: set[int]
def write_set(obj: SetWriter) -> None: obj.x = {1}
def generic(obj: Container[int]) -> None:
    write_set(obj)  # E:reportArgumentType

positive.py

from typing import Any, Callable, Protocol, assert_type, dataclass_transform
reveal_type(0)
def field(*, converter: Callable[..., Any]) -> Any: ...
@dataclass_transform(field_specifiers=(field,))
class Model: ...
def identity(value: int) -> int: return value
class Symmetric(Model):
    x: int = field(converter=identity)
class Writer(Protocol):
    x: int
def mutate(obj: Writer) -> None:
    obj.x = 12
    obj.x.bit_length()
def good(obj: Symmetric) -> None:
    mutate(obj)
    assert_type(obj.x, int)

pyrightconfig.json

{
  "include": [
    "negative.py",
    "positive.py",
    "frozen.py"
  ],
  "pythonVersion": "3.13",
  "typeCheckingMode": "basic"
}

From that directory, run each built Pyright revision:

node <pyright-cli-entrypoint> --outputjson -p .

Base ff00b031cf9c7ea1d59f3c12387ba4415c017fe0

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "frozen.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot assign to attribute \"x\" for class \"Frozen\"\n  \"Frozen\" is frozen",
      "range": {
        "start": [
          10,
          8
        ],
        "end": [
          10,
          9
        ]
      }
    },
    {
      "file": "frozen.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "negative.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Child\" cannot be assigned to parameter \"obj\" of type \"Writer\" in function \"mutate\"\n  \"Child\" is incompatible with protocol \"Writer\"\n    \"x\" is invariant because it is mutable\n    \"x\" is an incompatible type\n      \"__converterDescriptor_x\" is not assignable to \"int\"",
      "range": {
        "start": [
          13,
          11
        ],
        "end": [
          13,
          14
        ]
      }
    },
    {
      "file": "negative.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Container[int]\" cannot be assigned to parameter \"obj\" of type \"SetWriter\" in function \"write_set\"\n  \"Container[int]\" is incompatible with protocol \"SetWriter\"\n    \"x\" is invariant because it is mutable\n    \"x\" is an incompatible type\n      \"__converterDescriptor_x[int]\" is not assignable to \"set[int]\"",
      "range": {
        "start": [
          22,
          14
        ],
        "end": [
          22,
          17
        ]
      }
    },
    {
      "file": "negative.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "positive.py",
      "severity": "error",
      "rule": "reportArgumentType",
      "message": "Argument of type \"Symmetric\" cannot be assigned to parameter \"obj\" of type \"Writer\" in function \"mutate\"\n  \"Symmetric\" is incompatible with protocol \"Writer\"\n    \"x\" is invariant because it is mutable\n    \"x\" is an incompatible type\n      \"__converterDescriptor_x\" is not assignable to \"int\"",
      "range": {
        "start": [
          14,
          11
        ],
        "end": [
          14,
          14
        ]
      }
    },
    {
      "file": "positive.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

PR 07076bd64058ac8b723ce698df78928c080730fc

{
  "exit_code": 1,
  "diagnostics": [
    {
      "file": "frozen.py",
      "severity": "error",
      "rule": "reportAttributeAccessIssue",
      "message": "Cannot assign to attribute \"x\" for class \"Frozen\"\n  Attribute \"x\" is read-only",
      "range": {
        "start": [
          10,
          8
        ],
        "end": [
          10,
          9
        ]
      }
    },
    {
      "file": "frozen.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "negative.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    },
    {
      "file": "positive.py",
      "severity": "information",
      "rule": null,
      "message": "Type of \"0\" is \"Literal[0]\"",
      "range": {
        "start": [
          1,
          12
        ],
        "end": [
          1,
          13
        ]
      }
    }
  ]
}

Diagnostic ranges use zero-based line and character positions.

@bschnurr

Copy link
Copy Markdown
Member

I replayed the new QA cases against base ff00b031 and head 51cb41ce. The union-descriptor assignment diagnostic looks intentional: the value must be accepted by every possible setter signature. Two items still need resolution:

  1. isDataDescriptorInstance uses lookUpObjectMember to detect __set__/__delete__. Descriptor protocol special methods are looked up on the descriptor's class, not as attributes stored on the descriptor instance. In the QA example, Fake.__delete__ is assigned in Fake.__init__, so it is a non-data descriptor. CPython 3.14.7 returns the class-body value (str) for C.x; the base also infers str, but this head infers int and errors on C.x.upper(). Please restrict the data-descriptor test to type-level special methods.

  2. The broader evaluator suite fails DataClassConverter2 on this head: expected 4 errors, got 8 (7 suites passed, 1 failed). It newly rejects DC1.asymmetric = "2" and DC1.symmetric = "1", then exposes internal __converterDescriptor_* types in reveal_type; the base passes the test. If class-level writes to converter fields are intentionally no longer supported, please update the behavior and test contract explicitly and avoid leaking the synthetic type. Otherwise, preserve the existing converter-field behavior.

Validation: both revisions build with pnpm run build:cli:dev; the exact focused reproductions pass on base and produce the reported changes on head. The broader head command was pnpm --dir packages/pyright-internal exec jest typeEvaluator --runInBand --forceExit.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

If class-level writes to converter fields are intentionally no longer supported, please update the behavior and test contract explicitly and avoid leaking the synthetic type. Otherwise, preserve the existing converter-field behavior.

Class-level writes to converter fields are still supported. The problem is with how assignment is modeled. A class is an instance of its metaclass, so assignments on a class go through the metaclass's __setattr__. Pyright treats assignments on the class object as if it goes through the descriptor's __set__, which is wrong because the descriptor is just another attribute on the class (the metaclass instance).

That only shows up for converter fields because pyright models them with a synthesized descriptor (getDescriptorForConverterField), so a class-level write is now checked against that synthesized type instead of the attribute's declared type.

synthesizeDataClassMethods replaces a converter field's symbol with a
synthesized descriptor, so class-object assignment, which no longer
invokes it, is checked against the descriptor type. The descriptor
is created only while synthesizing __init__.

Keep the declared symbol, store the converter's input type on the
dataclass entry, and check assignment through an instance against it,
whether or not __init__ is synthesized.
@crypt0lith

Copy link
Copy Markdown
Contributor Author

07076bd fixes the three findings from the QA bot run on 18df53e: an empty container assigned to a converter field, through a union of descriptors, or to a class attribute shadowed by a metaclass data descriptor was inferred against the declared type rather than the type it's checked against.

The partial.py case in the second finding isn't addressed. That it differs from the base says nothing about what the correct behavior is: the base doesn't consult a metaclass data descriptor on a write to a class object at all, which is also why it reports an assert_type mismatch on controls.py. The case needs a metaclass attribute declared as ClassVar[Descriptor | bytes], which may or may not be a data descriptor, shadowed by a class attribute of an unrelated type, so the value has to be assignable to both list[int] and list[str]. The declarations also conflict over the write itself: the spec says a ClassVar "should not be set on class instances", and Child is an instance of Meta, while C declares a: list[int] = [], an instance variable with a default. The spec doesn't say which declaration governs Child.a. I don't see a real alternative to what the PR does here.

I'll post on DPO for a consensus. I wouldn't treat the partial.py case as blocking; it exposed a limitation of the typing spec.

@crypt0lith

Copy link
Copy Markdown
Contributor Author

I'll post on DPO for a consensus.

Posted here: https://discuss.python.org/t/clarifying-classvar-on-metaclasses/110326

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants