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 — Add basic pyobject c-api functions by bschoenmaeckers · Pull Request #7872 · RustPython/RustPython

Conversation

@bschoenmaeckers

@bschoenmaeckers bschoenmaeckers commented May 13, 2026 •
edited by coderabbitai Bot
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor

Summary by CodeRabbit

  • New Features
    • Extended C-API compatibility layer with support for object attribute access and manipulation.
    • Added object introspection and string representation capabilities.
    • Enhanced support for Python C extensions interoperability.

Review Change Stack

Sorry, something went wrong.

Uh oh!

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

All reactions
@bschoenmaeckers
Add basic pyobject c-api functions
683e008
@coderabbitai

coderabbitai Bot commented May 13, 2026 •
edited
Loading

Uh oh!

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

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This PR expands RustPython's C-API surface with seven new extern "C" functions. It adds attribute getters and setters (PyObject_GetAttr, PyObject_GetAttrString, PyObject_SetAttr, PyObject_SetAttrString), and object conversion helpers (PyObject_Repr, PyObject_Str, PyObject_IsTrue). These functions handle null pointers and type conversions transparently while delegating to the VM's existing object methods.

Changes

Object C-API Functions

Layer / File(s) Summary
Import and dependency setup
crates/capi/src/object.rs (lines 3–5)
Updated imports add C-interop helpers (CStr, c_char) and pointer utilities (NonNull), and expand rustpython_vm::builtins to support the new C-API functions.
Attribute access and mutation functions
crates/capi/src/object.rs (lines 50–107)
PyObject_GetAttr / PyObject_GetAttrString fetch attributes from objects; PyObject_SetAttr / PyObject_SetAttrString set attributes. Name conversion from PyStr or UTF-8 CStr and value cloning precede delegation to the VM's get_attr / set_attr methods.
Object conversion and truthiness helpers
crates/capi/src/object.rs (lines 109–137)
PyObject_Repr and PyObject_Str produce string representations (returning "<NULL>" for null pointers); PyObject_IsTrue tests object truthiness. All use with_vm and null handling for safety.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested reviewers

  • ShaharNaveh

Poem

A rabbit hops through code so bright, 🐰
Adding GetAttr, SetAttr with might,
Repr, Str, and IsTrue all fine,
C-API surface now does shine,
Seven functions intertwine!

🚥 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 accurately summarizes the main change: adding C-API functions for PyObject operations like GetAttr, SetAttr, Repr, Str, and IsTrue.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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
  • X
  • Mastodon
  • Reddit
  • LinkedIn

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

All reactions

Sorry, something went wrong.

Uh oh!

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

