python / python/cpython

Class creation doesn't call __set_name__ when creating class members in another __set_name__

Open
#122,381 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

When inserting a class member during some other class member's __set_name__ call, the __set_name__ method of the newly-inserted member doesn't get called as expected.

As an example, take this snippet:

class I_Am_Altering_The_Deal:
    def __set_name__(self, owner, name):
        print(f"__set_name__({self.__class__.__name__}, {owner.__name__}, {name!r}")
        owner.han_solo = Pray_I_Dont_Alter_It_Any_Further()
        
class Pray_I_Dont_Alter_It_Any_Further:
    def __set_name__(self, owner, name):
        print(f"__set_name__({self.__class__.__name__}, {owner.__name__}, {name!r}")

class Cloud_City:
    luke_skywalker = I_Am_Altering_The_Deal()

I would expect both __set_name__ functions to be called, resulting in the output:

__set_name__(I_Am_Altering_The_Deal, Cloud_City, 'luke_skywalker')
__set_name__(Pray_I_Dont_Alter_It_Any_Further, Cloud_City, 'han_solo')

But what is actually output, is:

__set_name__(I_Am_Altering_The_Deal, Cloud_City, 'luke_skywalker')

Discovered while testing a PEP-487 implementation for Micropython: micropython/micropython#15503.

Maybe be related to #72983.

CPython versions tested on:

3.8, 3.10, 3.12

Operating systems tested on:

Linux

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

Start by running the issue's class-creation snippet and compare its output with the expected two set_name calls. Read the PEP-487 implementation and the related issue #72983; the fix is complete when a member inserted during another member's set_name call receives its own expected callback, with regression coverage.

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
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.