Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/pybind11/detail/internals.h
Original file line number Diff line number Diff line change
Expand Up @@ -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]));
Expand Down
13 changes: 13 additions & 0 deletions tests/test_modules.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why not simply always go through __builtins__.__dict__.keys()? It works in CPython and PyPy.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

answered in gitter, but I'll add here as well. Python 2 has the following amazing feature

    In module __main__:
        __builtins__ is a reference to module __builtin__.
        __builtin__ only exists if you import it.
    In any other module:
        __builtins__ is a reference to module __builtin__'s __dict__.
        __builtin__ only exists if you import it.

so we need to handle both cases.

Copy link
Collaborator

Choose a reason for hiding this comment

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

sigh


assert {type(k) for k in keys} == {str}