Skip to content

feat: accept C++ integers as a key in operator[] - #6291

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

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

Conversation

@henryiii

Copy link
Copy Markdown
Collaborator

🤖 AI text below 🤖

Description

Closes #1309. Alternative to #6286 that follows the review there: only integer keys are accepted, and other key types still need an explicit py::cast(key).

obj[key] now accepts a C++ integer, for example d[1], d[-1], d[std::size_t{2}] and o[1][2]. The key is built with py::int_.

The change adds one constrained template overload of object_api::operator[]. The handle, object && and const char * overloads are unchanged.

bool and character types are excluded. d['a'] would otherwise become the key 97, while py::cast gives a str.

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.

Behaviour change: obj[0] compiled before, because the literal 0 converted to a null const char * and went to py::str(nullptr). It is now the integer key 0.

is_std_char_type moves from cast.h to detail/common.h so that pytypes.h can use it.

Suggested changelog entry:

  • operator[] on py::object, py::dict and accessors now accepts a C++ integer as the key (for example d[1]). The literal 0 is now the integer key 0; before, it was a null const char *.

Assisted-by: ClaudeCode:claude-fable-5-2

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?

1 participant