Skip to content

Commit af5cf1e

Browse files
authored
gh-103968: What's New: Add porting hints for PyType_From with metaclasses (GH-105698)
1 parent e5c32a8 commit af5cf1e

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
@@ -1837,7 +1837,31 @@ Porting to Python 3.12
18371837
allowing incomplete initialization.
18381838

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

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

0 commit comments

Comments
 (0)