From ac30b6ed1dfd4d891c31d6c35ba138856e2fdca5 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 1/9] fix: Update Python requirement to 3.10 in `pyproject.toml`. --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index e806166c..d7d01201 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -2,7 +2,7 @@ name = "comtypes" description = "Pure Python COM package" readme = "README.md" -requires-python = ">=3.9" +requires-python = ">=3.10" license = "MIT" license-files = ["LICENSE.txt"] authors = [ From 2c6aa3dbc505f0a2bb17b724a0baaf8aaec5bb58 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 2/9] style: Apply PEP 604 union syntax across the package. Convert `Optional[T]` and `Union[T, S]` annotations to `T | None` and `T | S` in a package-wide pass, following PEP 604 and pyupgrade's UP007 rule. This makes union type hints consistent and easier to read. Some cases cannot be converted in this bulk pass and will be handled in a follow-up change. Sort imports and normalize formatting alongside the annotation changes. --- comtypes/_automation.py | 6 +- comtypes/_comobject.py | 6 +- comtypes/_memberspec.py | 26 +++---- comtypes/_post_coinit/activeobj.py | 9 +-- comtypes/_post_coinit/misc.py | 55 +++++++------- comtypes/_post_coinit/unknwn.py | 7 +- comtypes/_vtbl.py | 14 ++-- comtypes/client/_activeobj.py | 14 ++-- comtypes/client/_create.py | 60 +++++++-------- comtypes/client/_events.py | 12 +-- comtypes/client/_generate.py | 15 ++-- comtypes/client/_managing.py | 6 +- comtypes/client/dynamic.py | 4 +- comtypes/errorinfo.py | 21 +++--- comtypes/hints.pyi | 73 +++++++------------ comtypes/malloc.py | 6 +- comtypes/persist.py | 4 +- comtypes/recordinfo.py | 4 +- comtypes/server/__init__.py | 2 +- comtypes/server/connectionpoints.py | 2 +- comtypes/server/inprocserver.py | 4 +- comtypes/server/localserver.py | 6 +- comtypes/server/register.py | 19 +++-- comtypes/test/gdi_helper.py | 5 +- comtypes/test/test_logutil.py | 6 +- comtypes/test/test_record_safearray_bstr.py | 11 +-- comtypes/test/test_record_safearray_value.py | 7 +- comtypes/test/test_showevents.py | 3 +- comtypes/test/test_storage.py | 3 +- comtypes/test/test_stream.py | 3 +- comtypes/tools/codegenerator/codegenerator.py | 26 +++---- comtypes/tools/codegenerator/heads.py | 3 +- comtypes/tools/codegenerator/modulenamer.py | 4 +- comtypes/tools/codegenerator/namespaces.py | 17 ++--- comtypes/tools/codegenerator/typeannotator.py | 26 +++---- comtypes/tools/tlbparser.py | 26 +++---- comtypes/tools/typedesc.py | 38 +++++----- comtypes/tools/typedesc_base.py | 16 ++-- comtypes/typeinfo.py | 43 +++++------ 39 files changed, 281 insertions(+), 331 deletions(-) diff --git a/comtypes/_automation.py b/comtypes/_automation.py index 421fe4ee..72b11da6 100644 --- a/comtypes/_automation.py +++ b/comtypes/_automation.py @@ -36,7 +36,7 @@ ) from ctypes import Array as _CArrayType from ctypes.wintypes import DWORD, LONG, UINT, VARIANT_BOOL, WORD -from typing import TYPE_CHECKING, Any, ClassVar, Optional +from typing import TYPE_CHECKING, Any, ClassVar import comtypes import comtypes.patcher @@ -863,8 +863,8 @@ class tagEXCEPINFO(Structure): bstrDescription: str bstrHelpFile: str dwHelpContext: int - pvReserved: Optional[int] - pfnDeferredFillIn: Optional[int] + pvReserved: int | None + pfnDeferredFillIn: int | None scode: int def __repr__(self): diff --git a/comtypes/_comobject.py b/comtypes/_comobject.py index 16b4410a..46e16f04 100644 --- a/comtypes/_comobject.py +++ b/comtypes/_comobject.py @@ -14,7 +14,7 @@ pointer, ) from ctypes.wintypes import INT, LONG, LPVOID, UINT, ULONG, WORD -from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from typing import Union as _UnionT import comtypes @@ -135,7 +135,7 @@ def _InterlockedDecrement(ob: c_long) -> int: class LocalServer: - _queue: Optional[queue.Queue] = None + _queue: queue.Queue | None = None def run(self, classobjects: Sequence["hints.localserver.ClassFactory"]) -> None: hr = _CoInitialize(None) @@ -270,7 +270,7 @@ def _get_method_finder_(self, itf: type[IUnknown]) -> _MethodFinder: ################################################################ # LocalServer / InprocServer stuff - __server__: _UnionT[None, InprocServer, LocalServer] = None + __server__: None | InprocServer | LocalServer = None @staticmethod def __run_inprocserver__() -> None: diff --git a/comtypes/_memberspec.py b/comtypes/_memberspec.py index 7d5d8f45..3b9140e5 100644 --- a/comtypes/_memberspec.py +++ b/comtypes/_memberspec.py @@ -51,9 +51,9 @@ def _encode_idl(names: Sequence[str]) -> int: def _unpack_argspec( idl: list[str], typ: type["_CDataType"], - name: Optional[str] = None, + name: str | None = None, defval: Any = _NOTHING, -) -> tuple[list[str], type["_CDataType"], Optional[str], Any]: +) -> tuple[list[str], type["_CDataType"], str | None, Any]: return idl, typ, name, defval @@ -102,12 +102,12 @@ def _resolve_argspec( class _ComMemberSpec(NamedTuple): """Specifier for a slot of COM method or property.""" - restype: Optional[type["_CDataType"]] + restype: type["_CDataType"] | None name: str argtypes: tuple[type["_CDataType"], ...] - paramflags: Optional[tuple["hints.ParamFlagType", ...]] + paramflags: tuple["hints.ParamFlagType", ...] | None idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"] - doc: Optional[str] + doc: str | None def is_prop(self) -> bool: return _is_spec_prop(self) @@ -119,7 +119,7 @@ class _DispMemberSpec(NamedTuple): what: Literal["DISPMETHOD", "DISPPROPERTY"] name: str idlflags: "_DispIdlFlags" - restype: Optional[type["_CDataType"]] + restype: type["_CDataType"] | None argspec: tuple["hints.ArgSpecElmType", ...] @property @@ -166,7 +166,7 @@ class dispid(int): def STDMETHOD( - restype: Optional[type["_CDataType"]], + restype: type["_CDataType"] | None, name: str, argtypes: Sequence[type["_CDataType"]] = (), ) -> _ComMemberSpec: @@ -190,8 +190,8 @@ def STDMETHOD( def DISPMETHOD( - idlflags: Sequence[_UnionT[int, str]], - restype: Optional[type["_CDataType"]], + idlflags: Sequence[int | str], + restype: type["_CDataType"] | None, name: str, *argspec: "hints.ArgSpecElmType", ) -> _DispMemberSpec: @@ -226,7 +226,7 @@ def DISPMETHOD( def DISPPROPERTY( - idlflags: Sequence[_UnionT[int, str]], + idlflags: Sequence[int | str], proptype: type["_CDataType"], name: str, ) -> _DispMemberSpec: @@ -259,8 +259,8 @@ def DISPPROPERTY( def COMMETHOD( - idlflags: Sequence[_UnionT[int, str]], - restype: Optional[type["_CDataType"]], + idlflags: Sequence[int | str], + restype: type["_CDataType"] | None, methodname: str, *argspec: "hints.ArgSpecElmType", ) -> _ComMemberSpec: @@ -610,7 +610,7 @@ class DispMemberGenerator: def __init__(self, cls_name: str) -> None: self._props = DispPropertyGenerator(cls_name) # sequence of (name: str, func_or_prop: Callable | property, is_prop: bool) - self._items: list[tuple[str, _UnionT[Callable[..., Any], property], bool]] = [] + self._items: list[tuple[str, Callable[..., Any] | property, bool]] = [] def add(self, m: _DispMemberSpec) -> None: if m.what == "DISPPROPERTY": # DISPPROPERTY diff --git a/comtypes/_post_coinit/activeobj.py b/comtypes/_post_coinit/activeobj.py index 46a1474e..7df16bde 100644 --- a/comtypes/_post_coinit/activeobj.py +++ b/comtypes/_post_coinit/activeobj.py @@ -1,7 +1,6 @@ from ctypes import HRESULT, POINTER, OleDLL, byref, c_ulong, c_void_p from ctypes.wintypes import DWORD, LPVOID -from typing import TYPE_CHECKING, Optional, TypeVar, overload -from typing import Union as _UnionT +from typing import TYPE_CHECKING, TypeVar, overload from comtypes import GUID from comtypes._post_coinit.unknwn import IUnknown @@ -18,7 +17,7 @@ def RegisterActiveObject( - punk: "_UnionT[IUnknown, hints.LP_LP_Vtbl]", clsid: GUID, flags: int + punk: "IUnknown | hints.LP_LP_Vtbl", clsid: GUID, flags: int ) -> int: """Registers a pointer as the active object for its class and returns the handle.""" handle = c_ulong() @@ -35,9 +34,7 @@ def RevokeActiveObject(handle: int) -> None: def GetActiveObject(clsid: GUID, interface: None = None) -> IUnknown: ... @overload def GetActiveObject(clsid: GUID, interface: type[_T_IUnknown]) -> _T_IUnknown: ... -def GetActiveObject( - clsid: GUID, interface: Optional[type[IUnknown]] = None -) -> IUnknown: +def GetActiveObject(clsid: GUID, interface: type[IUnknown] | None = None) -> IUnknown: """Retrieves a pointer to a running object""" p = POINTER(IUnknown)() _GetActiveObject(byref(clsid), None, byref(p)) diff --git a/comtypes/_post_coinit/misc.py b/comtypes/_post_coinit/misc.py index 7910389b..251e2790 100644 --- a/comtypes/_post_coinit/misc.py +++ b/comtypes/_post_coinit/misc.py @@ -13,8 +13,7 @@ pointer, ) from ctypes.wintypes import DWORD, LPCWSTR, LPVOID -from typing import TYPE_CHECKING, Any, Optional, TypeVar, overload -from typing import Union as _UnionT +from typing import TYPE_CHECKING, Any, TypeVar, overload from comtypes import CLSCTX_LOCAL_SERVER, CLSCTX_REMOTE_SERVER, CLSCTX_SERVER, GUID from comtypes._memberspec import COMMETHOD @@ -96,7 +95,7 @@ def QueryService( def CoGetObject(displayname: str, interface: None) -> IUnknown: ... @overload def CoGetObject(displayname: str, interface: type[_T_IUnknown]) -> _T_IUnknown: ... -def CoGetObject(displayname: str, interface: Optional[type[IUnknown]]) -> IUnknown: +def CoGetObject(displayname: str, interface: type[IUnknown] | None) -> IUnknown: """Convert a displayname to a moniker, then bind and return the object identified by the moniker.""" if interface is None: @@ -114,21 +113,21 @@ def CoGetObject(displayname: str, interface: Optional[type[IUnknown]]) -> IUnkno def CoCreateInstance( clsid: GUID, interface: None = None, - clsctx: Optional[int] = None, - punkouter: Optional[_pUnkOuter] = None, + clsctx: int | None = None, + punkouter: _pUnkOuter | None = None, ) -> IUnknown: ... @overload def CoCreateInstance( clsid: GUID, interface: type[_T_IUnknown], - clsctx: Optional[int] = None, - punkouter: Optional[_pUnkOuter] = None, + clsctx: int | None = None, + punkouter: _pUnkOuter | None = None, ) -> _T_IUnknown: ... def CoCreateInstance( clsid: GUID, - interface: Optional[type[IUnknown]] = None, - clsctx: Optional[int] = None, - punkouter: Optional[_pUnkOuter] = None, + interface: type[IUnknown] | None = None, + clsctx: int | None = None, + punkouter: _pUnkOuter | None = None, ) -> IUnknown: """The basic windows api to create a COM class object and return a pointer to an interface. @@ -146,22 +145,22 @@ def CoCreateInstance( @overload def CoGetClassObject( clsid: GUID, - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, interface: None = None, ) -> "hints.IClassFactory": ... @overload def CoGetClassObject( clsid: GUID, - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, interface: type[_T_IUnknown] = IUnknown, ) -> _T_IUnknown: ... def CoGetClassObject( clsid: GUID, - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, - interface: Optional[type[IUnknown]] = None, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, + interface: type[IUnknown] | None = None, ) -> IUnknown: if clsctx is None: clsctx = CLSCTX_SERVER @@ -221,7 +220,7 @@ class _COSERVERINFO(Structure): ] if TYPE_CHECKING: dwReserved1: int - pwszName: Optional[str] + pwszName: str | None pAuthInfo: _COAUTHINFO dwReserved2: int @@ -336,24 +335,24 @@ class _SOLE_AUTHENTICATION_LIST(Structure): def CoCreateInstanceEx( clsid: GUID, interface: None = None, - clsctx: Optional[int] = None, - machine: Optional[str] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + clsctx: int | None = None, + machine: str | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> IUnknown: ... @overload def CoCreateInstanceEx( clsid: GUID, interface: type[_T_IUnknown], - clsctx: Optional[int] = None, - machine: Optional[str] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + clsctx: int | None = None, + machine: str | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> _T_IUnknown: ... def CoCreateInstanceEx( clsid: GUID, - interface: Optional[type[IUnknown]] = None, - clsctx: Optional[int] = None, - machine: Optional[str] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + interface: type[IUnknown] | None = None, + clsctx: int | None = None, + machine: str | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> IUnknown: """The basic windows api to create a COM class object and return a pointer to an interface, possibly on another machine. diff --git a/comtypes/_post_coinit/unknwn.py b/comtypes/_post_coinit/unknwn.py index 00f6caf0..30a08b30 100644 --- a/comtypes/_post_coinit/unknwn.py +++ b/comtypes/_post_coinit/unknwn.py @@ -3,7 +3,7 @@ import logging import sys from ctypes import HRESULT, POINTER, byref, c_ulong, c_void_p -from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar import comtypes from comtypes import GUID, _CoUninitialize @@ -13,7 +13,6 @@ if TYPE_CHECKING: from typing import Literal - from typing import Union as _UnionT from comtypes import hints # type: ignore from comtypes._memberspec import _ComMemberSpec, _DispMemberSpec @@ -315,7 +314,7 @@ def __repr__(self) -> str: # It also allows to pass a COMObject instance to an api expecting a COM interface. @classmethod def from_param( - cls, value: "_UnionT[None, Literal[0], hints.Self, IUnknown, hints.COMObject]" + cls, value: "None | Literal[0] | hints.Self | IUnknown | hints.COMObject" ) -> Any: """Convert 'value' into a COM pointer to the interface. @@ -397,7 +396,7 @@ class IUnknown(_IUnknown_Base, metaclass=_cominterface_meta): # And if `isinstance(p, POINTER(T))` is `True`, then `isinstance(p, T)` is also `True`. # So returning `T` is not a lie, and good way to know what members the class has. def QueryInterface( - self, interface: type[_T_IUnknown], iid: Optional[GUID] = None + self, interface: type[_T_IUnknown], iid: GUID | None = None ) -> _T_IUnknown: """QueryInterface(interface) -> instance""" p = POINTER(interface)() diff --git a/comtypes/_vtbl.py b/comtypes/_vtbl.py index 904bfa6d..06e8bb31 100644 --- a/comtypes/_vtbl.py +++ b/comtypes/_vtbl.py @@ -2,7 +2,7 @@ from _ctypes import COMError from collections.abc import Callable, Iterator, Sequence from ctypes import WINFUNCTYPE, Structure, c_void_p -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from typing import Union as _UnionT import comtypes @@ -32,7 +32,7 @@ class E_NotImplemented(Exception): """COM method is not implemented""" -def HRESULT_FROM_WIN32(errcode: Optional[int]) -> int: +def HRESULT_FROM_WIN32(errcode: int | None) -> int: "Convert a Windows error code into a HRESULT value." if errcode is None: return 0x80000000 @@ -71,7 +71,7 @@ def _not_implemented(*args): def catch_errors( obj: "hints.COMObject", mth: Callable[..., Any], - paramflags: Optional[tuple["hints.ParamFlagType", ...]], + paramflags: tuple["hints.ParamFlagType", ...] | None, interface: type[IUnknown], mthname: str, ) -> Callable[..., Any]: @@ -120,7 +120,7 @@ def call_with_this(*args, **kw): def hack( inst: "hints.COMObject", mth: Callable[..., Any], - paramflags: Optional[tuple["hints.ParamFlagType", ...]], + paramflags: tuple["hints.ParamFlagType", ...] | None, interface: type[IUnknown], mthname: str, ) -> Callable[..., Any]: @@ -228,7 +228,7 @@ def get_impl( self, interface: type[IUnknown], mthname: str, - paramflags: Optional[tuple["hints.ParamFlagType", ...]], + paramflags: tuple["hints.ParamFlagType", ...] | None, idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"], ) -> Callable[..., Any]: mth = self.find_impl(interface, mthname, paramflags, idlflags) @@ -250,9 +250,9 @@ def find_impl( self, interface: type[IUnknown], mthname: str, - paramflags: Optional[tuple["hints.ParamFlagType", ...]], + paramflags: tuple["hints.ParamFlagType", ...] | None, idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"], - ) -> Optional[Callable[..., Any]]: + ) -> Callable[..., Any] | None: fq_name = f"{interface.__name__}_{mthname}" if interface._case_insensitive_: # simple name, like 'QueryInterface' diff --git a/comtypes/client/_activeobj.py b/comtypes/client/_activeobj.py index 7130f0e5..bec55844 100644 --- a/comtypes/client/_activeobj.py +++ b/comtypes/client/_activeobj.py @@ -1,4 +1,4 @@ -from typing import Any, Literal, Optional, TypeVar, overload +from typing import Any, Literal, TypeVar, overload from typing import Union as _UnionT import comtypes @@ -15,13 +15,13 @@ # @overload def GetActiveObject( - progid: _UnionT[str, type[CoClass], GUID], + progid: str | type[CoClass] | GUID, interface: None = None, dynamic: Literal[False] = False, ) -> Any: ... @overload def GetActiveObject( - progid: _UnionT[str, type[CoClass], GUID], + progid: str | type[CoClass] | GUID, interface: None = None, dynamic: Literal[True] = True, ) -> _UnionT[ @@ -29,13 +29,13 @@ def GetActiveObject( ]: ... @overload def GetActiveObject( - progid: _UnionT[str, type[CoClass], GUID], + progid: str | type[CoClass] | GUID, interface: type[_T_IUnknown] = IUnknown, dynamic: Literal[False] = False, ) -> _T_IUnknown: ... def GetActiveObject( - progid: _UnionT[str, type[CoClass], GUID], - interface: Optional[type[IUnknown]] = None, + progid: str | type[CoClass] | GUID, + interface: type[IUnknown] | None = None, dynamic: bool = False, ) -> Any: """Return a pointer to a running COM object that has been @@ -61,7 +61,7 @@ def GetActiveObject( def RegisterActiveObject( - punk: IUnknown, progid: _UnionT[str, type[CoClass], GUID], weak: bool = True + punk: IUnknown, progid: str | type[CoClass] | GUID, weak: bool = True ) -> int: clsid = GUID.from_progid(progid) flags = comtypes.ACTIVEOBJECT_WEAK if weak else comtypes.ACTIVEOBJECT_STRONG diff --git a/comtypes/client/_create.py b/comtypes/client/_create.py index 39ff2406..dd5300cf 100644 --- a/comtypes/client/_create.py +++ b/comtypes/client/_create.py @@ -1,5 +1,5 @@ import logging -from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, overload +from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload from typing import Union as _UnionT import comtypes @@ -23,23 +23,23 @@ # @overload def GetClassObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, interface: None = None, ) -> "hints.IClassFactory": ... @overload def GetClassObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, interface: type[_T_IUnknown] = IUnknown, ) -> _T_IUnknown: ... def GetClassObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, - interface: Optional[type[IUnknown]] = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, + interface: type[IUnknown] | None = None, ) -> IUnknown: """Create and return the class factory for a COM object. @@ -52,43 +52,43 @@ def GetClassObject( @overload -def CreateObject(progid: _UnionT[str, type[CoClass], GUID]) -> Any: ... +def CreateObject(progid: str | type[CoClass] | GUID) -> Any: ... @overload def CreateObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - machine: Optional[str] = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + machine: str | None = None, interface: None = None, dynamic: Literal[False] = False, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> Any: ... @overload def CreateObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - machine: Optional[str] = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + machine: str | None = None, interface: None = None, dynamic: Literal[True] = True, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> _UnionT[ "comtypes.client.lazybind.Dispatch", "comtypes.client.dynamic._Dispatch" ]: ... @overload def CreateObject( - progid: _UnionT[str, type[CoClass], GUID], - clsctx: Optional[int] = None, - machine: Optional[str] = None, + progid: str | type[CoClass] | GUID, + clsctx: int | None = None, + machine: str | None = None, interface: type[_T_IUnknown] = IUnknown, dynamic: Literal[False] = False, - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, ) -> _T_IUnknown: ... def CreateObject( - progid: _UnionT[str, type[CoClass], GUID], # which object to create - clsctx: Optional[int] = None, # how to create the object - machine: Optional[str] = None, # where to create the object - interface: Optional[type[IUnknown]] = None, # the interface we want + progid: str | type[CoClass] | GUID, # which object to create + clsctx: int | None = None, # how to create the object + machine: str | None = None, # where to create the object + interface: type[IUnknown] | None = None, # the interface we want dynamic: bool = False, # use dynamic dispatch - pServerInfo: "_UnionT[None, _CArgObject, COSERVERINFO]" = None, # server info struct for remoting + pServerInfo: "None | _CArgObject | COSERVERINFO" = None, # server info struct for remoting ) -> Any: """Create a COM object from 'progid', and try to QueryInterface() it to the most useful interface, generating typelib support on @@ -166,7 +166,7 @@ def CoGetObject( ) -> _T_IUnknown: ... def CoGetObject( displayname: str, - interface: Optional[type[IUnknown]] = None, + interface: type[IUnknown] | None = None, dynamic: bool = False, ) -> Any: """Create an object by calling CoGetObject(displayname). diff --git a/comtypes/client/_events.py b/comtypes/client/_events.py index 603c5531..f543f18b 100644 --- a/comtypes/client/_events.py +++ b/comtypes/client/_events.py @@ -14,7 +14,7 @@ LPVOID, ULONG, ) -from typing import Any, Optional +from typing import Any from typing import Union as _UnionT import comtypes @@ -66,9 +66,9 @@ class SECURITY_ATTRIBUTES(Structure): class _AdviseConnection: - cp: Optional[IConnectionPoint] - cookie: Optional[int] - receiver: Optional[_ReceiverType] + cp: IConnectionPoint | None + cookie: int | None + receiver: _ReceiverType | None def __init__( self, source: IUnknown, interface: type[IUnknown], receiver: _ReceiverType @@ -280,7 +280,7 @@ def _get_method_finder_(self, itf: type[IUnknown]) -> _MethodFinder: def GetEvents( - source: IUnknown, sink: Any, interface: Optional[type[IUnknown]] = None + source: IUnknown, sink: Any, interface: type[IUnknown] | None = None ) -> _AdviseConnection: """Receive COM events from 'source'. Events will call methods on the 'sink' object. 'interface' is the source interface to use. @@ -314,7 +314,7 @@ def handler(self, this, *args, **kw): def ShowEvents( - source: IUnknown, interface: Optional[type[IUnknown]] = None + source: IUnknown, interface: type[IUnknown] | None = None ) -> _AdviseConnection: """Receive COM events from 'source'. A special event sink will be used that first prints the names of events that are found in the diff --git a/comtypes/client/_generate.py b/comtypes/client/_generate.py index aeed69da..caa427a5 100644 --- a/comtypes/client/_generate.py +++ b/comtypes/client/_generate.py @@ -7,8 +7,7 @@ import types import winreg from collections.abc import Mapping -from typing import Any, Optional -from typing import Union as _UnionT +from typing import Any import comtypes.client from comtypes import GUID, typeinfo @@ -55,7 +54,7 @@ def _resolve_filename(tlib_string: str, dirpath: str) -> tuple[str, bool]: return tlib_string, False -def GetModule(tlib: _UnionT[Any, typeinfo.ITypeLib]) -> types.ModuleType: +def GetModule(tlib: Any | typeinfo.ITypeLib) -> types.ModuleType: """Create a module wrapping a COM typelibrary on demand. 'tlib' must be ... @@ -102,7 +101,7 @@ def GetModule(tlib: _UnionT[Any, typeinfo.ITypeLib]) -> types.ModuleType: # if a relative pathname is used, we try to interpret it relative to # the directory of the calling module (if not from command line) frame = sys._getframe(1) - _file_: Optional[str] = frame.f_globals.get("__file__", None) + _file_: str | None = frame.f_globals.get("__file__", None) pathname, is_abs = _resolve_filename( tlib_string, _file_ and os.path.dirname(_file_), # type: ignore @@ -159,8 +158,8 @@ def _load_tlib(obj: Any) -> typeinfo.ITypeLib: raise TypeError(f"'{obj!r}' is not supported type for loading typelib") -def _get_existing_module(tlib: typeinfo.ITypeLib) -> Optional[types.ModuleType]: - def _get_friendly(name: str) -> Optional[types.ModuleType]: +def _get_existing_module(tlib: typeinfo.ITypeLib) -> types.ModuleType | None: + def _get_friendly(name: str) -> types.ModuleType | None: try: mod = _my_import(name) except Exception as details: @@ -168,7 +167,7 @@ def _get_friendly(name: str) -> Optional[types.ModuleType]: else: return mod - def _get_wrapper(name: str) -> Optional[types.ModuleType]: + def _get_wrapper(name: str) -> types.ModuleType | None: if name in sys.modules: return sys.modules[name] try: @@ -213,7 +212,7 @@ def _create_module(modulename: str, code: str) -> types.ModuleType: class ModuleGenerator: - def __init__(self, tlib: typeinfo.ITypeLib, pathname: Optional[str]) -> None: + def __init__(self, tlib: typeinfo.ITypeLib, pathname: str | None) -> None: self.wrapper_name = codegenerator.name_wrapper_module(tlib) self.friendly_name = codegenerator.name_friendly_module(tlib) if pathname is None: diff --git a/comtypes/client/_managing.py b/comtypes/client/_managing.py index 24aea77d..a3d52bce 100644 --- a/comtypes/client/_managing.py +++ b/comtypes/client/_managing.py @@ -1,6 +1,6 @@ import logging from _ctypes import COMError -from typing import Any, Optional +from typing import Any import comtypes import comtypes.client.dynamic @@ -105,9 +105,7 @@ def GetBestInterface(punk: Any) -> Any: return result -def _manage( - obj: Any, clsid: Optional[GUID], interface: Optional[type[IUnknown]] -) -> Any: +def _manage(obj: Any, clsid: GUID | None, interface: type[IUnknown] | None) -> Any: obj.__dict__["__clsid"] = str(clsid) if interface is None: obj = GetBestInterface(obj) diff --git a/comtypes/client/dynamic.py b/comtypes/client/dynamic.py index 58cf4fe3..c038629a 100644 --- a/comtypes/client/dynamic.py +++ b/comtypes/client/dynamic.py @@ -1,5 +1,5 @@ import ctypes -from typing import Any, Optional, TypeVar +from typing import Any, TypeVar from comtypes import GUID, COMError, IUnknown, _is_object, automation from comtypes import hresult as hres @@ -90,7 +90,7 @@ def __getitem__(self, index: Any) -> Any: return item def QueryInterface( - self, interface: type[_T_IUnknown], iid: Optional[GUID] = None + self, interface: type[_T_IUnknown], iid: GUID | None = None ) -> _T_IUnknown: """QueryInterface is forwarded to the real com object.""" return self._comobj.QueryInterface(interface, iid) diff --git a/comtypes/errorinfo.py b/comtypes/errorinfo.py index 59f4d471..7700d82b 100644 --- a/comtypes/errorinfo.py +++ b/comtypes/errorinfo.py @@ -1,8 +1,7 @@ import sys from ctypes import POINTER, OleDLL, byref, c_wchar_p from ctypes.wintypes import DWORD, ULONG -from typing import TYPE_CHECKING, Optional -from typing import Union as _UnionT +from typing import TYPE_CHECKING from comtypes import BSTR, COMMETHOD, GUID, HRESULT, IUnknown from comtypes.hresult import DISP_E_EXCEPTION, S_OK @@ -90,7 +89,7 @@ def CreateErrorInfo() -> ICreateErrorInfo: return cei # type: ignore -def GetErrorInfo() -> Optional[IErrorInfo]: +def GetErrorInfo() -> IErrorInfo | None: """Get the error information for the current thread.""" errinfo = POINTER(IErrorInfo)() if S_OK == _GetErrorInfo(0, byref(errinfo)): @@ -98,7 +97,7 @@ def GetErrorInfo() -> Optional[IErrorInfo]: return None -def SetErrorInfo(errinfo: _UnionT[IErrorInfo, ICreateErrorInfo]) -> "hints.Hresult": +def SetErrorInfo(errinfo: IErrorInfo | ICreateErrorInfo) -> "hints.Hresult": """Set error information for the current thread.""" # ICreateErrorInfo can QueryInterface with IErrorInfo, so both types are # accepted, thanks to the magic of from_param. @@ -108,9 +107,9 @@ def SetErrorInfo(errinfo: _UnionT[IErrorInfo, ICreateErrorInfo]) -> "hints.Hresu def ReportError( text: str, iid: GUID, - clsid: _UnionT[None, str, GUID] = None, - helpfile: Optional[str] = None, - helpcontext: Optional[int] = 0, + clsid: None | str | GUID = None, + helpfile: str | None = None, + helpcontext: int | None = 0, hresult: int = DISP_E_EXCEPTION, ) -> int: """Report a COM error. Returns the passed in hresult value.""" @@ -138,10 +137,10 @@ def ReportError( def ReportException( hresult: int, iid: GUID, - clsid: _UnionT[None, str, GUID] = None, - helpfile: Optional[str] = None, - helpcontext: Optional[int] = None, - stacklevel: Optional[int] = None, + clsid: None | str | GUID = None, + helpfile: str | None = None, + helpcontext: int | None = None, + stacklevel: int | None = None, ) -> int: """Report a COM exception. Returns the passed in hresult value.""" typ, value, tb = sys.exc_info() diff --git a/comtypes/hints.pyi b/comtypes/hints.pyi index 5c197c34..0bfa49d1 100644 --- a/comtypes/hints.pyi +++ b/comtypes/hints.pyi @@ -7,8 +7,7 @@ from collections.abc import Callable, Iterator, Sequence from ctypes import _CData, _CDataType from typing import Annotated as Annotated from typing import Any as Any -from typing import ClassVar, Generic, NoReturn, Optional, Protocol, overload -from typing import Union as _UnionT +from typing import ClassVar, Generic, NoReturn, Protocol, overload if sys.version_info >= (3, 10): from typing import Concatenate, ParamSpec, TypeAlias @@ -102,7 +101,7 @@ _R_PutRef = TypeVar("_R_PutRef", infer_variance=True) def put_or_putref( put: Callable[_P_Put, _R_Put], putref: Callable[_P_PutRef, _R_PutRef] -) -> _UnionT[Callable[_P_Put, _R_Put], Callable[_P_PutRef, _R_PutRef]]: ... +) -> Callable[_P_Put, _R_Put] | Callable[_P_PutRef, _R_PutRef]: ... _T_Inst = TypeVar("_T_Inst", infer_variance=True) _T_SetVal = TypeVar("_T_SetVal", infer_variance=True) @@ -117,9 +116,7 @@ class _GetSetNormalProperty(Generic[_T_Inst, _R_Get, _T_SetVal]): @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload - def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / - ) -> _R_Get: ... + def __get__(self, instance: _T_Inst, owner: type[_T_Inst] | None, /) -> _R_Get: ... def __set__(self, instance: _T_Inst, value: _T_SetVal, /) -> None: ... class _GetOnlyNormalProperty(Generic[_T_Inst, _R_Get]): @@ -128,9 +125,7 @@ class _GetOnlyNormalProperty(Generic[_T_Inst, _R_Get]): @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload - def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / - ) -> _R_Get: ... + def __get__(self, instance: _T_Inst, owner: type[_T_Inst] | None, /) -> _R_Get: ... def __set__(self, instance: _T_Inst, value: Any, /) -> NoReturn: ... class _SetOnlyNormalProperty(Generic[_T_Inst, _T_SetVal]): @@ -141,7 +136,7 @@ class _SetOnlyNormalProperty(Generic[_T_Inst, _T_SetVal]): def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / + self, instance: _T_Inst, owner: type[_T_Inst] | None, / ) -> NoReturn: ... def __set__(self, instance: _T_Inst, value: _T_SetVal, /) -> None: ... @@ -162,7 +157,7 @@ class _GetSetBoundNamedProperty(Generic[_T_Inst, _P_Get, _R_Get, _P_Set]): name: str fget: Callable[Concatenate[_T_Inst, _P_Get], _R_Get] fset: Callable[Concatenate[_T_Inst, _P_Set], Any] - __doc__: Optional[str] + __doc__: str | None def __getitem__(self, index: Any, /) -> _R_Get: ... def __call__(self, *args: _P_Get.args, **kwargs: _P_Get.kwargs) -> _R_Get: ... def __setitem__(self, index: Any, value: Any, /) -> None: ... @@ -172,20 +167,20 @@ class _GetSetNamedProperty(Generic[_T_Inst, _P_Get, _R_Get, _P_Set]): name: str fget: Callable[Concatenate[_T_Inst, _P_Get], _R_Get] fset: Callable[Concatenate[_T_Inst, _P_Set], Any] - __doc__: Optional[str] + __doc__: str | None @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / + self, instance: _T_Inst, owner: type[_T_Inst] | None, / ) -> _GetSetBoundNamedProperty[_T_Inst, _P_Get, _R_Get, _P_Set]: ... def __set__(self, instance: _T_Inst, value: Any, /) -> NoReturn: ... class _GetOnlyBoundNamedProperty(Generic[_T_Inst, _P_Get, _R_Get]): name: str fget: Callable[Concatenate[_T_Inst, _P_Get], _R_Get] - __doc__: Optional[str] + __doc__: str | None def __getitem__(self, index: Any, /) -> _R_Get: ... def __call__(self, *args: _P_Get.args, **kwargs: _P_Get.kwargs) -> _R_Get: ... def __setitem__(self, index: Any, value: Any, /) -> NoReturn: ... @@ -194,20 +189,20 @@ class _GetOnlyBoundNamedProperty(Generic[_T_Inst, _P_Get, _R_Get]): class _GetOnlyNamedProperty(Generic[_T_Inst, _P_Get, _R_Get]): name: str fget: Callable[Concatenate[_T_Inst, _P_Get], _R_Get] - __doc__: Optional[str] + __doc__: str | None @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / + self, instance: _T_Inst, owner: type[_T_Inst] | None, / ) -> _GetOnlyBoundNamedProperty[_T_Inst, _P_Get, _R_Get]: ... def __set__(self, instance: _T_Inst, value: Any, /) -> NoReturn: ... class _SetOnlyBoundNamedProperty(Generic[_T_Inst, _P_Set]): name: str fset: Callable[Concatenate[_T_Inst, _P_Set], Any] - __doc__: Optional[str] + __doc__: str | None def __getitem__(self, index: Any, /) -> NoReturn: ... def __call__(self, *args: Any, **kwargs: Any) -> NoReturn: ... def __setitem__(self, index: Any, value: Any, /) -> None: ... @@ -216,13 +211,13 @@ class _SetOnlyBoundNamedProperty(Generic[_T_Inst, _P_Set]): class _SetOnlyNamedProperty(Generic[_T_Inst, _P_Set]): name: str fset: Callable[Concatenate[_T_Inst, _P_Set], Any] - __doc__: Optional[str] + __doc__: str | None @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / + self, instance: _T_Inst, owner: type[_T_Inst] | None, / ) -> _SetOnlyBoundNamedProperty[_T_Inst, _P_Set]: ... def __set__(self, instance: _T_Inst, value: Any, /) -> NoReturn: ... @@ -247,9 +242,7 @@ class _Descriptor(Protocol[_T_Inst, _R_Get]): @overload def __get__(self, instance: None, owner: type[_T_Inst], /) -> Self: ... @overload - def __get__( - self, instance: _T_Inst, owner: Optional[type[_T_Inst]], / - ) -> _R_Get: ... + def __get__(self, instance: _T_Inst, owner: type[_T_Inst] | None, /) -> _R_Get: ... # `__len__` for objects with `Count` @overload @@ -262,9 +255,7 @@ _T_E = TypeVar("_T_E", infer_variance=True) @overload def to_dunder_iter( - newenum: _UnionT[ - _Descriptor[_T_Inst, Iterator[_T_E]], Callable[[_T_Inst], Iterator[_T_E]] - ], + newenum: _Descriptor[_T_Inst, Iterator[_T_E]] | Callable[[_T_Inst], Iterator[_T_E]], ) -> Callable[[_T_Inst], Iterator[_T_E]]: ... @overload def to_dunder_iter(newenum: Any) -> Callable[..., NoReturn]: ... @@ -273,11 +264,9 @@ def to_dunder_iter(newenum: Any) -> Callable[..., NoReturn]: ... # `__call__` @overload def to_dunder_call( - item: _UnionT[ - _GetSetNamedProperty[_T_Inst, _P_Get, _R_Get, ...], - _GetOnlyNamedProperty[_T_Inst, _P_Get, _R_Get], - Callable[Concatenate[_T_Inst, _P_Get], _R_Get], - ], + item: _GetSetNamedProperty[_T_Inst, _P_Get, _R_Get, ...] + | _GetOnlyNamedProperty[_T_Inst, _P_Get, _R_Get] + | Callable[Concatenate[_T_Inst, _P_Get], _R_Get], ) -> Callable[Concatenate[_T_Inst, _P_Get], _R_Get]: ... @overload def to_dunder_call(item: Any) -> Callable[..., NoReturn]: ... @@ -285,11 +274,9 @@ def to_dunder_call(item: Any) -> Callable[..., NoReturn]: ... # `__getitem__` @overload def to_dunder_getitem( - item: _UnionT[ - _GetSetNamedProperty[_T_Inst, _P_Get, _R_Get, ...], - _GetOnlyNamedProperty[_T_Inst, _P_Get, _R_Get], - Callable[Concatenate[_T_Inst, _P_Get], _R_Get], - ], + item: _GetSetNamedProperty[_T_Inst, _P_Get, _R_Get, ...] + | _GetOnlyNamedProperty[_T_Inst, _P_Get, _R_Get] + | Callable[Concatenate[_T_Inst, _P_Get], _R_Get], ) -> Callable[Concatenate[_T_Inst, _P_Get], _R_Get]: ... @overload def to_dunder_getitem(item: Any) -> Callable[..., NoReturn]: ... @@ -297,20 +284,16 @@ def to_dunder_getitem(item: Any) -> Callable[..., NoReturn]: ... # `__setitem__` @overload def to_dunder_setitem( - item: _UnionT[ - _GetSetNamedProperty[_T_Inst, ..., Any, _P_Set], - _SetOnlyNamedProperty[_T_Inst, _P_Set], - ], + item: _GetSetNamedProperty[_T_Inst, ..., Any, _P_Set] + | _SetOnlyNamedProperty[_T_Inst, _P_Set], ) -> Callable[Concatenate[_T_Inst, _P_Set], Any]: ... @overload def to_dunder_setitem(item: Any) -> Callable[..., NoReturn]: ... -_PosParamFlagType: TypeAlias = tuple[int, Optional[str]] -_OptParamFlagType: TypeAlias = tuple[int, Optional[str], Any] -ParamFlagType: TypeAlias = _UnionT[_PosParamFlagType, _OptParamFlagType] +_PosParamFlagType: TypeAlias = tuple[int, str | None] +_OptParamFlagType: TypeAlias = tuple[int, str | None, Any] +ParamFlagType: TypeAlias = _PosParamFlagType | _OptParamFlagType _ResArgSpecElmType: TypeAlias = tuple[list[str], type[_CDataType]] _PosArgSpecElmType: TypeAlias = tuple[list[str], type[_CDataType], str] _OptArgSpecElmType: TypeAlias = tuple[list[str], type[_CDataType], str, Any] -ArgSpecElmType: TypeAlias = _UnionT[ - _ResArgSpecElmType, _PosArgSpecElmType, _OptArgSpecElmType -] +ArgSpecElmType: TypeAlias = _ResArgSpecElmType | _PosArgSpecElmType | _OptArgSpecElmType diff --git a/comtypes/malloc.py b/comtypes/malloc.py index b23cea32..22b934df 100644 --- a/comtypes/malloc.py +++ b/comtypes/malloc.py @@ -1,7 +1,7 @@ from ctypes import HRESULT, POINTER, OleDLL, WinDLL, byref, c_int, c_ulong, c_void_p from ctypes import c_size_t as SIZE_T from ctypes.wintypes import DWORD, LPVOID -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from comtypes import COMMETHOD, GUID, IUnknown from comtypes.GUID import _CoTaskMemFree as _CoTaskMemFree @@ -19,8 +19,8 @@ class IMalloc(IUnknown): ] if TYPE_CHECKING: - def Alloc(self, cb: int) -> Optional[int]: ... - def Realloc(self, pv: Any, cb: int) -> Optional[int]: ... + def Alloc(self, cb: int) -> int | None: ... + def Realloc(self, pv: Any, cb: int) -> int | None: ... def Free(self, py: Any) -> None: ... def GetSize(self, pv: Any) -> int: ... def DidAlloc(self, pv: Any) -> int: ... diff --git a/comtypes/persist.py b/comtypes/persist.py index 1312e0df..5894439e 100644 --- a/comtypes/persist.py +++ b/comtypes/persist.py @@ -12,7 +12,7 @@ from ctypes import POINTER, Structure, c_int, c_ulong, c_ushort, c_wchar_p from ctypes.wintypes import BOOL, DWORD, WORD -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from comtypes import COMMETHOD, GUID, HRESULT, IPersist, IUnknown from comtypes.automation import VARIANT, tagEXCEPINFO @@ -68,7 +68,7 @@ class IPropertyBag(IUnknown): if TYPE_CHECKING: def Read( - self, pszPropName: str, pVar: VARIANT, pErrorLog: Optional[IErrorLog] + self, pszPropName: str, pVar: VARIANT, pErrorLog: IErrorLog | None ) -> Any: ... def Write(self, pszPropName: str, pVar: Any) -> hints.Hresult: ... diff --git a/comtypes/recordinfo.py b/comtypes/recordinfo.py index 4cacd3d3..e7e708a9 100644 --- a/comtypes/recordinfo.py +++ b/comtypes/recordinfo.py @@ -7,7 +7,7 @@ c_wchar_p, ) from ctypes.wintypes import BOOL, LCID, ULONG -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any from comtypes import BSTR, COMMETHOD, GUID, HRESULT, IUnknown, _safearray from comtypes._automation import VARIANT @@ -23,7 +23,7 @@ class IRecordInfo(IUnknown): # C:/vc98/include/OAIDL.H 5974 _iid_ = GUID("{0000002F-0000-0000-C000-000000000046}") - def GetFieldNames(self, *args: Any) -> list[Optional[str]]: + def GetFieldNames(self, *args: Any) -> list[str | None]: count = ctypes.c_ulong() self.__com_GetFieldNames(count, None) # type: ignore array = (BSTR * count.value)() diff --git a/comtypes/server/__init__.py b/comtypes/server/__init__.py index 4f9473dc..d0a9607a 100644 --- a/comtypes/server/__init__.py +++ b/comtypes/server/__init__.py @@ -48,7 +48,7 @@ def CreateInstance( def CreateInstance( self, punkouter: Optional["_Pointer[IUnknown]"] = None, - interface: Optional[type[IUnknown]] = None, + interface: type[IUnknown] | None = None, dynamic: bool = False, ) -> Any: if dynamic: diff --git a/comtypes/server/connectionpoints.py b/comtypes/server/connectionpoints.py index 7ddb0b75..f88626a4 100644 --- a/comtypes/server/connectionpoints.py +++ b/comtypes/server/connectionpoints.py @@ -162,7 +162,7 @@ def IConnectionPointContainer_FindConnectionPoint( return CONNECT_E_NOCONNECTION def Fire_Event( - self, itf: _UnionT[int, type[IDispatch]], name: str, *args: Any, **kw: Any + self, itf: int | type[IDispatch], name: str, *args: Any, **kw: Any ) -> Any: # Fire event 'name' with arguments *args and **kw. # Accepts either an interface index or an interface as first argument. diff --git a/comtypes/server/inprocserver.py b/comtypes/server/inprocserver.py index 073e3cd3..5d3f26a8 100644 --- a/comtypes/server/inprocserver.py +++ b/comtypes/server/inprocserver.py @@ -2,7 +2,7 @@ import sys import winreg from ctypes import c_void_p, pointer -from typing import TYPE_CHECKING, Any, Literal, Optional +from typing import TYPE_CHECKING, Any, Literal from comtypes import GUID, COMObject, IUnknown, hresult from comtypes._comobject import InprocServer as _InprocRefCounter @@ -28,7 +28,7 @@ def __init__(self, cls: type[COMObject]) -> None: def IClassFactory_CreateInstance( self, this: Any, - punkOuter: Optional[type["_Pointer[IUnknown]"]], + punkOuter: type["_Pointer[IUnknown]"] | None, riid: "_Pointer[GUID]", ppv: c_void_p, ) -> int: diff --git a/comtypes/server/localserver.py b/comtypes/server/localserver.py index 0c7fc964..7fc376fb 100644 --- a/comtypes/server/localserver.py +++ b/comtypes/server/localserver.py @@ -3,7 +3,7 @@ from collections.abc import Sequence from ctypes import HRESULT, OleDLL, byref, c_ulong, c_void_p from ctypes.wintypes import DWORD, LPDWORD -from typing import TYPE_CHECKING, Any, Literal, Optional +from typing import TYPE_CHECKING, Any, Literal import comtypes from comtypes import GUID, COMObject, IUnknown, hresult @@ -42,7 +42,7 @@ def run(classes: Sequence[type[COMObject]]) -> None: class ClassFactory(COMObject): _com_interfaces_ = [IClassFactory] _locks: int = 0 - _queue: Optional[queue.Queue] = None + _queue: queue.Queue | None = None regcls: int = REGCLS_MULTIPLEUSE def __init__(self, cls: type[COMObject], *args, **kw) -> None: @@ -79,7 +79,7 @@ def _revoke_class(self) -> None: def CreateInstance( self, this: Any, - punkOuter: Optional[type["_Pointer[IUnknown]"]], + punkOuter: type["_Pointer[IUnknown]"] | None, riid: "_Pointer[GUID]", ppv: c_void_p, ) -> int: diff --git a/comtypes/server/register.py b/comtypes/server/register.py index 188cec41..980d1054 100644 --- a/comtypes/server/register.py +++ b/comtypes/server/register.py @@ -45,7 +45,6 @@ from collections.abc import Iterable, Iterator from ctypes import WinDLL, WinError from ctypes.wintypes import HKEY, LONG, LPCWSTR, MAX_PATH -from typing import Optional, Union from winreg import HKEY_CLASSES_ROOT as HKCR from winreg import HKEY_CURRENT_USER as HKCU from winreg import HKEY_LOCAL_MACHINE as HKLM @@ -65,7 +64,7 @@ _debug = logging.getLogger(__name__).debug -def get_winerror(exception: OSError) -> Optional[int]: +def get_winerror(exception: OSError) -> int | None: try: return exception.winerror except AttributeError: @@ -94,7 +93,7 @@ def _non_zero(retval, func, args): } -def _explain(hkey: int) -> Union[str, int]: +def _explain(hkey: int) -> str | int: return _KEYS.get(hkey, hkey) @@ -124,8 +123,8 @@ class Registrar: work. """ - _frozen: Union[None, int, str] - _frozendllhandle: Optional[int] + _frozen: None | int | str + _frozendllhandle: int | None def __init__(self) -> None: self._frozen = getattr(sys, "frozen", None) @@ -147,7 +146,7 @@ def nodebug(self, cls: type) -> None: if get_winerror(detail) != 2: raise - def debug(self, cls: type, levels: list[str], format: Optional[str]) -> None: + def debug(self, cls: type, levels: list[str], format: str | None) -> None: """Write entries in the registry to setup logging for this clsid.""" # handlers # format @@ -171,7 +170,7 @@ def debug(self, cls: type, levels: list[str], format: Optional[str]) -> None: if get_winerror(detail) != 2: raise - def register(self, cls: type, executable: Optional[str] = None) -> None: + def register(self, cls: type, executable: str | None = None) -> None: """Register the COM server class.""" # First, we unregister the object with force=True, to force removal # of all registry entries, even if we would not write them. @@ -184,7 +183,7 @@ def register(self, cls: type, executable: Optional[str] = None) -> None: self._unregister(cls, force=True) self._register(cls, executable) - def _register(self, cls: type, executable: Optional[str] = None) -> None: + def _register(self, cls: type, executable: str | None = None) -> None: table = sorted(self._generate_reg_entries(cls)) _debug("Registering %s", cls) for hkey, subkey, valuename, value in table: @@ -276,8 +275,8 @@ class FrozenRegistryEntries(RegistryEntries): def __init__( self, cls: type, - frozen: Union[str, int], - frozendllhandle: Optional[int] = None, + frozen: str | int, + frozendllhandle: int | None = None, ) -> None: self._cls = cls self._frozen = frozen diff --git a/comtypes/test/gdi_helper.py b/comtypes/test/gdi_helper.py index 466cddbe..a9fbc5b1 100644 --- a/comtypes/test/gdi_helper.py +++ b/comtypes/test/gdi_helper.py @@ -13,7 +13,6 @@ UINT, WORD, ) -from typing import Optional BI_RGB = 0 # No compression DIB_RGB_COLORS = 0 @@ -87,7 +86,7 @@ class BITMAPINFO(Structure): @contextlib.contextmanager -def get_dc(hwnd: Optional[int]) -> Iterator[int]: +def get_dc(hwnd: int | None) -> Iterator[int]: """Context manager to get and release a device context (DC).""" dc = _GetDC(hwnd) assert dc, "Failed to get device context." @@ -99,7 +98,7 @@ def get_dc(hwnd: Optional[int]) -> Iterator[int]: @contextlib.contextmanager -def create_compatible_dc(hdc: Optional[int]) -> Iterator[int]: +def create_compatible_dc(hdc: int | None) -> Iterator[int]: """Context manager to create and delete a compatible device context.""" mem_dc = _CreateCompatibleDC(hdc) assert mem_dc, "Failed to create compatible memory DC." diff --git a/comtypes/test/test_logutil.py b/comtypes/test/test_logutil.py index 3414c377..e98de1e6 100644 --- a/comtypes/test/test_logutil.py +++ b/comtypes/test/test_logutil.py @@ -8,7 +8,7 @@ from ctypes import c_size_t as SIZE_T from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR from queue import Queue -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING from typing import Union as _UnionT from comtypes.client._events import SECURITY_ATTRIBUTES @@ -78,7 +78,7 @@ def create_file_mapping( flprotect: int, size_high: int, size_low: int, - name: Optional[str], + name: str | None, ) -> Iterator[int]: """Context manager to creates a Windows file mapping object.""" handle = _CreateFileMappingW(hfile, security, flprotect, size_high, size_low, name) @@ -109,7 +109,7 @@ def create_event( security: _UnionT["_Pointer[SECURITY_ATTRIBUTES]", "_CArgObject", None], manual: bool, init: bool, - name: Optional[str], + name: str | None, ) -> Iterator[int]: """Context manager to creates a Windows event object.""" handle = _CreateEventW(security, manual, init, name) diff --git a/comtypes/test/test_record_safearray_bstr.py b/comtypes/test/test_record_safearray_bstr.py index aa475dce..15f59c7b 100644 --- a/comtypes/test/test_record_safearray_bstr.py +++ b/comtypes/test/test_record_safearray_bstr.py @@ -13,8 +13,7 @@ from _ctypes import COMError from collections.abc import Callable from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar -from typing import Union as _UnionT +from typing import TYPE_CHECKING, Any, ClassVar, TypeVar from comtypes import CLSCTX_LOCAL_SERVER, IUnknown, _safearray from comtypes.client import CreateObject, GetModule @@ -70,10 +69,8 @@ class _BstrRecordScenariosMixin(_TCBase): """ interface: ClassVar[ - _UnionT[ - type["ComtypesCppTestSrvLib.IDualRecordSafearrayTest"], - type["ComtypesCppTestSrvLib.IDispRecordSafearrayTest"], - ] + type["ComtypesCppTestSrvLib.IDualRecordSafearrayTest"] + | type["ComtypesCppTestSrvLib.IDispRecordSafearrayTest"] ] def test_first_record_length_1_safearray_by_from_param(self): @@ -424,7 +421,7 @@ def enable_fault_log(tmpfile: Path) -> io.TextIOWrapper: return f -def run_in_mp(fn: Callable[[Path], Any]) -> tuple[Optional[int], str]: +def run_in_mp(fn: Callable[[Path], Any]) -> tuple[int | None, str]: """Run a function in a separate process and return exit code and output. Using spawn isolates the process so crashes like segfaults do not affect diff --git a/comtypes/test/test_record_safearray_value.py b/comtypes/test/test_record_safearray_value.py index f2423c8e..37126b0f 100644 --- a/comtypes/test/test_record_safearray_value.py +++ b/comtypes/test/test_record_safearray_value.py @@ -8,7 +8,6 @@ import unittest from _ctypes import COMError from typing import TYPE_CHECKING, ClassVar, TypeVar -from typing import Union as _UnionT from comtypes import CLSCTX_LOCAL_SERVER, IUnknown, _safearray from comtypes.client import CreateObject, GetModule @@ -75,10 +74,8 @@ class _ValueRecordScenariosMixin(_TCBase): """ interface: ClassVar[ - _UnionT[ - type["ComtypesCppTestSrvLib.IDualRecordSafearrayTest"], - type["ComtypesCppTestSrvLib.IDispRecordSafearrayTest"], - ] + type["ComtypesCppTestSrvLib.IDualRecordSafearrayTest"] + | type["ComtypesCppTestSrvLib.IDispRecordSafearrayTest"] ] def test_first_record_length_1_safearray_by_from_param(self): diff --git a/comtypes/test/test_showevents.py b/comtypes/test/test_showevents.py index 6468499f..04b76368 100644 --- a/comtypes/test/test_showevents.py +++ b/comtypes/test/test_showevents.py @@ -1,10 +1,9 @@ import doctest import unittest -from typing import Optional def load_tests( - loader: unittest.TestLoader, tests: unittest.TestSuite, pattern: Optional[str] + loader: unittest.TestLoader, tests: unittest.TestSuite, pattern: str | None ) -> unittest.TestSuite: import comtypes.test.test_showevents diff --git a/comtypes/test/test_storage.py b/comtypes/test/test_storage.py index b478a974..1d42b45b 100644 --- a/comtypes/test/test_storage.py +++ b/comtypes/test/test_storage.py @@ -6,7 +6,6 @@ from ctypes import HRESULT, POINTER, OleDLL, byref, c_ubyte from ctypes.wintypes import DWORD, FILETIME, PWCHAR from pathlib import Path -from typing import Optional import comtypes import comtypes.client @@ -58,7 +57,7 @@ def _get_pwcsname(stat: tagSTATSTG) -> WSTRING: CREATE_TEMP_TESTDOC = CREATE_TESTDOC | STGM_DELETEONRELEASE -def _create_docfile(mode: int, name: Optional[str] = None) -> IStorage: +def _create_docfile(mode: int, name: str | None = None) -> IStorage: stg = POINTER(IStorage)() _StgCreateDocfile(name, mode, 0, byref(stg)) return stg # type: ignore diff --git a/comtypes/test/test_stream.py b/comtypes/test/test_stream.py index ff927e02..c7586960 100644 --- a/comtypes/test/test_stream.py +++ b/comtypes/test/test_stream.py @@ -32,7 +32,6 @@ ULARGE_INTEGER, ) from pathlib import Path -from typing import Optional import comtypes.client from comtypes import hresult @@ -92,7 +91,7 @@ def _create_stream_on_hglobal( - handle: Optional[int] = None, delete_on_release: bool = True + handle: int | None = None, delete_on_release: bool = True ) -> IStream: # Create an IStream stream = POINTER(IStream)() # type: ignore diff --git a/comtypes/tools/codegenerator/codegenerator.py b/comtypes/tools/codegenerator/codegenerator.py index 5510450e..cf0ea80f 100644 --- a/comtypes/tools/codegenerator/codegenerator.py +++ b/comtypes/tools/codegenerator/codegenerator.py @@ -8,7 +8,7 @@ import textwrap import warnings from collections.abc import Iterable, Iterator, Mapping, Sequence -from typing import TYPE_CHECKING, Any, Literal, Optional +from typing import TYPE_CHECKING, Any, Literal from typing import Union as _UnionT import comtypes @@ -87,17 +87,15 @@ def adjust_blank( def generate( self, - item: _UnionT[ - tlbparser.ParsedType, - tlbparser.SpecType, - typedesc.EnumValue, - typedesc.StructureHead, - typedesc.StructureBody, - typedesc.ComInterfaceHead, - typedesc.DispInterfaceHead, - typedesc.ComInterfaceBody, - typedesc.DispInterfaceBody, - ], + item: tlbparser.ParsedType + | tlbparser.SpecType + | typedesc.EnumValue + | typedesc.StructureHead + | typedesc.StructureBody + | typedesc.ComInterfaceHead + | typedesc.DispInterfaceHead + | typedesc.ComInterfaceBody + | typedesc.DispInterfaceBody, ) -> None: if item in self.done: return @@ -233,7 +231,7 @@ def _generate_typelib_path(self, filename): self.names.add("typelib_path") def generate_wrapper_code( - self, tdescs: Sequence[tlbparser.ParsedType], filename: Optional[str] + self, tdescs: Sequence[tlbparser.ParsedType], filename: str | None ) -> str: """Returns the code for the COM type library wrapper module. @@ -639,7 +637,7 @@ def ComInterface(self, itf: typedesc.ComInterface) -> None: self.names.add(itf.name) def _is_known_interface( - self, item: _UnionT[typedesc.ComInterface, typedesc.DispInterface] + self, item: typedesc.ComInterface | typedesc.DispInterface ) -> bool: """Returns whether an interface is statically defined in `comtypes`, based on its name and iid. diff --git a/comtypes/tools/codegenerator/heads.py b/comtypes/tools/codegenerator/heads.py index 1baf68d3..7c8999ac 100644 --- a/comtypes/tools/codegenerator/heads.py +++ b/comtypes/tools/codegenerator/heads.py @@ -1,5 +1,4 @@ import io -from typing import Optional from comtypes.tools import typedesc from comtypes.tools.codegenerator import typeannotator @@ -60,7 +59,7 @@ def write(self, lib: typedesc.TypeLib) -> None: class CoClassHeadWriter: - def __init__(self, stream: io.StringIO, filename: Optional[str]) -> None: + def __init__(self, stream: io.StringIO, filename: str | None) -> None: self.stream = stream self.filename = filename diff --git a/comtypes/tools/codegenerator/modulenamer.py b/comtypes/tools/codegenerator/modulenamer.py index c855ee38..4bddc75f 100644 --- a/comtypes/tools/codegenerator/modulenamer.py +++ b/comtypes/tools/codegenerator/modulenamer.py @@ -1,5 +1,3 @@ -from typing import Optional - import comtypes from comtypes import typeinfo @@ -12,7 +10,7 @@ def name_wrapper_module(tlib: typeinfo.ITypeLib) -> str: return f"comtypes.gen.{modname}" -def name_friendly_module(tlib: typeinfo.ITypeLib) -> Optional[str]: +def name_friendly_module(tlib: typeinfo.ITypeLib) -> str | None: """Determine the friendly-name of a typelib module. If cannot get friendly-name from typelib, returns `None`. """ diff --git a/comtypes/tools/codegenerator/namespaces.py b/comtypes/tools/codegenerator/namespaces.py index 8c1845a5..e289ac7b 100644 --- a/comtypes/tools/codegenerator/namespaces.py +++ b/comtypes/tools/codegenerator/namespaces.py @@ -2,13 +2,12 @@ import warnings from collections import Counter from collections.abc import Iterator, Mapping, Sequence -from typing import Optional, overload -from typing import Union as _UnionT +from typing import overload class ImportedNamespaces: def __init__(self) -> None: - self.data: dict[str, Optional[str]] = {} + self.data: dict[str, str | None] = {} @overload def add(self, modulename: str, /) -> None: ... @@ -19,8 +18,8 @@ def add(self, symbolname: str, /, *, symbols: Mapping[str, str]) -> None: ... def add( self, name1: str, - name2: Optional[str] = None, - symbols: Optional[Mapping[str, str]] = None, + name2: str | None = None, + symbols: Mapping[str, str] | None = None, ) -> None: """Adds a namespace will be imported. @@ -58,7 +57,7 @@ def add( from_, import_ = name1, name2 self.data[import_] = from_ - def __contains__(self, item: _UnionT[str, tuple[str, str]]) -> bool: + def __contains__(self, item: str | tuple[str, str]) -> bool: """Returns item has already added. Examples: @@ -105,7 +104,7 @@ def _make_line(self, from_: str, imports: Sequence[str]) -> str: return code def getvalue(self) -> str: - ns: dict[str, Optional[set[str]]] = {} + ns: dict[str, set[str] | None] = {} lines: list[str] = [] for key, val in self.data.items(): if val is None: @@ -125,9 +124,9 @@ def getvalue(self) -> str: class DeclaredNamespaces: def __init__(self) -> None: - self.data: dict[tuple[str, str], Optional[str]] = {} + self.data: dict[tuple[str, str], str | None] = {} - def add(self, alias: str, definition: str, comment: Optional[str] = None) -> None: + def add(self, alias: str, definition: str, comment: str | None = None) -> None: """Adds a namespace will be declared. Examples: diff --git a/comtypes/tools/codegenerator/typeannotator.py b/comtypes/tools/codegenerator/typeannotator.py index a9e7ca17..6f04693a 100644 --- a/comtypes/tools/codegenerator/typeannotator.py +++ b/comtypes/tools/codegenerator/typeannotator.py @@ -1,16 +1,16 @@ import abc import keyword from collections.abc import Iterable, Iterator, Sequence -from typing import Any, Generic, Optional, Protocol, TypeVar +from typing import Any, Generic, Protocol, TypeVar from comtypes.tools import typedesc class _MethodTypeDesc(Protocol): - arguments: list[tuple[Any, str, list[str], Optional[Any]]] + arguments: list[tuple[Any, str, list[str], Any | None]] idlflags: list[str] name: str - doc: Optional[str] + doc: str | None _T_MTD = TypeVar("_T_MTD", bound=_MethodTypeDesc) @@ -24,7 +24,7 @@ def is_put_or_putref(self) -> bool: return "propput" in self.method.idlflags or "propputref" in self.method.idlflags @property - def inarg_specs(self) -> Sequence[tuple[Any, str, Optional[Any]]]: + def inarg_specs(self) -> Sequence[tuple[Any, str, Any | None]]: index = 0 result = [] for typ, name, flags, default in self.method.arguments: @@ -40,7 +40,7 @@ def getvalue(self, name: str) -> str: ... _CatMths = tuple[ # categorized methods - str, Optional[_T_MTD], Optional[_T_MTD], Optional[_T_MTD], Optional[_T_MTD] + str, _T_MTD | None, _T_MTD | None, _T_MTD | None, _T_MTD | None ] @@ -52,7 +52,7 @@ def __init__(self) -> None: def to_method_annotator(self, method: _T_MTD) -> _MethodAnnotator[_T_MTD]: ... def _iter_methods(self, members: Iterable[_T_MTD]) -> Iterator[_CatMths[_T_MTD]]: - methods: dict[str, list[Optional[_T_MTD]]] = {} + methods: dict[str, list[_T_MTD | None]] = {} MTH = 0 GET = 1 PUT = 2 @@ -105,9 +105,9 @@ def _patch_dunder(self, name: str) -> None: def _define_named_prop( self, mem_name: str, - getter: Optional[str] = None, - setter: Optional[str] = None, - doc: Optional[str] = None, + getter: str | None = None, + setter: str | None = None, + doc: str | None = None, ) -> None: if getter and setter: content = ( @@ -128,9 +128,9 @@ def _define_named_prop( def _define_normal_prop( self, mem_name: str, - getter: Optional[str] = None, - setter: Optional[str] = None, - doc: Optional[str] = None, + getter: str | None = None, + setter: str | None = None, + doc: str | None = None, ) -> None: if getter and setter: content = f"{mem_name} = hints.normal_property({getter}, {setter})" @@ -242,7 +242,7 @@ def _to_outtype(typ: Any) -> str: return "hints.Incomplete" -def _generate_trailing_params(specs: Sequence[tuple[Any, str, Optional[Any]]]) -> str: +def _generate_trailing_params(specs: Sequence[tuple[Any, str, Any | None]]) -> str: """Generates a type hint for variadic positional arguments. This is for cases where required parameters follow optional ones, which is diff --git a/comtypes/tools/tlbparser.py b/comtypes/tools/tlbparser.py index 1d78719a..20e7703d 100644 --- a/comtypes/tools/tlbparser.py +++ b/comtypes/tools/tlbparser.py @@ -5,7 +5,7 @@ from collections.abc import Mapping from ctypes import alignment, c_void_p, sizeof, windll from ctypes.wintypes import MAX_PATH -from typing import Any, Optional, TypeVar +from typing import Any, TypeVar from typing import Union as _UnionT from comtypes import IUnknown, automation, typeinfo @@ -142,7 +142,7 @@ def midlSAFEARRAY(typ: _PT) -> typedesc.SAFEARRAYType[_PT]: typedesc.CoClass, typedesc.ComInterface, typedesc.DispInterface, - typedesc.Typedef["_UnionT[ParsedType, SpecType]"], + typedesc.Typedef["ParsedType | SpecType"], typedesc.Structure, typedesc.Union, typedesc.Enumeration, @@ -150,9 +150,9 @@ def midlSAFEARRAY(typ: _PT) -> typedesc.SAFEARRAYType[_PT]: SpecType = _UnionT[ typedesc.FundamentalType, - typedesc.PointerType["_UnionT[ParsedType, SpecType]"], - typedesc.ArrayType["_UnionT[ParsedType, SpecType]"], - typedesc.SAFEARRAYType["_UnionT[ParsedType, SpecType]"], + typedesc.PointerType["ParsedType | SpecType"], + typedesc.ArrayType["ParsedType | SpecType"], + typedesc.SAFEARRAYType["ParsedType | SpecType"], ] ################################################################ @@ -168,7 +168,7 @@ class Parser: def make_type( self, tdesc: typeinfo.TYPEDESC, tinfo: typeinfo.ITypeInfo - ) -> _UnionT[ParsedType, SpecType]: + ) -> ParsedType | SpecType: if tdesc.vt in COMTYPES: return COMTYPES[tdesc.vt] if tdesc.vt == automation.VT_CARRAY: @@ -314,7 +314,7 @@ def ParseModule(self, tinfo: typeinfo.ITypeInfo, ta: typeinfo.TYPEATTR) -> None: # TKIND_INTERFACE = 3 def ParseInterface( self, tinfo: typeinfo.ITypeInfo, ta: typeinfo.TYPEATTR - ) -> Optional[typedesc.ComInterface]: + ) -> typedesc.ComInterface | None: itf_name, itf_doc = tinfo.GetDocumentation(-1)[0:2] assert ta.cImplTypes <= 1 if ta.cImplTypes == 0 and itf_name != "IUnknown": @@ -638,7 +638,7 @@ def ParseUnion( ################################################################ - def _typelib_module(self, tlib: Optional[typeinfo.ITypeLib] = None) -> str: + def _typelib_module(self, tlib: typeinfo.ITypeLib | None = None) -> str: if tlib is None: tlib = self.tlib # return a string that uniquely identifies a typelib. @@ -647,9 +647,9 @@ def _typelib_module(self, tlib: Optional[typeinfo.ITypeLib] = None) -> str: def _register( self, - name: Optional[str], + name: str | None, value: ParsedType, - tlib: Optional[typeinfo.ITypeLib] = None, + tlib: typeinfo.ITypeLib | None = None, ) -> None: modname = self._typelib_module(tlib) fullname = f"{modname}.{name}" @@ -661,7 +661,7 @@ def _register( raise ValueError(f"Bug: Multiple registered name '{name}': {value!r}") self.items[fullname] = value - def parse_typeinfo(self, tinfo: typeinfo.ITypeInfo) -> Optional[ParsedType]: + def parse_typeinfo(self, tinfo: typeinfo.ITypeInfo) -> ParsedType | None: name = tinfo.GetDocumentation(-1)[0] modname = self._typelib_module() try: @@ -706,7 +706,7 @@ def parse_typeinfo(self, tinfo: typeinfo.ITypeInfo) -> Optional[ParsedType]: def _parse_DualInterface( self, tinfo: typeinfo.ITypeInfo - ) -> Optional[typedesc.ComInterface]: + ) -> typedesc.ComInterface | None: ta = tinfo.GetTypeAttr() assert ta.typekind == typeinfo.TKIND_INTERFACE return self.ParseInterface(tinfo, ta) @@ -801,7 +801,7 @@ def __init__(self, tlib): # path = r"c:\vc98\include\activscp.tlb" -def get_tlib_filename(tlib: typeinfo.ITypeLib) -> Optional[str]: +def get_tlib_filename(tlib: typeinfo.ITypeLib) -> str | None: # seems if the typelib is not registered, there's no way to # determine the filename. la = tlib.GetLibAttr() diff --git a/comtypes/tools/typedesc.py b/comtypes/tools/typedesc.py index c6908444..7ed44974 100644 --- a/comtypes/tools/typedesc.py +++ b/comtypes/tools/typedesc.py @@ -3,7 +3,7 @@ import ctypes from collections.abc import Sequence -from typing import Any, Generic, Optional, TypeVar, final +from typing import Any, Generic, TypeVar, final from typing import Union as _UnionT from comtypes import typeinfo @@ -26,7 +26,7 @@ @final class TypeLib: def __init__( - self, name: str, guid: str, major: int, minor: int, doc: Optional[str] = None + self, name: str, guid: str, major: int, minor: int, doc: str | None = None ) -> None: self.name = name self.guid = guid @@ -43,9 +43,9 @@ class Constant: def __init__( self, name: str, - typ: _UnionT[Typedef, FundamentalType], + typ: Typedef | FundamentalType, value: Any, - doc: Optional[str], + doc: str | None, ) -> None: self.name = name self.typ = typ @@ -61,7 +61,7 @@ def __init__( name: str, size: int, align: int, - docs: Optional[tuple[str, Optional[str]]] = None, + docs: tuple[str, str | None] | None = None, ) -> None: # the type library containing the symbol self.tlib = tlib @@ -94,7 +94,7 @@ def __init__( name: str, returns: Any, idlflags: list[str], - doc: Optional[str], + doc: str | None, ) -> None: self.invkind = invkind self.name = name @@ -102,10 +102,10 @@ def __init__( self.idlflags = idlflags self.memid = memid self.doc = doc - self.arguments: list[tuple[Any, str, list[str], Optional[Any]]] = [] + self.arguments: list[tuple[Any, str, list[str], Any | None]] = [] def add_argument( - self, typ: Any, name: str, idlflags: list[str], default: Optional[Any] + self, typ: Any, name: str, idlflags: list[str], default: Any | None ) -> None: self.arguments.append((typ, name, idlflags, default)) @@ -120,7 +120,7 @@ def __init__( name: str, returns: Any, idlflags: list[str], - doc: Optional[str], + doc: str | None, ) -> None: self.dispid = dispid self.invkind = invkind @@ -128,10 +128,10 @@ def __init__( self.returns = returns self.idlflags = idlflags self.doc = doc - self.arguments: list[tuple[Any, str, list[str], Optional[Any]]] = [] + self.arguments: list[tuple[Any, str, list[str], Any | None]] = [] def add_argument( - self, typ: Any, name: str, idlflags: list[str], default: Optional[Any] + self, typ: Any, name: str, idlflags: list[str], default: Any | None ) -> None: self.arguments.append((typ, name, idlflags, default)) @@ -140,7 +140,7 @@ def add_argument( class DispProperty: # dispatchable COM property, parsed from typelib def __init__( - self, dispid: int, name: str, typ: Any, idlflags: list[str], doc: Optional[str] + self, dispid: int, name: str, typ: Any, idlflags: list[str], doc: str | None ) -> None: self.dispid = dispid self.name = name @@ -166,13 +166,13 @@ class DispInterface: def __init__( self, name: str, - base: "_UnionT[ComInterface, DispInterface, External]", + base: "ComInterface | DispInterface | External", iid: str, idlflags: list[str], - doc: Optional[str], + doc: str | None, ) -> None: self.name = name - self.members: list[_UnionT[DispMethod, DispProperty]] = [] + self.members: list[DispMethod | DispProperty] = [] self.base = base self.iid = iid self.idlflags = idlflags @@ -180,7 +180,7 @@ def __init__( self.itf_body = DispInterfaceBody(self) self.doc = doc - def add_member(self, member: _UnionT[DispMethod, DispProperty]) -> None: + def add_member(self, member: DispMethod | DispProperty) -> None: self.members.append(member) def get_body(self) -> DispInterfaceBody: @@ -207,10 +207,10 @@ class ComInterface: def __init__( self, name: str, - base: "_UnionT[None, ComInterface, External]", + base: "None | ComInterface | External", iid: str, idlflags: list[str], - doc: Optional[str], + doc: str | None, ) -> None: self.name = name self.members: list[ComMethod] = [] @@ -243,7 +243,7 @@ def __init__( clsid: str, idlflags: list[str], tlibattr: TLIBATTR, - doc: Optional[str], + doc: str | None, ) -> None: self.name = name self.clsid = clsid diff --git a/comtypes/tools/typedesc_base.py b/comtypes/tools/typedesc_base.py index ccd94910..bbeda57b 100644 --- a/comtypes/tools/typedesc_base.py +++ b/comtypes/tools/typedesc_base.py @@ -1,5 +1,5 @@ # typedesc.py - classes representing C type descriptions -from typing import Any, Generic, Optional, SupportsInt, TypeVar, final +from typing import Any, Generic, SupportsInt, TypeVar, final _TD = TypeVar("_TD") @@ -167,8 +167,8 @@ class _Struct_Union_Base: name: str align: int members: list["Field"] - artificial: Optional[Any] - size: Optional[int] + artificial: Any | None + size: int | None _recordinfo_: tuple[str, int, int, int, str] location = None @@ -191,8 +191,8 @@ def __init__( name: str, align: SupportsInt, members: list["Field"], - size: Optional[SupportsInt], - artificial: Optional[Any] = None, + size: SupportsInt | None, + artificial: Any | None = None, ) -> None: self.name = name self.align = int(align) @@ -212,8 +212,8 @@ def __init__( name: str, align: SupportsInt, members: list["Field"], - size: Optional[SupportsInt], - artificial: Optional[Any] = None, + size: SupportsInt | None, + artificial: Any | None = None, ) -> None: self.name = name self.align = int(align) @@ -229,7 +229,7 @@ def __init__( @final class Field: def __init__( - self, name: str, typ: Any, bits: Optional[Any], offset: SupportsInt + self, name: str, typ: Any, bits: Any | None, offset: SupportsInt ) -> None: self.name = name self.typ = typ diff --git a/comtypes/typeinfo.py b/comtypes/typeinfo.py index 5881c28c..408419f8 100644 --- a/comtypes/typeinfo.py +++ b/comtypes/typeinfo.py @@ -30,8 +30,7 @@ WCHAR, WORD, ) -from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, overload -from typing import Union as _UnionT +from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload # isort: off from comtypes import BSTR, COMMETHOD, GUID, IID, STDMETHOD, IUnknown, _CData @@ -247,7 +246,7 @@ def GetTypeComp(self) -> "ITypeComp": def GetDocumentation( self, index: int - ) -> tuple[str, Optional[str], int, Optional[str]]: + ) -> tuple[str, str | None, int, str | None]: """Return documentation for a type description.""" ... @@ -262,7 +261,7 @@ def GetLibAttr(self) -> "TLIBATTR": self.ReleaseTLibAttr, ) - def IsName(self, name: str, lHashVal: int = 0) -> Optional[str]: + def IsName(self, name: str, lHashVal: int = 0) -> str | None: """Check if there is type information for this name. Returns the name with capitalization found in the type @@ -275,9 +274,7 @@ def IsName(self, name: str, lHashVal: int = 0) -> Optional[str]: return namebuf[:].split("\0", 1)[0] # type: ignore return None - def FindName( - self, name: str, lHashVal: int = 0 - ) -> Optional[tuple[int, "ITypeInfo"]]: + def FindName(self, name: str, lHashVal: int = 0) -> tuple[int, "ITypeInfo"] | None: # Hm... # Could search for more than one name - should we support this? found = ctypes.c_ushort(1) @@ -332,7 +329,7 @@ def GetImplTypeFlags(self, index: int) -> int: # ), def GetDllEntry( self, memid: int, invkind: int - ) -> tuple[Optional[str], Optional[str], int]: + ) -> tuple[str | None, str | None, int]: """Return the dll name, function name, and ordinal for a function and invkind. """ @@ -342,7 +339,7 @@ def GetRefTypeInfo(self, href: int) -> "ITypeInfo": """Get type info for reftype""" ... - def GetMops(self, index: int) -> Optional[str]: + def GetMops(self, index: int) -> str | None: """Get marshalling opcodes (whatever that is...)""" ... @@ -369,9 +366,7 @@ def GetTypeAttr(self) -> "TYPEATTR": self.ReleaseTypeAttr, ) - def GetDocumentation( - self, memid: int - ) -> tuple[str, Optional[str], int, Optional[str]]: + def GetDocumentation(self, memid: int) -> tuple[str, str | None, int, str | None]: """Return name, docstring, helpcontext, and helpfile for 'memid'.""" name, doc, helpctx, helpfile = self._GetDocumentation(memid) # type: ignore return fix_name(name), fix_name(doc), helpctx, fix_name(helpfile) @@ -412,9 +407,9 @@ def AddressOfMember(self, memid: int, invkind: int) -> int: def CreateInstance( self, - punkouter: Optional[type["_Pointer[IUnknown]"]] = None, + punkouter: type["_Pointer[IUnknown]"] | None = None, interface: type[_T_IUnknown] = IUnknown, - iid: Optional[GUID] = None, + iid: GUID | None = None, ) -> _T_IUnknown: if iid is None: iid = interface._iid_ @@ -429,12 +424,12 @@ class ITypeComp(IUnknown): def Bind( self, name: str, flags: int = 0, lHashVal: int = 0 - ) -> _UnionT[ - tuple[Literal["function"], "FUNCDESC"], - tuple[Literal["variable"], "VARDESC"], - tuple[Literal["type"], "ITypeComp"], - None, - ]: + ) -> ( + tuple[Literal["function"], "FUNCDESC"] + | tuple[Literal["variable"], "VARDESC"] + | tuple[Literal["type"], "ITypeComp"] + | None + ): """Bind to a name""" bindptr = BINDPTR() desckind = DESCKIND() @@ -542,7 +537,7 @@ def SetFuncAndParamNames(self, index: int, *names: str) -> int: def LoadRegTypeLib( - guid: _UnionT[str, GUID], wMajorVerNum: int, wMinorVerNum: int, lcid: int = 0 + guid: str | GUID, wMajorVerNum: int, wMinorVerNum: int, lcid: int = 0 ) -> ITypeLib: """Load a registered type library""" tlib = POINTER(ITypeLib)() @@ -575,9 +570,7 @@ def UnRegisterTypeLib( return _UnRegisterTypeLib(byref(GUID(libID)), wVerMajor, wVerMinor, lcid, syskind) -def RegisterTypeLib( - tlib: ITypeLib, fullpath: str, helpdir: Optional[str] = None -) -> int: +def RegisterTypeLib(tlib: ITypeLib, fullpath: str, helpdir: str | None = None) -> int: """Register a type library in the registry""" return _RegisterTypeLib(tlib, c_wchar_p(fullpath), c_wchar_p(helpdir)) @@ -618,7 +611,7 @@ def QueryPathOfRegTypeLib( return pathname.value.split("\0")[0] -def GetModuleFileName(handle: Optional[int], maxsize: int) -> str: +def GetModuleFileName(handle: int | None, maxsize: int) -> str: """Returns the fullpath of the loaded module specified by the handle. If the handle is NULL, returns the executable file path of the current process. From 7cebc3c223a0f4c01afa18b7bdd9b8f987382d89 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 3/9] style: Convert remaining type aliases to PEP 604. Python 3.10 is now the minimum supported version, so type aliases no longer need the older `typing.Union` form. Use `|` consistently in the remaining aliases to make the COM type descriptions easier to read and maintain. --- comtypes/_memberspec.py | 12 +++--- comtypes/client/_events.py | 3 +- comtypes/connectionpoints.py | 3 +- comtypes/tools/codegenerator/codegenerator.py | 17 ++++----- comtypes/tools/codegenerator/helpers.py | 2 +- comtypes/tools/tlbparser.py | 38 +++++++++---------- comtypes/tools/typedesc.py | 3 +- 7 files changed, 37 insertions(+), 41 deletions(-) diff --git a/comtypes/_memberspec.py b/comtypes/_memberspec.py index 3b9140e5..523664a7 100644 --- a/comtypes/_memberspec.py +++ b/comtypes/_memberspec.py @@ -1,6 +1,6 @@ import ctypes from collections.abc import Callable, Iterator, Sequence -from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Optional +from typing import TYPE_CHECKING, Any, Literal, NamedTuple from typing import Union as _UnionT import comtypes @@ -95,8 +95,8 @@ def _resolve_argspec( _VarFlagsWithDispIdHelpstr = tuple["dispid", "helpstring", hints.Unpack[_VarFlags]] _VarFlagsWithDispId = tuple["dispid", hints.Unpack[_VarFlags]] _VarFlagsWithHelpstr = tuple["helpstring", hints.Unpack[_VarFlags]] - _DispIdlFlags = _UnionT[_VarFlagsWithDispIdHelpstr, _VarFlagsWithDispId] - _ComIdlFlags = _UnionT[_VarFlags, _VarFlagsWithHelpstr] + _DispIdlFlags = _VarFlagsWithDispIdHelpstr | _VarFlagsWithDispId + _ComIdlFlags = _VarFlags | _VarFlagsWithHelpstr class _ComMemberSpec(NamedTuple): @@ -135,7 +135,7 @@ def is_prop(self) -> bool: # Specifier of a slot of method or property. # This should be `typing.Protocol` if supporting Py3.8+ only. -_MemberSpec = _UnionT[_ComMemberSpec, _DispMemberSpec] +_MemberSpec = _ComMemberSpec | _DispMemberSpec def _is_spec_prop(m: _MemberSpec): @@ -439,8 +439,8 @@ def call_with_inout(self, *args, **kw): ################################################################ -_PropFunc = Optional[Callable[..., Any]] -_DocType = Optional[str] +_PropFunc = Callable[..., Any] | None +_DocType = str | None class PropertyMapping: diff --git a/comtypes/client/_events.py b/comtypes/client/_events.py index f543f18b..9bea65d8 100644 --- a/comtypes/client/_events.py +++ b/comtypes/client/_events.py @@ -15,7 +15,6 @@ ULONG, ) from typing import Any -from typing import Union as _UnionT import comtypes from comtypes import COMObject, IUnknown, hresult @@ -62,7 +61,7 @@ class SECURITY_ATTRIBUTES(Structure): _CloseHandle.argtypes = [HANDLE] _CloseHandle.restype = BOOL -_ReceiverType = _UnionT[COMObject, IUnknown] +_ReceiverType = COMObject | IUnknown class _AdviseConnection: diff --git a/comtypes/connectionpoints.py b/comtypes/connectionpoints.py index f630dc7f..865c6aa9 100644 --- a/comtypes/connectionpoints.py +++ b/comtypes/connectionpoints.py @@ -1,6 +1,5 @@ from ctypes import POINTER, Structure, c_ulong from typing import TYPE_CHECKING -from typing import Union as _UnionT from comtypes import COMMETHOD, GUID, HRESULT, IUnknown @@ -9,7 +8,7 @@ from comtypes import hints # noqa # type: ignore - REFIID = _UnionT[_Pointer[GUID], _CArgObject] + REFIID = _Pointer[GUID] | _CArgObject _GUID = GUID diff --git a/comtypes/tools/codegenerator/codegenerator.py b/comtypes/tools/codegenerator/codegenerator.py index cf0ea80f..ec153148 100644 --- a/comtypes/tools/codegenerator/codegenerator.py +++ b/comtypes/tools/codegenerator/codegenerator.py @@ -9,7 +9,6 @@ import warnings from collections.abc import Iterable, Iterator, Mapping, Sequence from typing import TYPE_CHECKING, Any, Literal -from typing import Union as _UnionT import comtypes from comtypes import typeinfo @@ -36,14 +35,14 @@ __warn_on_munge__ = __debug__ -_InterfaceTypeDesc = _UnionT[ - typedesc.ComInterface, - typedesc.ComInterfaceHead, - typedesc.ComInterfaceBody, - typedesc.DispInterface, - typedesc.DispInterfaceHead, - typedesc.DispInterfaceBody, -] +_InterfaceTypeDesc = ( + typedesc.ComInterface + | typedesc.ComInterfaceHead + | typedesc.ComInterfaceBody + | typedesc.DispInterface + | typedesc.DispInterfaceHead + | typedesc.DispInterfaceBody +) class CodeGenerator: diff --git a/comtypes/tools/codegenerator/helpers.py b/comtypes/tools/codegenerator/helpers.py index bd7750b4..6df4b309 100644 --- a/comtypes/tools/codegenerator/helpers.py +++ b/comtypes/tools/codegenerator/helpers.py @@ -72,7 +72,7 @@ def get_real_type(tp): _DefValType = _UnionT["lcid", Any, None] -_IdlFlagType = _UnionT[str, dispid, helpstring] +_IdlFlagType = str | dispid | helpstring def _to_arg_definition( diff --git a/comtypes/tools/tlbparser.py b/comtypes/tools/tlbparser.py index 20e7703d..6e407f17 100644 --- a/comtypes/tools/tlbparser.py +++ b/comtypes/tools/tlbparser.py @@ -135,25 +135,25 @@ def midlSAFEARRAY(typ: _PT) -> typedesc.SAFEARRAYType[_PT]: # automation.VT_ARRAY = 8192 # automation.VT_BYREF = 16384 -ParsedType = _UnionT[ - typedesc.TypeLib, - typedesc.Constant, - typedesc.External, - typedesc.CoClass, - typedesc.ComInterface, - typedesc.DispInterface, - typedesc.Typedef["ParsedType | SpecType"], - typedesc.Structure, - typedesc.Union, - typedesc.Enumeration, -] - -SpecType = _UnionT[ - typedesc.FundamentalType, - typedesc.PointerType["ParsedType | SpecType"], - typedesc.ArrayType["ParsedType | SpecType"], - typedesc.SAFEARRAYType["ParsedType | SpecType"], -] +ParsedType = ( + typedesc.TypeLib + | typedesc.Constant + | typedesc.External + | typedesc.CoClass + | typedesc.ComInterface + | typedesc.DispInterface + | typedesc.Typedef["ParsedType | SpecType"] + | typedesc.Structure + | typedesc.Union + | typedesc.Enumeration +) + +SpecType = ( + typedesc.FundamentalType + | typedesc.PointerType["ParsedType | SpecType"] + | typedesc.ArrayType["ParsedType | SpecType"] + | typedesc.SAFEARRAYType["ParsedType | SpecType"] +) ################################################################ diff --git a/comtypes/tools/typedesc.py b/comtypes/tools/typedesc.py index 7ed44974..5dca2beb 100644 --- a/comtypes/tools/typedesc.py +++ b/comtypes/tools/typedesc.py @@ -4,7 +4,6 @@ import ctypes from collections.abc import Sequence from typing import Any, Generic, TypeVar, final -from typing import Union as _UnionT from comtypes import typeinfo from comtypes.tools.typedesc_base import ArrayType as ArrayType @@ -232,7 +231,7 @@ def get_head(self) -> ComInterfaceHead: _ImplTypeFlags = int -_Interface = _UnionT[ComInterface, DispInterface] +_Interface = ComInterface | DispInterface @final From ab75f2926e85dcf7d2fd351cb62bec11243f3a48 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 4/9] style: Complete PEP 604 union annotations Python 3.10 is the minimum supported version, so `typing.Union` and `Optional` are no longer needed. Use `|` consistently in the remaining type annotations to make them easier to read and maintain. Keep forward references as strings when their types are only available to type checkers, so the annotations do not require those names at runtime. --- comtypes/_comobject.py | 3 +-- comtypes/_memberspec.py | 5 ++--- comtypes/_vtbl.py | 5 ++--- comtypes/client/_activeobj.py | 5 +---- comtypes/client/_create.py | 9 ++------- comtypes/client/_generate.py | 2 +- comtypes/server/__init__.py | 8 ++++---- comtypes/server/connectionpoints.py | 1 - comtypes/test/test_logutil.py | 5 ++--- comtypes/tools/codegenerator/helpers.py | 5 ++--- comtypes/tools/tlbparser.py | 3 +-- 11 files changed, 18 insertions(+), 33 deletions(-) diff --git a/comtypes/_comobject.py b/comtypes/_comobject.py index 46e16f04..7965ae8f 100644 --- a/comtypes/_comobject.py +++ b/comtypes/_comobject.py @@ -15,7 +15,6 @@ ) from ctypes.wintypes import INT, LONG, LPVOID, UINT, ULONG, WORD from typing import TYPE_CHECKING, Any, ClassVar, TypeVar -from typing import Union as _UnionT import comtypes from comtypes import GUID, IPersist, IUnknown, _CoUninitialize, hresult @@ -355,7 +354,7 @@ def IUnknown_QueryInterface( self, this: Any, riid: "_Pointer[GUID]", - ppvObj: _UnionT[c_void_p, "_CArgObject"], + ppvObj: "c_void_p | _CArgObject", _debug=_debug, ) -> int: # XXX This is probably too slow. diff --git a/comtypes/_memberspec.py b/comtypes/_memberspec.py index 523664a7..652eddb5 100644 --- a/comtypes/_memberspec.py +++ b/comtypes/_memberspec.py @@ -1,7 +1,6 @@ import ctypes from collections.abc import Callable, Iterator, Sequence from typing import TYPE_CHECKING, Any, Literal, NamedTuple -from typing import Union as _UnionT import comtypes @@ -106,7 +105,7 @@ class _ComMemberSpec(NamedTuple): name: str argtypes: tuple[type["_CDataType"], ...] paramflags: tuple["hints.ParamFlagType", ...] | None - idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"] + idlflags: "_ComIdlFlags | _DispIdlFlags" doc: str | None def is_prop(self) -> bool: @@ -504,7 +503,7 @@ def add(self, m: _MemberSpec, func: Callable[..., Any]) -> None: # The following code assumes that the docstrings for # propget and propput are identical. - def __iter__(self) -> Iterator[tuple[str, _UnionT[property, "named_property"]]]: + def __iter__(self) -> Iterator[tuple[str, "property | named_property"]]: for name, doc, nargs, fget, fset in self._mapping: if nargs == 0: prop = property(fget, fset, None, doc) diff --git a/comtypes/_vtbl.py b/comtypes/_vtbl.py index 06e8bb31..30fb3e9f 100644 --- a/comtypes/_vtbl.py +++ b/comtypes/_vtbl.py @@ -3,7 +3,6 @@ from collections.abc import Callable, Iterator, Sequence from ctypes import WINFUNCTYPE, Structure, c_void_p from typing import TYPE_CHECKING, Any -from typing import Union as _UnionT import comtypes from comtypes import GUID, IUnknown, hresult @@ -229,7 +228,7 @@ def get_impl( interface: type[IUnknown], mthname: str, paramflags: tuple["hints.ParamFlagType", ...] | None, - idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"], + idlflags: "_ComIdlFlags | _DispIdlFlags", ) -> Callable[..., Any]: mth = self.find_impl(interface, mthname, paramflags, idlflags) if mth is None: @@ -251,7 +250,7 @@ def find_impl( interface: type[IUnknown], mthname: str, paramflags: tuple["hints.ParamFlagType", ...] | None, - idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"], + idlflags: "_ComIdlFlags | _DispIdlFlags", ) -> Callable[..., Any] | None: fq_name = f"{interface.__name__}_{mthname}" if interface._case_insensitive_: diff --git a/comtypes/client/_activeobj.py b/comtypes/client/_activeobj.py index bec55844..c259df84 100644 --- a/comtypes/client/_activeobj.py +++ b/comtypes/client/_activeobj.py @@ -1,5 +1,4 @@ from typing import Any, Literal, TypeVar, overload -from typing import Union as _UnionT import comtypes import comtypes.client.dynamic @@ -24,9 +23,7 @@ def GetActiveObject( progid: str | type[CoClass] | GUID, interface: None = None, dynamic: Literal[True] = True, -) -> _UnionT[ - "comtypes.client.lazybind.Dispatch", "comtypes.client.dynamic._Dispatch" -]: ... +) -> "comtypes.client.lazybind.Dispatch | comtypes.client.dynamic._Dispatch": ... @overload def GetActiveObject( progid: str | type[CoClass] | GUID, diff --git a/comtypes/client/_create.py b/comtypes/client/_create.py index dd5300cf..a5036e39 100644 --- a/comtypes/client/_create.py +++ b/comtypes/client/_create.py @@ -1,6 +1,5 @@ import logging from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload -from typing import Union as _UnionT import comtypes import comtypes.client.dynamic @@ -70,9 +69,7 @@ def CreateObject( interface: None = None, dynamic: Literal[True] = True, pServerInfo: "None | _CArgObject | COSERVERINFO" = None, -) -> _UnionT[ - "comtypes.client.lazybind.Dispatch", "comtypes.client.dynamic._Dispatch" -]: ... +) -> "comtypes.client.lazybind.Dispatch | comtypes.client.dynamic._Dispatch": ... @overload def CreateObject( progid: str | type[CoClass] | GUID, @@ -155,9 +152,7 @@ def CoGetObject( displayname: str, interface: None = None, dynamic: Literal[True] = True, -) -> _UnionT[ - "comtypes.client.lazybind.Dispatch", "comtypes.client.dynamic._Dispatch" -]: ... +) -> "comtypes.client.lazybind.Dispatch | comtypes.client.dynamic._Dispatch": ... @overload def CoGetObject( displayname: str, diff --git a/comtypes/client/_generate.py b/comtypes/client/_generate.py index caa427a5..f0c132fd 100644 --- a/comtypes/client/_generate.py +++ b/comtypes/client/_generate.py @@ -64,7 +64,7 @@ def GetModule(tlib: Any | typeinfo.ITypeLib) -> types.ModuleType: - interpreted as relative to the callers `__file__`, if this exists - a COM CLSID `GUID` - a `tuple`/`list` specifying the typelib - - `List[_UnionT[str, int]]` + - `list[str | int]` - `(libid: str[, wMajorVerNum: int, wMinorVerNum: int[, lcid: int]])` - an object with `_reg_libid_: str` and `_reg_version_: Iterable[int]` diff --git a/comtypes/server/__init__.py b/comtypes/server/__init__.py index d0a9607a..68c6d965 100644 --- a/comtypes/server/__init__.py +++ b/comtypes/server/__init__.py @@ -1,6 +1,6 @@ import ctypes from ctypes import HRESULT, POINTER, byref -from typing import TYPE_CHECKING, Any, Literal, Optional, TypeVar, overload +from typing import TYPE_CHECKING, Any, Literal, TypeVar, overload import comtypes import comtypes.client @@ -34,20 +34,20 @@ class IClassFactory(IUnknown): @overload def CreateInstance( self, - punkouter: Optional["_Pointer[IUnknown]"] = None, + punkouter: "_Pointer[IUnknown] | None" = None, interface: type[_T_IUnknown] = IUnknown, dynamic: Literal[False] = False, ) -> _T_IUnknown: ... @overload def CreateInstance( self, - punkouter: Optional["_Pointer[IUnknown]"] = None, + punkouter: "_Pointer[IUnknown] | None" = None, interface: None = None, dynamic: Literal[True] = True, ) -> Any: ... def CreateInstance( self, - punkouter: Optional["_Pointer[IUnknown]"] = None, + punkouter: "_Pointer[IUnknown] | None" = None, interface: type[IUnknown] | None = None, dynamic: bool = False, ) -> Any: diff --git a/comtypes/server/connectionpoints.py b/comtypes/server/connectionpoints.py index f88626a4..9d32e25e 100644 --- a/comtypes/server/connectionpoints.py +++ b/comtypes/server/connectionpoints.py @@ -5,7 +5,6 @@ from ctypes import c_void_p, pointer from ctypes.wintypes import DWORD from typing import TYPE_CHECKING, Any -from typing import Union as _UnionT from comtypes import GUID, COMObject, IUnknown from comtypes.automation import IDispatch diff --git a/comtypes/test/test_logutil.py b/comtypes/test/test_logutil.py index e98de1e6..e0705435 100644 --- a/comtypes/test/test_logutil.py +++ b/comtypes/test/test_logutil.py @@ -9,7 +9,6 @@ from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR from queue import Queue from typing import TYPE_CHECKING -from typing import Union as _UnionT from comtypes.client._events import SECURITY_ATTRIBUTES from comtypes.logutil import NTDebugHandler @@ -74,7 +73,7 @@ @contextlib.contextmanager def create_file_mapping( hfile: int, - security: _UnionT["_Pointer[SECURITY_ATTRIBUTES]", "_CArgObject", None], + security: "_Pointer[SECURITY_ATTRIBUTES] | _CArgObject | None", flprotect: int, size_high: int, size_low: int, @@ -106,7 +105,7 @@ def map_view_of_file( @contextlib.contextmanager def create_event( - security: _UnionT["_Pointer[SECURITY_ATTRIBUTES]", "_CArgObject", None], + security: "_Pointer[SECURITY_ATTRIBUTES] | _CArgObject | None", manual: bool, init: bool, name: str | None, diff --git a/comtypes/tools/codegenerator/helpers.py b/comtypes/tools/codegenerator/helpers.py index 6df4b309..d1121d0a 100644 --- a/comtypes/tools/codegenerator/helpers.py +++ b/comtypes/tools/codegenerator/helpers.py @@ -1,7 +1,6 @@ import keyword from collections.abc import Iterator -from typing import Any, TypeVar, overload -from typing import Union as _UnionT +from typing import Any, TypeAlias, TypeVar, overload from comtypes.tools import typedesc from comtypes.tools.codegenerator.modulenamer import name_wrapper_module @@ -71,7 +70,7 @@ def get_real_type(tp): ################################################################ -_DefValType = _UnionT["lcid", Any, None] +_DefValType: TypeAlias = "lcid | Any | None" _IdlFlagType = str | dispid | helpstring diff --git a/comtypes/tools/tlbparser.py b/comtypes/tools/tlbparser.py index 6e407f17..be34bc00 100644 --- a/comtypes/tools/tlbparser.py +++ b/comtypes/tools/tlbparser.py @@ -6,7 +6,6 @@ from ctypes import alignment, c_void_p, sizeof, windll from ctypes.wintypes import MAX_PATH from typing import Any, TypeVar -from typing import Union as _UnionT from comtypes import IUnknown, automation, typeinfo from comtypes.tools import typedesc @@ -16,7 +15,7 @@ ################################ -_PT = TypeVar("_PT", bound=_UnionT["ParsedType", "SpecType"]) +_PT = TypeVar("_PT", bound="ParsedType | SpecType") def PTR(typ: _PT) -> typedesc.PointerType[_PT]: From dbbae175c3e745d8ac69ce7e57bed6a41f5b4e66 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 5/9] ci: Align checks with the Python 3.10 support floor. --- .github/workflows/autofmt.yml | 2 +- .github/workflows/autotest.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/autofmt.yml b/.github/workflows/autofmt.yml index 0bbaca21..e521dcce 100644 --- a/.github/workflows/autofmt.yml +++ b/.github/workflows/autofmt.yml @@ -12,7 +12,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v6 with: - python-version: 3.9 + python-version: 3.10 - name: Install ruff run: pip install ruff==0.6.9 - name: Check format diff --git a/.github/workflows/autotest.yml b/.github/workflows/autotest.yml index 60b25c7f..30128853 100644 --- a/.github/workflows/autotest.yml +++ b/.github/workflows/autotest.yml @@ -14,7 +14,7 @@ jobs: fail-fast: false matrix: os: [windows-latest] - python-version: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14', '3.15'] + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.15'] architecture: ['x86', 'x64'] support: ['with 3rd parties', 'without 3rd parties'] steps: @@ -62,7 +62,7 @@ jobs: strategy: matrix: os: [windows-2025, windows-2022] - python-version: ['3.9', '3.10', '3.11', '3.12', '3.13', '3.14', '3.15'] + python-version: ['3.10', '3.11', '3.12', '3.13', '3.14', '3.15'] architecture: ['x86', 'x64'] steps: - uses: actions/checkout@v6 From 0439d3680a09302540d9f484de4c4514e0bb737a Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 6/9] chore: Remove obsolete `automation` lint suppressions. The `automation` module no longer needs the unused ctypes imports or the runtime-only `_CArgObject` alias. --- comtypes/automation.py | 6 +----- pyproject.toml | 1 - 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/comtypes/automation.py b/comtypes/automation.py index d6e314d2..a1b6e147 100644 --- a/comtypes/automation.py +++ b/comtypes/automation.py @@ -1,7 +1,7 @@ # comtypes.automation module from _ctypes import COMError from collections.abc import Sequence -from ctypes import HRESULT, POINTER, byref, c_int, c_uint, c_ulong, c_wchar_p, pointer +from ctypes import HRESULT, POINTER, byref, c_uint, c_ulong, c_wchar_p, pointer from ctypes.wintypes import UINT, WORD from ctypes.wintypes import VARIANT_BOOL as VARIANT_BOOL from ctypes.wintypes import WCHAR as WCHAR @@ -19,12 +19,8 @@ from comtypes.safearray import _midlSAFEARRAY as _midlSAFEARRAY if TYPE_CHECKING: - from ctypes import _CArgObject, _CDataType - from comtypes import hints # type: ignore from comtypes._memberspec import _DispMemberSpec -else: - _CArgObject = type(byref(c_int())) # isort: off from comtypes._automation import LCID as LCID diff --git a/pyproject.toml b/pyproject.toml index d7d01201..3bea1c4a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -66,7 +66,6 @@ ignore = ["E402"] # production "comtypes/_npsupport.py" = ["F401"] "comtypes/_vtbl.py" = ["E722"] -"comtypes/automation.py" = ["F401", "F403", "F405"] "comtypes/viewobject.py" = ["F403", "F405"] "comtypes/client/_constants.py" = ["F401"] "comtypes/server/automation.py" = ["F403", "F405"] From abf9c20f07f2b17c01657e289b4d54ba3cf38d15 Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 7/9] ci: Keep GH-212 skips limited to affected Python versions. Python 3.9 is no longer supported, so it should not determine whether these tests run. Keep skipping only Python 3.10 releases before 3.10.10 and Python 3.11 releases before 3.11.2, where the GH-212 issue still affects the tests. --- comtypes/test/test_excel.py | 3 +-- comtypes/test/test_string_safearray_inside_variant.py | 8 +++----- 2 files changed, 4 insertions(+), 7 deletions(-) diff --git a/comtypes/test/test_excel.py b/comtypes/test/test_excel.py index aabbba13..08691f36 100644 --- a/comtypes/test/test_excel.py +++ b/comtypes/test/test_excel.py @@ -134,8 +134,7 @@ def test(self): @unittest.skipIf(IMPORT_FAILED, "This depends on Excel.") @unittest.skipIf( - sys.version_info[:2] == (3, 9) - or (sys.version_info[:2] == (3, 10) and sys.version_info < (3, 10, 10)) + (sys.version_info[:2] == (3, 10) and sys.version_info < (3, 10, 10)) or (sys.version_info[:2] == (3, 11) and sys.version_info < (3, 11, 2)), f"This fails in {PY_VER}. See https://github.com/enthought/comtypes/issues/212", ) diff --git a/comtypes/test/test_string_safearray_inside_variant.py b/comtypes/test/test_string_safearray_inside_variant.py index 839e055c..f96b3f37 100644 --- a/comtypes/test/test_string_safearray_inside_variant.py +++ b/comtypes/test/test_string_safearray_inside_variant.py @@ -31,11 +31,9 @@ def _create_tester() -> "ComtypesCppTestSrvLib.IStringSafearrayInsideVariantTest PY_VER = "Python {0}.{1}.{2}".format(*sys.version_info[:3]) # It seems to be the same root cause we discussed in https://github.com/enthought/comtypes/issues/212 -IS_SKIP_PY_VER = sys.version_info[:2] == ( - (3, 9) - or (sys.version_info[:2] == (3, 10) and sys.version_info < (3, 10, 10)) - or (sys.version_info[:2] == (3, 11) and sys.version_info < (3, 11, 2)) -) +IS_SKIP_PY_VER = ( + sys.version_info[:2] == (3, 10) and sys.version_info < (3, 10, 10) +) or (sys.version_info[:2] == (3, 11) and sys.version_info < (3, 11, 2)) @unittest.skipIf(IS_SKIP_PY_VER, f"This fails in {PY_VER}.") From bb618127eab9c3f604fe9add2fc18f574229319f Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:33:25 +0900 Subject: [PATCH 8/9] docs: Clarify the Python 3.10 support requirement. --- README.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1cc596d3..38b03ad0 100644 --- a/README.md +++ b/README.md @@ -11,14 +11,15 @@ `comtypes` allows you to define, call, and implement custom and dispatch-based COM interfaces in pure Python. -`comtypes` requires Windows and Python 3.9 or later. +`comtypes` requires Windows and Python 3.10 or later. +- Version [1.5.0](https://pypi.org/project/comtypes/1.5.0/) is the last version to support Python 3.9. - Version <= [1.4.17](https://pypi.org/project/comtypes/1.4.17/) has issues with enum behavior on Python 3.15 as reported in [GH-894](https://github.com/enthought/comtypes/issues/894). Version [1.5.0](https://pypi.org/project/comtypes/1.5.0/) supports Python 3.15. - Version [1.4.12](https://pypi.org/project/comtypes/1.4.12/) is the last version to support Python 3.8. - Version <= [1.4.7](https://pypi.org/project/comtypes/1.4.7/) does not work with Python 3.13 as reported in [GH-618](https://github.com/enthought/comtypes/issues/618). Version [1.4.8](https://pypi.org/project/comtypes/1.4.8/) can work with Python 3.13. - Version [1.4.6](https://pypi.org/project/comtypes/1.4.6/) is the last version to support Python 3.7. - Version [1.2.1](https://pypi.org/project/comtypes/1.2.1/) is the last version to support Python 2.7 and 3.3–3.6. -- Certain `comtypes` functions may not work correctly in Python 3.8 and 3.9 as reported in [GH-212](https://github.com/enthought/comtypes/issues/212). This bug has been fixed in Python >= 3.10.10 and >= 3.11.2. +- In older releases that support Python 3.8 or 3.9, certain `comtypes` functions may not work correctly as reported in [GH-212](https://github.com/enthought/comtypes/issues/212). This bug has been fixed in Python >= 3.10.10 and >= 3.11.2. ## Installation From f8bfd5d343739a22c1c62214bfba585c0c4d489d Mon Sep 17 00:00:00 2001 From: junkmd Date: Thu, 12 Nov 2026 23:57:58 +0900 Subject: [PATCH 9/9] ci: Enclose Python version in quotes for consistency. --- .github/workflows/autofmt.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/autofmt.yml b/.github/workflows/autofmt.yml index e521dcce..f5c158f1 100644 --- a/.github/workflows/autofmt.yml +++ b/.github/workflows/autofmt.yml @@ -12,7 +12,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v6 with: - python-version: 3.10 + python-version: "3.10" - name: Install ruff run: pip install ruff==0.6.9 - name: Check format