Breaking backward compatibility between ctypes
and metaclasses in Python 3.13. · Issue #124520 · python/cpython (original) (raw)
Documentation
Background
I am one of the maintainers of comtypes. comtypes
is based on ctypes
and uses metaclasses to implement IUnknown.
It was reported to the comtypes
community that an error occurs when attempting to use conventional metaclasses with Python 3.13.
A similar error was encountered in pyglet, which also uses metaclasses to implement COM interfaces, when running on Python 3.13.
By referring to pyglet/pyglet#1196 and pyglet/pyglet#1199, I made several modifications to the code through trial and error, and now comtypes
works in both Python 3.13 and earlier versions without problems:
- https://github.com/enthought/comtypes/compare/a3a8733..04b766a
- It is necessary to pass arguments directly to the metaclass instead of using
__new__
in places where the metaclass is instantiated (i.e., where the class is dynamically defined). This also works in versions prior to Python 3.13. - After calling
type.__new__
, any remaining initialization would be handled in__init__
instead of in__new__
. Since this results in an error in versions prior to Python 3.13, a bridge usingsys.version_info
is necessary.
- It is necessary to pass arguments directly to the metaclass instead of using
I think these changes are likely related to #114314 and #117142 and were introduced by the PRs linked to those issues.
Since this change to ctypes
breaks compatibility, I think it should be mentioned in the What’s New In Python 3.13 and/or in the ctypes documentation.
There are likely other projects besides comtypes
and pyglet
that rely on the combination of ctypes
and metaclasses, and I want to prevent confusion for those maintainers when they try to support Python 3.13.
(Additionally, I would like to ask with the ctypes
maintainers to confirm whether the changes for the metaclasses in comtypes
(and pyglet
) are appropriate.)