Hacktoberfest 2026:メンテナが10月に向けて印を付けた、オープンで初心者向けの issue。 Hacktoberfest の issue を見る

Eliminate Workarounds for `POINTER(IUnknown)` by `Intersection` Generic Alias

オープン
#957 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 1 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
35/100
issue の種類
ドキュメント
明瞭さ
おおむね明確
活発さ
活発
技術スタック
python
領域
documentation

調査の方向性

Examine the current if TYPE_CHECKING: workaround in comtypes/_post_coinit/unknwn.py around lines 355-373 to understand the existing hack. Study how POINTER creates pointer types and how interface classes like IUnknown are defined with _cominterface_meta. Investigate adding __pointer_type__ to interface classes and using Intersection from typing-extensions to define ComPointer[T]. Check for type stub tests to validate changes. Done means the workaround is removed and type checkers correctly infer ComPointer[IUnknown] from CreateObject.

索引モデルが issue の本文から書いたものです。

説明

typing

Background and Challenge: The "Intersecting" Dual Nature of COM Pointers

In comtypes, a COM pointer is a complex object that simultaneously exhibits two distinct characteristics at runtime:

  1. C-Level Pointer Nature:
    It manages memory addresses and can be passed directly to C functions as a derivative of ctypes.c_void_p or _compointer_base.
  2. COM Interface Nature:
    It can directly invoke high-level methods defined by specific interfaces, such as IUnknown or IDispatch (e.g., AddRef, QueryInterface, GetClassInfo).

Inspecting the MRO (Method Resolution Order) of POINTER, IUnknown, and their underlying metaclasses at runtime reveals how these two characteristics are bound together via dynamic multiple inheritance.
Notably, a POINTER(IUnknown) instance is not a ctypes._Pointer type, whereas POINTER(POINTER(IUnknown)) is a ctypes._Pointer type:

>>> # Python 3.15
>>> from ctypes import POINTER, c_void_p, pointer
>>> import comtypes.client
>>> from comtypes import IUnknown, GUID
>>> from comtypes._post_coinit.unknwn import _compointer_base, _compointer_meta, _cominterface_meta
>>> # metaclass instance = type
>>> isinstance(IUnknown, _compointer_base)
False
>>> isinstance(IUnknown, _compointer_meta)
False
>>> isinstance(IUnknown, _cominterface_meta)
True
>>> isinstance(POINTER(IUnknown), _compointer_base)
False
>>> isinstance(POINTER(IUnknown), _compointer_meta)
True
>>> isinstance(POINTER(IUnknown), _cominterface_meta)
True
>>> # instance
>>> isinstance(IUnknown(), _compointer_base)
False
>>> isinstance(IUnknown(), _compointer_meta)
False
>>> isinstance(IUnknown(), _cominterface_meta)
False
>>> isinstance(IUnknown(), IUnknown)
True
>>> isinstance(POINTER(IUnknown)(), _compointer_base)
True
>>> isinstance(POINTER(IUnknown)(), _compointer_meta)
False
>>> isinstance(POINTER(IUnknown)(), _cominterface_meta)
False
>>> isinstance(POINTER(IUnknown)(), IUnknown)
True
>>> isinstance(POINTER(IUnknown)(), POINTER(IUnknown))
True
>>> isinstance(POINTER(IUnknown)(), _Pointer)
False
>>> isinstance(POINTER(POINTER(IUnknown))(), POINTER(IUnknown))
False
>>> isinstance(POINTER(POINTER(IUnknown))(), _Pointer)
True
>>> # mro
>>> _compointer_base.__mro__
(<class 'comtypes._post_coinit.unknwn._compointer_base'>, <class 'ctypes.c_void_p'>, <class '_ctypes._SimpleCData'>, <class '_ctypes._CData'>, <class 'object'>)
>>> _compointer_meta.__mro__
(<class 'comtypes._post_coinit.unknwn._compointer_meta'>, <class '_ctypes.PyCSimpleType'>, <class '_ctypes.CType_Type'>, <class 'comtypes._post_coinit.unknwn._cominterface_meta'>, <class 'type'>, <class 'object'>)
>>> _cominterface_meta.__mro__
(<class 'comtypes._post_coinit.unknwn._cominterface_meta'>, <class 'type'>, <class 'object'>)
>>> IUnknown.__mro__
(<class 'comtypes._post_coinit.unknwn.IUnknown'>, <class 'object'>)
>>> POINTER(IUnknown).__mro__
(<class 'comtypes._post_coinit.unknwn.POINTER(IUnknown)'>, <class 'comtypes._post_coinit.unknwn.IUnknown'>, <class 'comtypes._post_coinit.unknwn._compointer_base'>, <class 'ctypes.c_void_p'>, <class '_ctypes._SimpleCData'>, <class '_ctypes._CData'>, <class 'object'>)
>>> POINTER(POINTER(IUnknown)).__mro__
(<class 'ctypes.LP_POINTER(IUnknown)'>, <class '_ctypes._Pointer'>, <class '_ctypes._CData'>, <class 'object'>)
>>> type(_compointer_base)
<class 'comtypes._post_coinit.unknwn._compointer_meta'>
>>> type(_compointer_meta)
<class 'type'>
>>> type(_cominterface_meta)
<class 'type'>
>>> type(IUnknown)
<class 'comtypes._post_coinit.unknwn._cominterface_meta'>
>>> type(POINTER(IUnknown))
<class 'comtypes._post_coinit.unknwn._compointer_meta'>
>>> type(POINTER(POINTER(IUnknown)))
<class '_ctypes.PyCPointerType'>
>>> _CData = _SimpleCData.__mro__[:-1][-1]
>>> _CData.__mro__
(<class '_ctypes._CData'>, <class 'object'>)
>>> isinstance(IUnknown(), _CData)
False
>>> isinstance(POINTER(IUnknown)(), _CData)
True
>>> isinstance(POINTER(POINTER(IUnknown))(), _CData)
True

