GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [mypyc] Preserve inherited attribute defaults under separate=True by georgesittas · Pull Request #21547 · python/mypy

[mypyc] Preserve inherited attribute defaults under separate=True #21547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
p-sawicki merged 7 commits into python:master from VaggelisD:fix/mypyc-defaults-setup-cache-load
Jun 3, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

[mypyc] Preserve inherited attribute defaults under separate=True #21547

Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
7 commits
Select commit Hold shift + click to select a range
dcc9641
[mypyc] Preserve inherited attribute defaults under separate=True
georgesittas May 27, 2026
c6cae72
PR feedback: pre-register __mypyc_defaults_setup decl in prepare phase
georgesittas Jun 2, 2026
517beb1
Merge branch 'master' into fix/mypyc-defaults-setup-cache-load
georgesittas Jun 2, 2026
762a755
Fix CI
georgesittas Jun 2, 2026
99451dc
Address PR feedback
georgesittas Jun 3, 2026
2f36f40
Merge branch 'master' into fix/mypyc-defaults-setup-cache-load
georgesittas Jun 3, 2026
8bcbd54
Fixup
georgesittas Jun 3, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view
Prev Previous commit
Next Next commit
Address PR feedback
  • Loading branch information

Uh oh!

There was an error while loading. Please reload this page.

@georgesittas
georgesittas committed Jun 3, 2026
commit 99451dcf734cc08972d464e2814405846ce7c530

There are no files selected for viewing

3 changes: 2 additions & 1 deletion 3 mypyc/codegen/emitclass.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
BITMAP_BITS,
BITMAP_TYPE,
CPYFUNCTION_NAME,
MYPYC_DEFAULTS_SETUP,
NATIVE_PREFIX,
PREFIX,
REG_PREFIX,
Expand Down Expand Up @@ -285,7 +286,7 @@ def emit_line() -> None:

# If the class has a method to initialize default attribute
# values, we need to call it during initialization.
defaults_fn = cl.get_method("__mypyc_defaults_setup")
defaults_fn = cl.get_method(MYPYC_DEFAULTS_SETUP)

# If there is a __init__ method, we'll use it in the native constructor.
init_fn = cl.get_method("__init__")
Expand Down
1 change: 1 addition & 0 deletions 1 mypyc/common.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
LAMBDA_NAME: Final = "__mypyc_lambda__"
PROPSET_PREFIX: Final = "__mypyc_setter__"
SELF_NAME: Final = "__mypyc_self__"
MYPYC_DEFAULTS_SETUP: Final = "__mypyc_defaults_setup"
GENERATOR_ATTRIBUTE_PREFIX: Final = "__mypyc_generator_attribute__"
CPYFUNCTION_NAME = "__cpyfunction__"

