Skip to content

feat: accept any castable type as a key in operator[] - #6286

Open
henryiii wants to merge 1 commit into
pybind:masterfrom
henryiii:feat/item-accessor-any-key
Open

henryiii wants to merge 1 commit into
pybind:masterfrom
henryiii:feat/item-accessor-any-key

Conversation

@henryiii

@henryiii henryiii commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

The key difference here is that it's a constrained template, so that the old fast-paths can keep working. Every one of the three current specialization does something useful: const char * avoids alocation and copy, py::handle can't be done generally (would take/drop refcounts), and even py::object && avoids a borrow and move.

I didn't do any of the other accessors, but getattr and maybe setattr for consistency seems reasonable too.

This fixes a bug: if you pass obj[0], before this PR that 0 matched const char * as nullptr (common C++ annoyance).

🤖 AI text below 🤖

Description

Closes #1309. Supersedes and closes #4004 (and #4007). Thanks to @woodychow and @cielavenir for the original proposal and tests.

obj[key] now accepts any C++ type that py::cast can convert, for example d[2.5], d[std::string("s")], d['c'] and d[std::make_pair(1, 2)]. This is an alternative to #6316, which adds only std::string and std::string_view.

The change replaces the integer overload from #6291 with one constrained template overload of object_api::operator[] that converts the key with py::cast. Integer keys use this overload too. Integers wider than unsigned long long (for example unsigned __int128) are still rejected at compile time, because py::cast would truncate them. bool and character keys are now accepted and become True / a one-character str, the same as py::cast.

The handle, object && and const char * overloads are unchanged, so existing code resolves to the same overload at the same cost. #4004 replaced all three with a catch-all T &&. That sends string literals through py::cast, which builds a temporary std::string, and it loses the implicit conversions to handle (for example from a type with operator PyObject *()).

py::tuple, py::list and py::sequence declare their own operator[], which hides the new overload. t[1] on those types still uses the size_t accessors.

The segfault seen in #4007 was in the tests. The lambdas returned l1[1] with a deduced return type, which is a list_accessor. An accessor holds a non-owning handle to the container and reads the item lazily, so the read occurred after the list was destroyed. This also occurs on master.

Suggested changelog entry:

  • operator[] on py::object, py::dict and accessors now accepts any key type that py::cast can convert (for example d[2.5] or d[std::string("s")]).

@henryiii

henryiii commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator Author

Here's ideas for a followup. I do wonder if this should not close 1309 until getattr is also supported...

🤖 AI text below 🤖

These are the entry points that still accept only Python objects (or const char *), sorted by how useful a cast would be. I read the declarations in pytypes.h but did not prototype any of these.

Entry point Today Would allow Notes
getattr(obj, name, default_) handle default_ py::getattr(o, "x", 42) Named in #1309. Small and low risk.
setattr(obj, name, value) handle value py::setattr(o, "x", 42) o.attr("x") = 42 already casts, so this is only for consistency.
Arithmetic and bitwise operators (+ - * / | & ^ << >> and the = forms) object_api const &other o + 1, o * 2.0 Most useful after operator[]. Higher risk: 18 operators, and a template operand can cause ambiguous overloads in user code.
equal, not_equal, <, <=, >, >= object_api const &other o.equal(1), o < 2 Same risk as arithmetic. == and != must stay as pointer identity on handle.
attr(name), getattr, hasattr, delattr, setattr name argument handle or const char * o.attr(std::string(...)), std::string_view Only strings are valid names, so a std::string overload is sufficient. Low value.
py::len, py::repr, py::hash, py::iter, isinstance handle py::repr(42) Little practical use. I would not change these.

These already cast, so they need no change: contains() on object_api, dict and set; list::append and list::insert; set::add; accessor assignment (d[k] = 42, o.attr("x") = 42); call arguments; make_tuple; print.

operator[] on py::tuple, py::list and py::sequence takes size_t, so l[-1] wraps to a very large index instead of counting from the end. This is a related gap, but it is an index problem, not a cast problem.

I recommend that #6286 stays as it is. The getattr default and setattr value are a good small follow-up. The operators need their own PR because of the overload risk.

@rwgk rwgk left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

My main concern is that obj[key] can hide a fair amount of work for a small convenience.

With the STL caster, a vector used as an index becomes a fresh Python list on every access, with every element converted. That happens as soon as the accessor is created, even though the lookup is lazy. I’d prefer to see that conversion at the call site. Conversion path

There’s also a less obvious identity issue. In a small reproducer with a bound C++ key that uses Python’s default identity hashing, d[key] = 42 followed by d[key] raised KeyError. The two casts created distinct Python objects. Casting once and reusing the Python key worked.