We can confirm that this holds true even for fully functional COM pointers at runtime:

>>> CLSID_CUIAutomation = GUID("{FF48DBA4-60EF-4201-AA87-54103EEF594E}")
>>> punk = CreateObject(CLSID_CUIAutomation, interface=IUnknown)
>>> punk
<POINTER(IUnknown) ptr=... at ...>
>>> isinstance(punk, c_void_p)
True
>>> isinstance(punk, _compointer_base)
True
>>> isinstance(punk, _compointer_meta)
False
>>> isinstance(punk, _cominterface_meta)
False
>>> isinstance(punk, IUnknown)
True
>>> isinstance(punk, POINTER(IUnknown))
True
>>> isinstance(punk, POINTER(POINTER(IUnknown)))
False
>>> ppunk = pointer(punk)
>>> ppunk
<ctypes.LP_POINTER(IUnknown) object at ...>
>>> isinstance(ppunk, _compointer_base)
False
>>> isinstance(ppunk, _compointer_meta)
False
>>> isinstance(ppunk, _cominterface_meta)
False
>>> isinstance(ppunk, IUnknown)
False
>>> isinstance(ppunk, POINTER(IUnknown))
False
>>> isinstance(ppunk, POINTER(POINTER(IUnknown)))
True

Expressing this "dynamic and intersecting nature" in current Python static typing is extremely difficult.

Limitations of Traditional Approaches (Union / Single Inheritance) and Current Workarounds

It is impossible to accurately represent this state using conventional type systems.

  • Limitations of Union (A | B):
    Since a Union means "either A or B", it cannot express the intersecting state of "having pointer capabilities (A) and interface methods (B) simultaneously".
    Attempting to call an interface method causes the type checker to emit false-positive errors because the pointer type itself does not own those methods.
  • Limitations of Single Inheritance Trees and Mixins:
    To statically define a base class possessing both traits, we need to statically define as many mixin classes as there are derived classes of IUnknown (hundreds to thousands of COM interfaces).
    This is entirely impractical and completely blocks dynamic generic expressions like "a pointer to an arbitrary interface T".