Expand Down
42 changes: 12 additions & 30 deletions 42 mypyc/irbuild/classdef.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
is_class_var,
)
from mypy.types import Instance, UnboundType, get_proper_type
from mypyc.common import PROPSET_PREFIX
from mypyc.common import MYPYC_DEFAULTS_SETUP, PROPSET_PREFIX
from mypyc.ir.class_ir import ClassIR, NonExtClassInfo
from mypyc.ir.func_ir import FuncDecl, FuncSignature
from mypyc.ir.ops import (
Expand Down Expand Up @@ -342,9 +342,14 @@ def finalize(self, ir: ClassIR) -> None:
# Call __init_subclass__ after class attributes have been set
self.builder.call_c(py_init_subclass_op, [self.type_obj], self.cdef.line)

attrs_with_defaults, default_assignments = find_attr_initializers(self.builder, self.cdef)
ir.attrs_with_defaults.update(attrs_with_defaults)
generate_attr_defaults_init(self.builder, self.cdef, default_assignments)
# The decl is pre-registered in prepare.py iff the class has its own
# default attribute assignments to emit; skip the body walk otherwise.
if MYPYC_DEFAULTS_SETUP in ir.method_decls:
attrs_with_defaults, default_assignments = find_attr_initializers(
self.builder, self.cdef
)
ir.attrs_with_defaults.update(attrs_with_defaults)
generate_attr_defaults_init(self.builder, self.cdef, default_assignments)
create_ne_from_eq(self.builder, self.cdef)


Expand Down Expand Up @@ -766,9 +771,6 @@ def find_attr_initializers(
for stmt in info.defn.defs.body:
if not isinstance(stmt, AssignmentStmt):
continue
if isinstance(stmt.lvalues[0], NameExpr) and stmt.lvalues[0].name == "__deletable__":
check_deletable_declaration(builder, cls, stmt.line)
continue
name = default_attr_name(stmt, info_ir, cls_type)
if name is None:
continue
Expand Down Expand Up @@ -802,21 +804,21 @@ def generate_attr_defaults_init(
parent_with_defaults: ClassIR | None = None
if builder.options.separate:
for ancestor in cls.mro[1:]:
if "__mypyc_defaults_setup" in ancestor.method_decls:
if MYPYC_DEFAULTS_SETUP in ancestor.method_decls:
parent_with_defaults = ancestor
break

if not default_assignments and parent_with_defaults is None:
return

with builder.enter_method(cls, "__mypyc_defaults_setup", bool_rprimitive):
with builder.enter_method(cls, MYPYC_DEFAULTS_SETUP, bool_rprimitive):
self_var = builder.self()

# Chain to parent's setup so inherited defaults run first; propagate
# its False return so a parent default that raised still aborts
# instance creation rather than being silently swallowed here.
if parent_with_defaults is not None:
decl = parent_with_defaults.method_decl("__mypyc_defaults_setup")
decl = parent_with_defaults.method_decl(MYPYC_DEFAULTS_SETUP)
parent_ok = builder.builder.call(decl, [self_var], [ARG_POS], [None], cdef.line)
fail_block, continue_block = BasicBlock(), BasicBlock()
builder.add(Branch(parent_ok, continue_block, fail_block, Branch.BOOL))
Expand Down Expand Up @@ -848,26 +850,6 @@ def generate_attr_defaults_init(
builder.add(Return(builder.true()))


def check_deletable_declaration(builder: IRBuilder, cl: ClassIR, line: int) -> None:
for attr in cl.deletable:
if attr not in cl.attributes:
if not cl.has_attr(attr):
builder.error(f'Attribute "{attr}" not defined', line)
continue
for base in cl.mro:
if attr in base.property_types:
builder.error(f'Cannot make property "{attr}" deletable', line)
break
else:
_, base = cl.attr_details(attr)
builder.error(
('Attribute "{}" not defined in "{}" ' + '(defined in "{}")').format(
attr, cl.name, base.name
),
line,
)


def create_ne_from_eq(builder: IRBuilder, cdef: ClassDef) -> None:
"""Create a "__ne__" method from a "__eq__" method (if only latter exists)."""
cls = builder.mapper.type_to_ir[cdef.info]
Expand Down
58 changes: 55 additions & 3 deletions 58 mypyc/irbuild/prepare.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@
from mypy.semanal import refers_to_fullname
from mypy.traverser import TraverserVisitor
from mypy.types import Instance, Type, get_proper_type
from mypyc.common import FAST_PREFIX, PROPSET_PREFIX, SELF_NAME, get_id_from_name
from mypyc.common import (
FAST_PREFIX,
MYPYC_DEFAULTS_SETUP,
PROPSET_PREFIX,
SELF_NAME,
get_id_from_name,
)
from mypyc.crash import catch_errors
from mypyc.errors import Errors
from mypyc.ir.class_ir import ClassIR
Expand Down Expand Up @@ -145,6 +151,14 @@ def build_type_map(
if class_ir.is_ext_class and _has_own_default_attrs(cdef, class_ir):
_register_defaults_setup_decl(class_ir, module.fullname)

# Validate __deletable__ declarations. Done here so the compiler exits
# early on invalid input before any IR is built.
for module, cdef in classes:
class_ir = mapper.type_to_ir[cdef.info]
if class_ir.is_ext_class:
with catch_errors(module.path, cdef.line):
_check_deletable_declarations(module.path, cdef, class_ir, errors)

# Collect all the functions also. We collect from the symbol table
# so that we can easily pick out the right copy of a function that
# is conditionally defined. This doesn't include nested functions!
Expand Down Expand Up @@ -441,9 +455,47 @@ def _has_own_default_attrs(cdef: ClassDef, ir: ClassIR) -> bool:

def _register_defaults_setup_decl(ir: ClassIR, module_name: str) -> None:
sig = FuncSignature([RuntimeArg(SELF_NAME, RInstance(ir))], bool_rprimitive)
ir.method_decls["__mypyc_defaults_setup"] = FuncDecl(
"__mypyc_defaults_setup", ir.name, module_name, sig
ir.method_decls[MYPYC_DEFAULTS_SETUP] = FuncDecl(
MYPYC_DEFAULTS_SETUP, ir.name, module_name, sig
)


def _check_deletable_declarations(path: str, cdef: ClassDef, ir: ClassIR, errors: Errors) -> None:
"""Validate that attributes listed in __deletable__ refer to definable
attributes on the class.

Runs in the prepare phase so we exit early on invalid programs before
any IR is built.
"""
if not ir.deletable:
return
line = next(
(
stmt.line
for stmt in cdef.info.defn.defs.body
if isinstance(stmt, AssignmentStmt)
and isinstance(stmt.lvalues[0], NameExpr)
and stmt.lvalues[0].name == "__deletable__"
),
cdef.line,
)
for attr in ir.deletable:
if attr not in ir.attributes:
if not ir.has_attr(attr):
errors.error(f'Attribute "{attr}" not defined', path, line)
continue
for base in ir.mro:
if attr in base.property_types:
errors.error(f'Cannot make property "{attr}" deletable', path, line)
break
else:
_, base = ir.attr_details(attr)
errors.error(
f'Attribute "{attr}" not defined in "{ir.name}" '
f'(defined in "{base.name}")',
path,
line,
)


def prepare_class_def(
Expand Down
4 changes: 2 additions & 2 deletions 4 mypyc/irbuild/util.py
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def dataclass_type(cdef: ClassDef) -> str | None:
return None


def defaults_skip(stmt: AssignmentStmt, cls_type: str | None) -> bool:
def _defaults_skip(stmt: AssignmentStmt, cls_type: str | None) -> bool:
"""Whether a class-level default assignment is skipped when emitting
__mypyc_defaults_setup, based on class type.

Expand Down Expand Up @@ -138,7 +138,7 @@ def default_attr_name(stmt: AssignmentStmt, ir: ClassIR, cls_type: str | None) -
name = lvalue.name
if name in ("__slots__", "__deletable__") or name not in ir.attributes:
return None
if defaults_skip(stmt, cls_type):
if _defaults_skip(stmt, cls_type):
return None
if isinstance(stmt.rvalue, RefExpr) and stmt.rvalue.fullname == "builtins.None":
attr_type = ir.attributes[name]
Expand Down
3 changes: 2 additions & 1 deletion 3 mypyc/test-data/irbuild-classes.test
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -1135,7 +1135,7 @@ class Ok2:
__deletable__ = ['x']
x: int

[case testInvalidDeletableAttribute]
[case testDeleteNonDeletableAttribute]
class NotDeletable:
__deletable__ = ['x']
x: int
Expand All @@ -1146,6 +1146,7 @@ def g(o: NotDeletable) -> None:
del o.y # E: "y" cannot be deleted \
# N: Using "__deletable__ = ['<attr>']" in the class body enables "del obj.<attr>"

[case testInvalidDeletableAttribute]
class Base:
x: int

Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.