Skip to content

Store nested classes themselves on the outer class (#875) - #907

Open
HoneyBearTech wants to merge 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-nested-class-attr
Open

HoneyBearTech wants to merge 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-nested-class-attr

Conversation

@HoneyBearTech

Copy link
Copy Markdown
Contributor

Refs #875

What was broken
A class defined inside another class's body stayed on the outer class as the internal EvalLocalVar placeholder, not the class itself. So once the outer class was built, Outer.Inner behaved differently from Python:

class Outer:
    class Inner:
        pass

class Bar:
    y: Outer.Inner | None = None   # TypeError: unsupported operand type(s) for |: 'EvalLocalVar' and 'NoneType'

type(Outer.Inner()) is Outer.Inner  # False

This is the same error as #875, for a class nested in another class.

What I changed
Just before the outer class is created, each defined EvalLocalVar in its namespace is replaced by the value it holds. The placeholder objects themselves aren't changed, so methods that use the nested class by its bare name keep working as before. A class namespace that isn't a plain dict, such as one returned by a custom metaclass __prepare__, is left as it is.

Testing

  • New tests in tests/test_unit_eval.py, compared against CPython:
    • Outer.Inner | None, at module level and in another class's annotations;
    • type(Outer.Inner()) is Outer.Inner and isinstance;
    • a dataclass with a nested dataclass;
    • two levels of nesting.
  • Further tests:
    • one pins the bare-name method behaviour;
    • two check custom __prepare__ namespaces.
  • The full test suite, ruff, pylint, mypy and codespell pass on Python 3.14.

Note
#902 and #906 also change ast_classdef, in different lines. Whichever merges later may need a small rebase; I'm happy to do it.

…#875)

A class defined inside a class body was left on the outer class as the
internal EvalLocalVar placeholder instead of the class itself. So after
the outer class was created, Outer.Inner | None raised the same
TypeError as in custom-components#875, and type(Outer.Inner()) is Outer.Inner was False.

Before the outer class is created, replace each defined EvalLocalVar in
a plain dict class namespace with the value it holds. The placeholders
themselves are left alone, so methods that read the nested class by its
bare name keep working as before. A class namespace that isn't a plain
dict, such as a mapping returned by a custom metaclass __prepare__, is
left as it is.

Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
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.

1 participant