Due to these constraints, comtypes currently relies on workarounds using if TYPE_CHECKING: blocks:

https://github.com/enthought/comtypes/blob/824b7a1abcba520235d7d3c2995795f3a6bb63f0/comtypes/_post_coinit/unknwn.py#L355-L373

At runtime, it is simply an alias for object, but forcing it to inherit from c_void_p strictly during static type checking prevents a flood of false positives when calling POINTER(IUnknown).
However, this is merely an ad-hoc fix that decouples the actual runtime structure (MRO) from static analysis.

Evolution in Python 3.14+ (Leveraging __pointer_type__ and Generics)

By leveraging _CData.__pointer_type__ introduced in Python 3.14+, we now have the foundation to tie interfaces to their respective pointer types using generics.

Note: While the code snippet below follows PEP 695 syntax, the same can be achieved using traditional TypeVar.

# Type stub desired to be added to typeshed
class _HasDunderPointerType[T](Protocol):
    __pointer_type__: type[T]


# Existing overloads of `POINTER`...
@overload
def POINTER[T](cls: _HasDunderPointerType[T]) -> type[T]: ...
# Existing overloads of `POINTER`...

If every interface explicitly specifies its pointer type via __pointer_type__ and the POINTER factory overloads accept it, we can at least dynamically and generically communicate "what the pointer type of this interface is" to the type checker.
However, the fundamental problem of how to define the inner contents of T (the actual layout of the pointer) remains unsolved.

Complete Resolution via Intersection and the Need for Adoption

By combining the generic foundation above with Intersection—as discussed in https://github.com/python/typing/issues/213 and https://github.com/CarliJoy/intersection_examples — we can completely eliminate past contradictions and hacks, achieving a static type representation that perfectly matches the runtime behavior.

type ComPointer[T_IUnknown: IUnknown] = Intersection[_compointer_base, T_IUnknown]

This single line declares the coexistence of "the underlying C pointer capability (_compointer_base)" and "any high-level COM interface (T_IUnknown)".
This allows type-safe propagation of return values from dynamic factory methods like CreateObject or QueryInterface:

# _post_coinit/unknwn.py
class IUnknown(object, metaclass=_cominterface_meta):  # Workaround is NO more
    if TYPE_CHECKING:
        # Need to add new type-check only attribute
        __pointer_type__: ClassVar[type[ComPointer[Self]]]

punk = CreateObject("AnyProgId", interface=IUnknown)
pc = punk.QueryInterface(IProvideClassInfo)
ti = pc.GetClassInfo()
assert_type(punk, ComPointer[IUnknown])
assert_type(pc, ComPointer[IProvideClassInfo])
assert_type(ti, ComPointer[ITypeInfo])
ppunk = pointer(punk)
assert_type(ppunk, _Pointer[ComPointer[IUnknown]])

This can be verified using ty, which features a pioneering internal implementation of Intersection, confirming that type inference works as intended and statically validates types that precisely match the complex runtime MRO:
https://play.ty.dev/c57737cd-e7e3-4cfc-8e11-4d3e5764750e

Future Outlook

If an experimental version of Intersection is eventually implemented in typing-extensions, we may face some limitations regarding Python versions or supported type checkers, but I would likely adopt code like the above to represent COM pointer types.
In any case, this change is strictly for static typing and is designed to have no impact on runtime behavior.
While complex metaprogramming that relies on runtime annotation inspection might be affected, I am not aware of any projects attempting this with comtypes.
When a clean way to accurately express types becomes available, prioritizing its adoption is my preferred direction.

主要言語
Python
スター
347
フォーク
107
平均マージ
19時間 36分
マージ済み PR(30日)
17

環境構築

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

enthought/comtypes のほかの issue

enthought/comtypes の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。