From a68aeebd2ce06f5e8d2377813606942b697f39ab Mon Sep 17 00:00:00 2001 From: Stan Ulbrych Date: Sun, 22 Feb 2026 22:05:23 +0000 Subject: [PATCH] Add support to `str.maketrans` --- Lib/test/test_str.py | 7 +++++++ .../2026-02-22-22-05-09.gh-issue-145118.TaKMJE.rst | 1 + Objects/unicodeobject.c | 2 +- 3 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core_and_Builtins/2026-02-22-22-05-09.gh-issue-145118.TaKMJE.rst diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 0a8dddb026f6c8..4f57499af70f4d 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -454,6 +454,13 @@ def test_maketrans_translate(self): self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})), "[<\u20ac>\xe9]") + # with frozendict + tbl = self.type2test.maketrans(frozendict({'s': 'S', 'T': 't'})) + self.assertEqual(tbl, {ord('s'): 'S', ord('T'): 't'}) + self.assertEqual('sTan'.translate(tbl), 'Stan') + tbl = self.type2test.maketrans(frozendict({'a': None, 'b': ''})) + self.checkequalnofix('c', 'abababc', 'translate', tbl) + # invalid Unicode characters invalid_char = 0x10ffff+1 for before in "a\xe9\u20ac\U0010ffff": diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-02-22-22-05-09.gh-issue-145118.TaKMJE.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-22-22-05-09.gh-issue-145118.TaKMJE.rst new file mode 100644 index 00000000000000..fccc3bc2a1804e --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-02-22-22-05-09.gh-issue-145118.TaKMJE.rst @@ -0,0 +1 @@ +:meth:`str.maketrans` now accepts :class:`frozendict`. diff --git a/Objects/unicodeobject.c b/Objects/unicodeobject.c index fdcbcf51cb62c2..988e5f95573fe1 100644 --- a/Objects/unicodeobject.c +++ b/Objects/unicodeobject.c @@ -13149,7 +13149,7 @@ unicode_maketrans_impl(PyObject *x, PyObject *y, PyObject *z) const void *data; /* x must be a dict */ - if (!PyDict_CheckExact(x)) { + if (!PyAnyDict_CheckExact(x)) { PyErr_SetString(PyExc_TypeError, "if you give only one argument " "to maketrans it must be a dict"); goto err;