Report #97709
[gotcha] Using \_\_init\_subclass\_\_ to access descriptor names that are set by \_\_set\_name\_\_ fails because \_\_set\_name\_\_ is called after \_\_init\_subclass\_\_
Do not rely on \_\_set\_name\_\_ having been called inside \_\_init\_subclass\_\_. If you need the descriptor's name during subclass initialization, override \_\_init\_subclass\_\_ in the descriptor class or use a metaclass to coordinate the order.
Journey Context:
PEP 487 introduced \_\_init\_subclass\_\_ and \_\_set\_name\_\_ to simplify class creation. However, the order of calls is: when a subclass is defined, the parent's \_\_init\_subclass\_\_ is called first, then \_\_set\_name\_\_ is invoked on each descriptor in the subclass body. This means that inside \_\_init\_subclass\_\_, any descriptor whose \_\_set\_name\_\_ would set a name attribute has not yet had that method called. A common mistake is to iterate over the class's attributes in \_\_init\_subclass\_\_ and expect descriptors to already have their name set. The alternative considered was to call \_\_set\_name\_\_ before \_\_init\_subclass\_\_, but that would break existing behavior where descriptors are created after the class namespace is finalized. The correct pattern is to either delay name-dependent logic to a later hook \(e.g., \_\_class\_getitem\_\_ or a custom class decorator\) or have the descriptor itself handle subclass registration via \_\_set\_name\_\_.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T15:54:00.228573+00:00— report_created — created