Force the builtin module key to be the correct type. (#2814)

* Force the builtin module key to be the correct type.

Previously it was always going to be a std::string which converted into
unicode. Python 2 appears to want module keys to be normal str types, so
this was breaking code that expected plain string types in the
builtins.keys() data structure

* Add a simple unit test to ensure all built-in keys are str

* Update the unit test so it will also run on pypy

* Run pre-commit.

Co-authored-by: Jesse Clemens <jesse.clemens@sony.com>
This commit is contained in:
crimsoncor 2021-01-24 12:17:28 -05:00 committed by GitHub
parent 08bca374fd
commit 9ea39dc356
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 1 deletions

View File

@ -266,7 +266,7 @@ PYBIND11_NOINLINE inline internals &get_internals() {
const PyGILState_STATE state;
} gil;
constexpr auto *id = PYBIND11_INTERNALS_ID;
PYBIND11_STR_TYPE id(PYBIND11_INTERNALS_ID);
auto builtins = handle(PyEval_GetBuiltins());
if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
internals_pp = static_cast<internals **>(capsule(builtins[id]));

View File

@ -75,3 +75,16 @@ def test_duplicate_registration():
"""Registering two things with the same name"""
assert m.duplicate_registration() == []
def test_builtin_key_type():
"""Test that all the keys in the builtin modules have type str.
Previous versions of pybind11 would add a unicode key in python 2.
"""
if hasattr(__builtins__, "keys"):
keys = __builtins__.keys()
else: # this is to make pypy happy since builtins is different there.
keys = __builtins__.__dict__.keys()
assert {type(k) for k in keys} == {str}