Skip to content

Conversation

@blhsing
Copy link
Contributor

@blhsingblhsing commented Jul 5, 2024

This PR allows a mapping as the __dict__ attribute of an object. This was originally meant to allow a mapping to be passed as the globals argument to exec and eval, but for consistency the global namespace of a module should be allowed to be a mapping as well, and by extension the __dict__ attribute of any object.

Full backwards compatibility is maintained by adding a PyDict_Check-guarded fast path to existing PyDict_* function calls with a fallback to their PyMapping_* equivalent API calls. A unified dict/mapping API in the form of helper macros is introduced to avoid potential code clutter from adding such a conditional statement to every PyDict_* call.

Note that some PyDict_* functions do not have direct PyMapping_* equivalents so calls to those functions have to be switched to similar functions that do have PyMapping_* equivalents. These include:

  • PyDict_Pop(dict, key, NULL) is replaced with PyDict_DelItem(dict, key); the former does not raise KeyError while the latter does, so the caller has to handle error differently.
  • PyDict_GetItemWithError is replaced with PyDict_GetItemRef; the former returns a borrowed reference while the latter creates a new ref so the caller has to account for the new ref accordingly.

Tests that expected SystemError or TypeError from a non-dict global namspace have been revised to reflect the new capability.

@blhsingblhsing changed the title gh-121306: allow a mapping, rather than just a dict subclass, as globalsgh-121306: allow a mapping as the globals argument to exec and evalJul 8, 2024
@blhsingblhsing requested a review from methane as a code ownerJuly 11, 2024 04:27
@blhsingblhsing marked this pull request as draft July 11, 2024 05:13
@blhsingblhsing changed the title gh-121306: allow a mapping as the globals argument to exec and evalgh-121306: allow a mapping as __dict__ of objectJul 12, 2024
@blhsingblhsing marked this pull request as ready for review July 12, 2024 02:17
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

@blhsing@serhiy-storchaka