Skip to content

interp: compute __abstractmethods__ in _abc_init and propagate __isabstractmethod__#554

Open
fregataa wants to merge 2 commits into
youknowone:mainfrom
fregataa:interp/abc-abstractmethods
Open

interp: compute __abstractmethods__ in _abc_init and propagate __isabstractmethod__#554
fregataa wants to merge 2 commits into
youknowone:mainfrom
fregataa:interp/abc-abstractmethods

Conversation

@fregataa

@fregataa fregataa commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Summary

_abc_init only set up _abc_registry and never computed __abstractmethods__, so ABCs were freely instantiable and inspect.isabstract always returned False. This PR completes the ABC abstract-method machinery.

  • _abc_init computes __abstractmethods__ — new compute_abstract_methods (mirrors _abcmodule.c / app_abc.py): the abstract members in cls.__dict__ plus those inherited from bases and not overridden with a concrete member.
  • property.__isabstractmethod__ getset descriptor (isabstract(fget) or fset or fdel).
  • staticmethod/classmethod __new__ honour the subtype, so the legacy abstractstaticmethod/abstractclassmethod subclasses behave correctly (subtype instance returned, __init__ runs, class-level __isabstractmethod__ = True is visible).
  • w_type_get_flags reports Py_TPFLAGS_IS_ABSTRACT from the existing flag_abstract, which inspect.isabstract reads.

Test

python -m test test_abc: 24 failures + 8 errors → 11 failures, 0 errors.

Remaining test_abc failures are unrelated to this change:

  • test_abstractproperty_basics / test_descriptors_with_abstractmethod are blocked by a separate super().<property> bug (property __get__ is not invoked through super), reproducible independently of abc.
  • test_issubclass_bad_arguments is a pre-existing issubclass() argument-validation gap.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Abstract base classes now automatically track abstract methods inherited from parent classes.
    • Abstract properties are recognized when their getter, setter, or deleter is abstract.
    • Static methods and class methods created through subclasses now correctly preserve the subclass type.
    • Type information now reports when a class is abstract.
  • Bug Fixes

    • Improved handling of overridden methods and abstract members during class initialization.

…stractmethod__

`_abc_init` only set up `_abc_registry` and never computed
`__abstractmethods__`, so ABCs were freely instantiable and
`inspect.isabstract` always returned False. Add `compute_abstract_methods`
(mirrors `_abcmodule.c` / `app_abc.py`): collect the abstract members in
`cls.__dict__` plus those inherited from bases and not overridden, and store
them on `cls.__abstractmethods__`.

Also wire up the abstract-method flag on the descriptor wrappers:
- property gains an `__isabstractmethod__` getset (fget/fset/fdel).
- staticmethod/classmethod `__new__` honour the subtype, so the legacy
  `abstractstaticmethod`/`abstractclassmethod` subclasses behave correctly.
- `w_type_get_flags` reports `Py_TPFLAGS_IS_ABSTRACT` from `flag_abstract`,
  which `inspect.isabstract` reads.

test_abc: 24 failures + 8 errors -> 11 failures, 0 errors.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 14, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@fregataa, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: d6687dd3-8350-4d76-b210-25eac7fe3517

📥 Commits

Reviewing files that changed from the base of the PR and between e6b02d3 and 4cb3e74.

📒 Files selected for processing (1)
  • pyre/pyre-interpreter/src/module/_abc/mod.rs

Walkthrough

ABC initialization now derives inherited and local abstract methods, descriptors expose abstractness, subclass descriptor constructors preserve their type, and type flags include the abstract-class bit.

Changes

Abstract class support

Layer / File(s) Summary
Descriptor abstractness behavior
pyre/pyre-interpreter/src/typedef.rs
staticmethod and classmethod constructors preserve valid subclasses, while property.__isabstractmethod__ reflects abstract accessors.
Abstract method computation
pyre/pyre-interpreter/src/module/_abc/mod.rs
ABC initialization scans class members and bases, resolves abstract names, and stores them as a frozenset.
Abstract type flags
pyre/pyre-object/src/typeobject.rs
w_type_get_flags reports Py_TPFLAGS_IS_ABSTRACT from the tracked abstract state.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant abc_init
  participant compute_abstract_methods
  participant ClassDictionary
  participant BaseClasses
  abc_init->>compute_abstract_methods: compute cls.__abstractmethods__
  compute_abstract_methods->>ClassDictionary: inspect class members
  compute_abstract_methods->>BaseClasses: incorporate inherited abstract names
  compute_abstract_methods-->>abc_init: assign frozenset
Loading

Possibly related PRs

  • youknowone/pyre#526: Updates abstract-state handling, __abstractmethods__, and abstract instantiation behavior.

Suggested labels: z-ca-2026

Suggested reviewers: youknowone, lifthrasiir

Poem