coderabbitai[bot]
coderabbitai Bot reviewed May 13, 2026
View reviewed changes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

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 `@crates/capi/src/object.rs`:
- Around line 87-89: The code currently uses
CStr::from_ptr(attr_name).to_str().expect(...) which will panic on invalid
UTF-8; instead decode the C string and handle errors by converting the UTF-8
error into a Python exception and returning the appropriate error indicator
(e.g., null pointer or error code) from the surrounding FFI function. Replace
the .expect() on to_str() with a match or map_err that calls the Python C-API to
set an exception (e.g., PyErr_SetString(PyExc_UnicodeDecodeError, ... ) or the
project's helper for raising Python errors), include the invalid data/error
message, and then return early from the function using the function's error
return convention; update uses of the local variable name accordingly after
successful decoding.
- Around line 70-74: The code currently calls
CStr::from_ptr(attr_name).to_str().expect(...), which will panic on invalid
UTF-8; replace the expect with explicit error handling by matching the Result
from to_str(): on Ok(s) assign s to name, on Err(e) set a Python exception (e.g.
PyErr_SetString(PyExc_ValueError, format!("invalid UTF-8 in attribute name: {}",
e).as_ptr()) or using pyo3::exceptions::PyValueError::new_err(...)) and return
the function's error sentinel (NULL for pointer returns or -1 for int returns).
Update the block around CStr::from_ptr(attr_name) / to_str() to use match or
map_err so attr_name decoding never panics and the function returns a
Python-level error instead; reference the variables/functions attr_name, name,
CStr::from_ptr and to_str when making the change.
🪄 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: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: f82b4ad9-daf1-4860-9a13-70f1be3e791c

📥 Commits

Reviewing files that changed from the base of the PR and between ef375be and 683e008.

📒 Files selected for processing (1)
  • crates/capi/src/object.rs

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread crates/capi/src/object.rs
Comment on lines +70 to +74
let name = unsafe {
CStr::from_ptr(attr_name)
.to_str()
.expect("attribute name must be valid UTF-8")
};

@coderabbitai coderabbitai Bot May 13, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace .expect() with proper error handling to avoid panics.

The .expect() call will panic if attr_name contains invalid UTF-8, crashing the entire process. In C APIs, panics cannot be caught by C callers. Instead, convert UTF-8 errors to Python exceptions.

🛡️ Proposed fix to handle UTF-8 decode errors gracefully
         let obj = unsafe { &*obj };
-        let name = unsafe {
-            CStr::from_ptr(attr_name)
-                .to_str()
-                .expect("attribute name must be valid UTF-8")
-        };
+        let name = unsafe { CStr::from_ptr(attr_name) }
+            .to_str()
+            .map_err(|_| vm.new_unicode_decode_error("attribute name must be valid UTF-8".to_owned()))?;
         obj.get_attr(name, vm)
🤖 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 `@crates/capi/src/object.rs` around lines 70 - 74, The code currently calls
CStr::from_ptr(attr_name).to_str().expect(...), which will panic on invalid
UTF-8; replace the expect with explicit error handling by matching the Result
from to_str(): on Ok(s) assign s to name, on Err(e) set a Python exception (e.g.
PyErr_SetString(PyExc_ValueError, format!("invalid UTF-8 in attribute name: {}",
e).as_ptr()) or using pyo3::exceptions::PyValueError::new_err(...)) and return
the function's error sentinel (NULL for pointer returns or -1 for int returns).
Update the block around CStr::from_ptr(attr_name) / to_str() to use match or
map_err so attr_name decoding never panics and the function returns a
Python-level error instead; reference the variables/functions attr_name, name,
CStr::from_ptr and to_str when making the change.

Sorry, something went wrong.

Uh oh!

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

All reactions
Comment thread crates/capi/src/object.rs
Comment on lines +87 to +89
let name = unsafe { CStr::from_ptr(attr_name) }
.to_str()
.expect("attribute name must be valid UTF-8");

@coderabbitai coderabbitai Bot May 13, 2026

Copy link
Copy Markdown
Contributor

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace .expect() with proper error handling to avoid panics.

Same issue as in PyObject_GetAttrString: the .expect() call will panic on invalid UTF-8, crashing the process. Convert UTF-8 errors to Python exceptions instead.

🛡️ Proposed fix to handle UTF-8 decode errors gracefully
         let obj = unsafe { &*obj };
-        let name = unsafe { CStr::from_ptr(attr_name) }
-            .to_str()
-            .expect("attribute name must be valid UTF-8");
+        let name = unsafe { CStr::from_ptr(attr_name) }
+            .to_str()
+            .map_err(|_| vm.new_unicode_decode_error("attribute name must be valid UTF-8".to_owned()))?;
         let value = unsafe { &*value }.to_owned();
🤖 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 `@crates/capi/src/object.rs` around lines 87 - 89, The code currently uses
CStr::from_ptr(attr_name).to_str().expect(...) which will panic on invalid
UTF-8; instead decode the C string and handle errors by converting the UTF-8
error into a Python exception and returning the appropriate error indicator
(e.g., null pointer or error code) from the surrounding FFI function. Replace
the .expect() on to_str() with a match or map_err that calls the Python C-API to
set an exception (e.g., PyErr_SetString(PyExc_UnicodeDecodeError, ... ) or the
project's helper for raising Python errors), include the invalid data/error
message, and then return early from the function using the function's error
return convention; update uses of the local variable name accordingly after
successful decoding.

Sorry, something went wrong.

Uh oh!

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

All reactions
youknowone
youknowone approved these changes May 14, 2026
View reviewed changes

@youknowone youknowone left a comment

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

Choose a reason for hiding this comment

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

👍

Sorry, something went wrong.

Uh oh!

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

All reactions
@youknowone
youknowone merged commit 11e991f into RustPython:main May 14, 2026
25 checks passed

Uh oh!

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

@bschoenmaeckers
bschoenmaeckers deleted the c-api-object branch May 16, 2026 12:28
@coderabbitai coderabbitai Bot mentioned this pull request May 20, 2026
Add bool support to c-api #7938
Merged
This was referenced Jun 1, 2026
Update PyO3 to 0.29 & enable c-api tests #8000
Merged
Add more object functions to c-api #8042
Merged
@coderabbitai coderabbitai Bot mentioned this pull request Jun 25, 2026
Add more object c-api's #8170
Merged
youknowone pushed a commit that referenced this pull request Sep 16, 2026
@bschoenmaeckers
Add basic pyobject c-api functions (#7872)
399ba4f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@coderabbitai coderabbitai[bot] coderabbitai[bot] left review comments
@youknowone youknowone youknowone approved these changes

Uh oh!

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

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

Uh oh!

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

2 participants

@bschoenmaeckers @youknowone
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 01402520 — 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.