I see the consistency with dict::contains and dict::get. For operator[], could we start with integral keys? obj[1] is useful, and obj[0] fixes the null C-string trap. I’d keep py::cast(key) explicit for compound and user-defined keys, where the cost and identity of the converted key can matter.

@henryiii

Copy link
Copy Markdown
Collaborator Author

I'm trying an int-only version, in #6291. But I don't follow:

In a small reproducer with a bound C++ key that uses Python’s default identity hashing

But keys of dictionaries are supposed to be hashable. object() shouldn't be used as the key of a dictionary. For any well formed key, this should be fine. For a non-well formed key, this isn't much different than expecting dict[object()] to be repeatable.

Most places in pybind11 autocast, I think, so I still think this is fairly sensible.

@rwgk

rwgk commented Nov 21, 2026

Copy link
Copy Markdown
Collaborator

@henryiii, to respond to your comment, I asked codex for advice:

I’d move forward with the integer-only #6291 once Henry marks it ready and CI passes. Keep #6286 open while he looks at consistency across pybind11, then close it as superseded if #6291 lands. Slack discussion · Draft #6291

  • feat: accept C++ integers as a key in operator[] #6291 solves the concrete request. The original issue asks for tpl[1] on a py::object and calls out the trap with 0. I spot-checked the draft. Zero, negative indices, and a full-width unsigned key worked. Existing typed sequence accessors kept their overloads, and floats and containers still require explicit conversion. Original issue · Probe
  • I’d acknowledge Henry’s identity analogy. The two casts behave like two calls to object(). An identity-hashed object is a valid dict key when you reuse that Python object. The surprise is that writing the same C++ key twice can silently create two Python objects. Eager container conversion is the stronger reason to keep the overload narrow. Henry’s reply · Python data model
  • Follow up on Draft: Support arbitrary type in item accessor's subscript operator [with more tests] #4007 separately. Its concrete crash example returns a lazy accessor into a local list. return py::object(l1[1]); materializes the result while the list is alive. I’d ask for a current failing example if the reporter still needs something beyond integer indexing. Crash example

@henryiii

Copy link
Copy Markdown
Collaborator Author

I’d acknowledge Henry’s identity analogy

My issue was not really with that, my issue was you should not make a dictionary with keys you can't recreate unless you are doing something really weird. If you can't recreate the key, but must keep the original key because it's hashed by memory location, then you are already doing something pretty weird, and you should know what you are doing.

🤖 AI text below 🤖

#6286 (any castable key) is more consistent with the rest of pybind11. #6291 (integers only) has no precedent in the object API.

Why #6286 fits

Where #6291 has precedent

  • The integral constraint itself is used in pytypes.h, but for indices and sizes (sequence_item, list_item, tuple_item at lines 1125–1176, and the str/bytes size constructors). Those take plain std::is_integral and go through ssize_t_cast; they do not build a Python key.
  • The exclusion of bool and character types is new. It also gives a small inconsistency of its own: d.contains('a') casts to a str, but d['a'] does not compile.
  • attr(), getattr and setattr take only handle or const char *, so "no autocast on a name or key" does exist, but only for attribute names, where a string is the only valid type.

Trade-off

rwgk's objection to #6286 is cost, not consistency: obj[vec] builds a Python list at each access, and two casts of an identity-hashed bound object give two different keys. Both points apply equally to the existing dict::contains and dict::get, so they do not make #6291 more consistent, only more conservative.

If consistency is the deciding criterion, take #6286. #6291 is the smaller step if you want to settle the review, and it can be widened to #6286 later without a break.

@cielavenir

Copy link
Copy Markdown
Contributor

@henryiii @rwgk what about std::string -> py::str conversion?

@henryiii

Copy link
Copy Markdown
Collaborator Author

I would rather just support any castable type instead of adding every "safe" class one at a time, but yes, std::string is a pretty obvious one to do if we keep going that way.

@cielavenir

Copy link
Copy Markdown
Contributor

@henryiii (@rwgk) I'd like at least std::string support in the next pybind11 release. If supporting any castable type does not go well, I'd appreciate supporting only std::string for now.

Replace the integer overload of object_api::operator[] with a
constrained template overload that converts the key with
pybind11::cast. It also covers integers. Integers wider than
unsigned long long are still rejected, because cast would truncate
them. The handle, object&& and const char* overloads are unchanged.

Closes pybind#1309.

Assisted-by: ClaudeCode:claude-opus-5-5
@henryiii
henryiii force-pushed the feat/item-accessor-any-key branch from 76d445f to a0e7379 Compare November 27, 2026 04:22

This branch has not been deployed

No deployments
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.

Implicit conversion of ints (and char const*) to handles?

3 participants