I twitch my nose at abstract lore,
Descriptors bloom with types galore.
Frozensets gather names just right,
And flags now shine with abstract light.
Hop, hop—ABC stands tall!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the main interpreter changes around abstractmethods computation and isabstractmethod handling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6b02d35b6

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +68 to +72
let base_abstracts = match crate::baseobjspace::getattr_str(base, "__abstractmethods__") {
Ok(v) if !v.is_null() => v,
_ => continue,
};
for name_obj in unsafe { w_set_items(base_abstracts) } {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Iterate inherited abstracts through Python protocol

When a base class has a user-assigned __abstractmethods__ such as None/a list, or a metaclass lookup raises a non-AttributeError, _py_abc.py's for name in getattr(base, "__abstractmethods__", set()) uses normal iteration and propagates non-missing errors. This branch instead treats every error as missing and then unconditionally casts whatever value was returned with w_set_items, whose safety contract requires a real set object; subclass creation can silently ignore lookup failures or dereference a non-set object rather than raising/iterating correctly.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@pyre/pyre-interpreter/src/module/_abc/mod.rs`:
- Around line 35-43: Update is_abstract to delegate directly to the existing
baseobjspace::isabstractmethod_w helper, preserving its Result<bool, PyError>
behavior. Remove the duplicated getattr, truthiness, and AttributeError handling
while leaving the null guards at both call sites unchanged.
- Around line 65-92: Guard the inherited __abstractmethods__ value before
iterating in the abstract-method resolution loop: validate it with the existing
set-or-frozenset check before calling w_set_items, and validate each name object
with the existing string check before calling w_str_get_value_opt. Skip invalid
values, matching the safety pattern used by abstract_instantiation_error.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: cd855e8c-f1f5-4c52-bbd4-07d1144182f4

📥 Commits

Reviewing files that changed from the base of the PR and between 8df6bf3 and e6b02d3.

📒 Files selected for processing (3)
  • pyre/pyre-interpreter/src/module/_abc/mod.rs
  • pyre/pyre-interpreter/src/typedef.rs
  • pyre/pyre-object/src/typeobject.rs

Comment on lines +35 to +43
// `getattr(value, "__isabstractmethod__", False)` truthiness (`app_abc.py`).
fn is_abstract(value: PyObjectRef) -> Result<bool, crate::PyError> {
match crate::baseobjspace::getattr_str(value, "__isabstractmethod__") {
Ok(v) if !v.is_null() => crate::baseobjspace::is_true(v),
Ok(_) => Ok(false),
Err(e) if e.kind == crate::PyErrorKind::AttributeError => Ok(false),
Err(e) => Err(e),
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reimplements baseobjspace::isabstractmethod_w instead of calling it.

Both call sites (lines 59, 87) already null-guard value before invoking is_abstract, so this can just delegate to the existing canonical helper rather than re-encoding the same getattr + truthiness + AttributeError-swallow logic a second time.

♻️ Proposed simplification
 fn is_abstract(value: PyObjectRef) -> Result<bool, crate::PyError> {
-    match crate::baseobjspace::getattr_str(value, "__isabstractmethod__") {
-        Ok(v) if !v.is_null() => crate::baseobjspace::is_true(v),
-        Ok(_) => Ok(false),
-        Err(e) if e.kind == crate::PyErrorKind::AttributeError => Ok(false),
-        Err(e) => Err(e),
-    }
+    crate::baseobjspace::isabstractmethod_w(value)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// `getattr(value, "__isabstractmethod__", False)` truthiness (`app_abc.py`).
fn is_abstract(value: PyObjectRef) -> Result<bool, crate::PyError> {
match crate::baseobjspace::getattr_str(value, "__isabstractmethod__") {
Ok(v) if !v.is_null() => crate::baseobjspace::is_true(v),
Ok(_) => Ok(false),
Err(e) if e.kind == crate::PyErrorKind::AttributeError => Ok(false),
Err(e) => Err(e),
}
}
// `getattr(value, "__isabstractmethod__", False)` truthiness (`app_abc.py`).
fn is_abstract(value: PyObjectRef) -> Result<bool, crate::PyError> {
crate::baseobjspace::isabstractmethod_w(value)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pyre/pyre-interpreter/src/module/_abc/mod.rs` around lines 35 - 43, Update
is_abstract to delegate directly to the existing
baseobjspace::isabstractmethod_w helper, preserving its Result<bool, PyError>
behavior. Remove the duplicated getattr, truthiness, and AttributeError handling
while leaving the null guards at both call sites unchanged.

Comment thread pyre/pyre-interpreter/src/module/_abc/mod.rs
compute_abstract_methods' Stage 2 fed base.__abstractmethods__ straight into
w_set_items / w_str_get_value_opt, which cast without a type check. Since the
__abstractmethods__ setter marks any truthy value abstract, a non-set value
(e.g. `C.__abstractmethods__ = [1, 2, 3]`) type-confused and aborted when a
subclass was created. Guard with is_set_or_frozenset / is_str, matching the
existing abstract_instantiation_error pattern.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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