Skip to content

Commit 2eb9fe9

Browse files
[3.12] gh-103968: What's New: Add porting hints for PyType_From with metaclasses (GH-105698) (GH-106619)
gh-103968: What's New: Add porting hints for PyType_From with metaclasses (GH-105698) (cherry picked from commit af5cf1e) Co-authored-by: Petr Viktorin <encukou@gmail.com>
1 parent 30870c8 commit 2eb9fe9

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

Doc/whatsnew/3.12.rst

+25-1
Original file line numberDiff line numberDiff line change
@@ -1836,7 +1836,31 @@ Porting to Python 3.12
18361836
allowing incomplete initialization.
18371837

18381838
Note that :c:func:`PyType_FromMetaclass` (added in Python 3.12)
1839-
already disallows creating classes whose metaclass overrides ``tp_new``.
1839+
already disallows creating classes whose metaclass overrides ``tp_new``
1840+
(:meth:`~object.__new__` in Python).
1841+
1842+
Since ``tp_new`` overrides almost everything ``PyType_From*`` functions do,
1843+
the two are incompatible with each other.
1844+
The existing behavior -- ignoring the metaclass for several steps
1845+
of type creation -- is unsafe in general, since (meta)classes assume that
1846+
``tp_new`` was called.
1847+
There is no simple general workaround. One of the following may work for you:
1848+
1849+
- If you control the metaclass, avoid using ``tp_new`` in it:
1850+
1851+
- If initialization can be skipped, it can be done in
1852+
:c:member:`~PyTypeObject.tp_init` instead.
1853+
- If the metaclass doesn't need to be instantiated from Python,
1854+
set its ``tp_new`` to ``NULL`` using
1855+
the :const:`Py_TPFLAGS_DISALLOW_INSTANTIATION` flag.
1856+
This makes it acceptable for ``PyType_From*`` functions.
1857+
1858+
- Avoid ``PyType_From*`` functions: if you don't need C-specific features
1859+
(slots or setting the instance size), create types by :ref:`calling <call>`
1860+
the metaclass.
1861+
1862+
- If you *know* the ``tp_new`` can be skipped safely, filter the deprecation
1863+
warning out using :func:`warnings.catch_warnings` from Python.
18401864

18411865
* :c:var:`PyOS_InputHook` and :c:var:`PyOS_ReadlineFunctionPointer` are no
18421866
longer called in :ref:`subinterpreters <sub-interpreter-support>`. This is

0 commit comments

Comments
 (0)