Skip to content

Commit f2bd605

Browse files
authored
Update *.py and _post_coinit/*.py files for PEP585 compliance. (#880)
* Update `comtypes/_post_coinit/_cominterface_meta_patcher.py` for PEP585 compliance. * Update `comtypes/_post_coinit/activeobj.py` for PEP585 compliance. * Update `comtypes/_post_coinit/bstr.py` for PEP585 compliance. * Update `comtypes/_post_coinit/misc.py` for PEP585 compliance. * Update `comtypes/_post_coinit/unknwn.py` for PEP585 compliance. * Update `comtypes/__init__.py` for PEP585 compliance. * Update `comtypes/_comobject.py` for PEP585 compliance. * Update `comtypes/_memberspec.py` for PEP585 compliance. * Update `comtypes/_vtbl.py` for PEP585 compliance. * Update `comtypes/automation.py` for PEP585 compliance. * Update `comtypes/connectionpoints.py` for PEP585 compliance. * Update `comtypes/messageloop.py` for PEP585 compliance. * Update `comtypes/safearray.py` for PEP585 compliance. * Update `comtypes/shelllink.py` for PEP585 compliance. * Update `comtypes/stream.py` for PEP585 compliance. * Update `comtypes/typeinfo.py` for PEP585 compliance. * Update `comtypes/util.py` for PEP585 compliance.
1 parent ab2b95e commit f2bd605

17 files changed

+143
-184
lines changed

comtypes/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from ctypes import * # noqa # type: ignore
2727
from ctypes import HRESULT, OleDLL, WinDLL, _SimpleCData, c_int, c_ulong
2828
from ctypes.wintypes import DWORD, LPVOID
29-
from typing import TYPE_CHECKING, Dict, Type
29+
from typing import TYPE_CHECKING
3030

3131
if TYPE_CHECKING:
3232
from ctypes import _CData # only in `typeshed`, private in runtime
@@ -172,10 +172,10 @@ def CoUninitialize():
172172
# global registries.
173173

174174
# allows to find interface classes by guid strings (iid)
175-
com_interface_registry: Dict[str, Type["IUnknown"]] = {}
175+
com_interface_registry: dict[str, type["IUnknown"]] = {}
176176

177177
# allows to find coclasses by guid strings (clsid)
178-
com_coclass_registry: Dict[str, Type["CoClass"]] = {}
178+
com_coclass_registry: dict[str, type["CoClass"]] = {}
179179

180180

181181
################################################################

comtypes/_comobject.py

Lines changed: 11 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import logging
22
import queue
33
from _ctypes import COMError, CopyComPointer
4+
from collections.abc import Callable, Sequence
45
from ctypes import (
56
POINTER,
67
FormatError,
@@ -13,19 +14,7 @@
1314
pointer,
1415
)
1516
from ctypes.wintypes import INT, LONG, LPVOID, UINT, ULONG, WORD
16-
from typing import (
17-
TYPE_CHECKING,
18-
Any,
19-
Callable,
20-
ClassVar,
21-
Dict,
22-
List,
23-
Optional,
24-
Sequence,
25-
Tuple,
26-
Type,
27-
TypeVar,
28-
)
17+
from typing import TYPE_CHECKING, Any, ClassVar, Optional, TypeVar
2918
from typing import Union as _UnionT
3019

3120
import comtypes
@@ -208,14 +197,14 @@ def DllCanUnloadNow(self) -> int:
208197

209198

210199
class COMObject:
211-
_com_interfaces_: ClassVar[List[Type[IUnknown]]]
212-
_outgoing_interfaces_: ClassVar[List[Type["hints.IDispatch"]]]
213-
_instances_: ClassVar[Dict["COMObject", None]] = {}
200+
_com_interfaces_: ClassVar[list[type[IUnknown]]]
201+
_outgoing_interfaces_: ClassVar[list[type["hints.IDispatch"]]]
202+
_instances_: ClassVar[dict["COMObject", None]] = {}
214203
_reg_clsid_: ClassVar[GUID]
215-
_reg_typelib_: ClassVar[Tuple[str, int, int]]
204+
_reg_typelib_: ClassVar[tuple[str, int, int]]
216205
__typelib: "hints.ITypeLib"
217-
_com_pointers_: Dict[GUID, "hints.LP_LP_Vtbl"]
218-
_dispimpl_: Dict[Tuple[comtypes.dispid, int], Callable[..., Any]]
206+
_com_pointers_: dict[GUID, "hints.LP_LP_Vtbl"]
207+
_dispimpl_: dict[tuple[comtypes.dispid, int], Callable[..., Any]]
219208

220209
def __new__(cls, *args: Any, **kw: Any) -> "hints.Self":
221210
self = super().__new__(cls)
@@ -268,15 +257,15 @@ def __prepare_comobject(self) -> None:
268257
for itf in interfaces[::-1]:
269258
self.__make_interface_pointer(itf)
270259

271-
def __make_interface_pointer(self, itf: Type[IUnknown]) -> None:
260+
def __make_interface_pointer(self, itf: type[IUnknown]) -> None:
272261
finder = self._get_method_finder_(itf)
273262
iids, vtbl = create_vtbl_mapping(itf, finder)
274263
for iid in iids:
275264
self._com_pointers_[iid] = pointer(pointer(vtbl))
276265
if hasattr(itf, "_disp_methods_"):
277266
self._dispimpl_ = create_dispimpl(itf, finder)
278267

279-
def _get_method_finder_(self, itf: Type[IUnknown]) -> _MethodFinder:
268+
def _get_method_finder_(self, itf: type[IUnknown]) -> _MethodFinder:
280269
# This method can be overridden to customize how methods are found.
281270
return _MethodFinder(self)
282271

@@ -381,7 +370,7 @@ def IUnknown_QueryInterface(
381370
_debug("%r.QueryInterface(%s) -> E_NOINTERFACE", self, iid)
382371
return hresult.E_NOINTERFACE
383372

384-
def QueryInterface(self, interface: Type[_T_IUnknown]) -> _T_IUnknown:
373+
def QueryInterface(self, interface: type[_T_IUnknown]) -> _T_IUnknown:
385374
"Query the object for an interface pointer"
386375
# This method is NOT the implementation of
387376
# IUnknown::QueryInterface, instead it is supposed to be

comtypes/_memberspec.py

Lines changed: 35 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,6 @@
11
import ctypes
2-
from typing import (
3-
TYPE_CHECKING,
4-
Any,
5-
Callable,
6-
Dict,
7-
Iterator,
8-
List,
9-
Literal,
10-
NamedTuple,
11-
Optional,
12-
Sequence,
13-
Tuple,
14-
Type,
15-
)
2+
from collections.abc import Callable, Iterator, Sequence
3+
from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Optional
164
from typing import Union as _UnionT
175

186
import comtypes
@@ -61,17 +49,17 @@ def _encode_idl(names: Sequence[str]) -> int:
6149

6250

6351
def _unpack_argspec(
64-
idl: List[str],
65-
typ: Type["_CDataType"],
52+
idl: list[str],
53+
typ: type["_CDataType"],
6654
name: Optional[str] = None,
6755
defval: Any = _NOTHING,
68-
) -> Tuple[List[str], Type["_CDataType"], Optional[str], Any]:
56+
) -> tuple[list[str], type["_CDataType"], Optional[str], Any]:
6957
return idl, typ, name, defval
7058

7159

7260
def _resolve_argspec(
73-
items: Tuple["hints.ArgSpecElmType", ...],
74-
) -> Tuple[Tuple["hints.ParamFlagType", ...], Tuple[Type["_CDataType"], ...]]:
61+
items: tuple["hints.ArgSpecElmType", ...],
62+
) -> tuple[tuple["hints.ParamFlagType", ...], tuple[type["_CDataType"], ...]]:
7563
"""Unpacks and converts from argspec to paramflags and argtypes.
7664
7765
- paramflags is a sequence of `(pflags: int, argname: str, | None[, defval: Any])`.
@@ -103,21 +91,21 @@ def _resolve_argspec(
10391

10492

10593
if TYPE_CHECKING:
106-
_VarFlags = Tuple[str, ...]
107-
_VarFlagsWithDispIdHelpstr = Tuple["dispid", "helpstring", hints.Unpack[_VarFlags]]
108-
_VarFlagsWithDispId = Tuple["dispid", hints.Unpack[_VarFlags]]
109-
_VarFlagsWithHelpstr = Tuple["helpstring", hints.Unpack[_VarFlags]]
94+
_VarFlags = tuple[str, ...]
95+
_VarFlagsWithDispIdHelpstr = tuple["dispid", "helpstring", hints.Unpack[_VarFlags]]
96+
_VarFlagsWithDispId = tuple["dispid", hints.Unpack[_VarFlags]]
97+
_VarFlagsWithHelpstr = tuple["helpstring", hints.Unpack[_VarFlags]]
11098
_DispIdlFlags = _UnionT[_VarFlagsWithDispIdHelpstr, _VarFlagsWithDispId]
11199
_ComIdlFlags = _UnionT[_VarFlags, _VarFlagsWithHelpstr]
112100

113101

114102
class _ComMemberSpec(NamedTuple):
115103
"""Specifier for a slot of COM method or property."""
116104

117-
restype: Optional[Type["_CDataType"]]
105+
restype: Optional[type["_CDataType"]]
118106
name: str
119-
argtypes: Tuple[Type["_CDataType"], ...]
120-
paramflags: Optional[Tuple["hints.ParamFlagType", ...]]
107+
argtypes: tuple[type["_CDataType"], ...]
108+
paramflags: Optional[tuple["hints.ParamFlagType", ...]]
121109
idlflags: _UnionT["_ComIdlFlags", "_DispIdlFlags"]
122110
doc: Optional[str]
123111

@@ -131,8 +119,8 @@ class _DispMemberSpec(NamedTuple):
131119
what: Literal["DISPMETHOD", "DISPPROPERTY"]
132120
name: str
133121
idlflags: "_DispIdlFlags"
134-
restype: Optional[Type["_CDataType"]]
135-
argspec: Tuple["hints.ArgSpecElmType", ...]
122+
restype: Optional[type["_CDataType"]]
123+
argspec: tuple["hints.ArgSpecElmType", ...]
136124

137125
@property
138126
def memid(self) -> int:
@@ -228,7 +216,7 @@ def COMMETHOD(idlflags, restype, methodname, *argspec) -> _ComMemberSpec:
228216
# workarounds for ctypes functions and parameters
229217

230218

231-
def _prepare_parameter(value: Any, atyp: Type["_CDataType"]) -> "_CDataType":
219+
def _prepare_parameter(value: Any, atyp: type["_CDataType"]) -> "_CDataType":
232220
# parameter was passed, call `from_param()` to
233221
# convert it to a `ctypes` type.
234222
if getattr(value, "_type_", None) is atyp:
@@ -249,8 +237,8 @@ def _prepare_parameter(value: Any, atyp: Type["_CDataType"]) -> "_CDataType":
249237

250238
def _fix_inout_args(
251239
func: Callable[..., Any],
252-
argtypes: Tuple[Type["_CDataType"], ...],
253-
paramflags: Tuple["hints.ParamFlagType", ...],
240+
argtypes: tuple[type["_CDataType"], ...],
241+
paramflags: tuple["hints.ParamFlagType", ...],
254242
) -> Callable[..., Any]:
255243
"""This function provides a workaround for a bug in `ctypes`.
256244
@@ -266,7 +254,7 @@ def _fix_inout_args(
266254
def call_with_inout(self, *args, **kw):
267255
args = list(args)
268256
# Indexed by order in the output
269-
outargs: Dict[int, "_CDataType"] = {}
257+
outargs: dict[int, "_CDataType"] = {}
270258
outnum = 0
271259
param_index = 0
272260
# Go through all expected arguments and match them to the provided arguments.
@@ -292,7 +280,7 @@ def call_with_inout(self, *args, **kw):
292280
name = info[1]
293281
# [in, out] parameters are passed as pointers,
294282
# this is the pointed-to type:
295-
atyp: Type["_CDataType"] = getattr(argtypes[i], "_type_")
283+
atyp: type["_CDataType"] = getattr(argtypes[i], "_type_")
296284

297285
# Get the actual parameter, either as positional or
298286
# keyword arg.
@@ -355,7 +343,7 @@ def call_with_inout(self, *args, **kw):
355343

356344
class PropertyMapping:
357345
def __init__(self):
358-
self._data: Dict[Tuple[str, _DocType, int], List[_PropFunc]] = {}
346+
self._data: dict[tuple[str, _DocType, int], list[_PropFunc]] = {}
359347

360348
def add_propget(
361349
self, name: str, doc: _DocType, nargs: int, func: Callable[..., Any]
@@ -372,7 +360,7 @@ def add_propputref(
372360
) -> None:
373361
self._data.setdefault((name, doc, nargs), [None, None, None])[2] = func
374362

375-
def __iter__(self) -> Iterator[Tuple[str, _DocType, int, _PropFunc, _PropFunc]]:
363+
def __iter__(self) -> Iterator[tuple[str, _DocType, int, _PropFunc, _PropFunc]]:
376364
for (name, doc, nargs), (fget, propput, propputref) in self._data.items():
377365
if propput is not None and propputref is not None:
378366
# Create a setter method that examines the argument type
@@ -414,7 +402,7 @@ def add(self, m: _MemberSpec, func: Callable[..., Any]) -> None:
414402

415403
# The following code assumes that the docstrings for
416404
# propget and propput are identical.
417-
def __iter__(self) -> Iterator[Tuple[str, _UnionT[property, "named_property"]]]:
405+
def __iter__(self) -> Iterator[tuple[str, _UnionT[property, "named_property"]]]:
418406
for name, doc, nargs, fget, fset in self._mapping:
419407
if nargs == 0:
420408
prop = property(fget, fset, None, doc)
@@ -425,49 +413,49 @@ def __iter__(self) -> Iterator[Tuple[str, _UnionT[property, "named_property"]]]:
425413
prop = named_property(f"{self._cls_name}.{name}", fget, fset, doc)
426414
yield (name, prop)
427415

428-
def to_propget_keys(self, m: _MemberSpec) -> Tuple[str, _DocType, int]:
416+
def to_propget_keys(self, m: _MemberSpec) -> tuple[str, _DocType, int]:
429417
raise NotImplementedError
430418

431-
def to_propput_keys(self, m: _MemberSpec) -> Tuple[str, _DocType, int]:
419+
def to_propput_keys(self, m: _MemberSpec) -> tuple[str, _DocType, int]:
432420
raise NotImplementedError
433421

434-
def to_propputref_keys(self, m: _MemberSpec) -> Tuple[str, _DocType, int]:
422+
def to_propputref_keys(self, m: _MemberSpec) -> tuple[str, _DocType, int]:
435423
raise NotImplementedError
436424

437425

438426
class ComPropertyGenerator(PropertyGenerator):
439427
# XXX Hm. What, when paramflags is None?
440428
# Or does have '0' values?
441429
# Seems we loose then, at least for properties...
442-
def to_propget_keys(self, m: _ComMemberSpec) -> Tuple[str, _DocType, int]:
430+
def to_propget_keys(self, m: _ComMemberSpec) -> tuple[str, _DocType, int]:
443431
assert m.name.startswith("_get_")
444432
assert m.paramflags is not None
445433
nargs = len([f for f in m.paramflags if f[0] & 7 in (0, 1)])
446434
# XXX or should we do this?
447435
# nargs = len([f for f in paramflags if (f[0] & 1) or (f[0] == 0)])
448436
return m.name[len("_get_") :], m.doc, nargs
449437

450-
def to_propput_keys(self, m: _ComMemberSpec) -> Tuple[str, _DocType, int]:
438+
def to_propput_keys(self, m: _ComMemberSpec) -> tuple[str, _DocType, int]:
451439
assert m.name.startswith("_set_")
452440
assert m.paramflags is not None
453441
nargs = len([f for f in m.paramflags if f[0] & 7 in (0, 1)]) - 1
454442
return m.name[len("_set_") :], m.doc, nargs
455443

456-
def to_propputref_keys(self, m: _ComMemberSpec) -> Tuple[str, _DocType, int]:
444+
def to_propputref_keys(self, m: _ComMemberSpec) -> tuple[str, _DocType, int]:
457445
assert m.name.startswith("_setref_")
458446
assert m.paramflags is not None
459447
nargs = len([f for f in m.paramflags if f[0] & 7 in (0, 1)]) - 1
460448
return m.name[len("_setref_") :], m.doc, nargs
461449

462450

463451
class DispPropertyGenerator(PropertyGenerator):
464-
def to_propget_keys(self, m: _DispMemberSpec) -> Tuple[str, _DocType, int]:
452+
def to_propget_keys(self, m: _DispMemberSpec) -> tuple[str, _DocType, int]:
465453
return m.name, None, len(m.argspec)
466454

467-
def to_propput_keys(self, m: _DispMemberSpec) -> Tuple[str, _DocType, int]:
455+
def to_propput_keys(self, m: _DispMemberSpec) -> tuple[str, _DocType, int]:
468456
return m.name, None, len(m.argspec) - 1
469457

470-
def to_propputref_keys(self, m: _DispMemberSpec) -> Tuple[str, _DocType, int]:
458+
def to_propputref_keys(self, m: _DispMemberSpec) -> tuple[str, _DocType, int]:
471459
return m.name, None, len(m.argspec) - 1
472460

473461

@@ -477,7 +465,7 @@ def __init__(self, cls_name: str, vtbl_offset: int, iid: "comtypes.GUID") -> Non
477465
self._iid = iid
478466
self._props = ComPropertyGenerator(cls_name)
479467
# sequence of (name: str, func: Callable, raw_func: Callable, is_prop: bool)
480-
self._mths: List[Tuple[str, Callable[..., Any], Callable[..., Any], bool]] = []
468+
self._mths: list[tuple[str, Callable[..., Any], Callable[..., Any], bool]] = []
481469
self._member_index = 0
482470

483471
def add(self, m: _ComMemberSpec) -> None:
@@ -520,7 +508,7 @@ class DispMemberGenerator:
520508
def __init__(self, cls_name: str) -> None:
521509
self._props = DispPropertyGenerator(cls_name)
522510
# sequence of (name: str, func_or_prop: Callable | property, is_prop: bool)
523-
self._items: List[Tuple[str, _UnionT[Callable[..., Any], property], bool]] = []
511+
self._items: list[tuple[str, _UnionT[Callable[..., Any], property], bool]] = []
524512

525513
def add(self, m: _DispMemberSpec) -> None:
526514
if m.what == "DISPPROPERTY": # DISPPROPERTY

comtypes/_post_coinit/_cominterface_meta_patcher.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
import types
22
from _ctypes import COMError
3-
from typing import Type
43

54
from comtypes import hresult, patcher
65

76
_all_slice = slice(None, None, None)
87

98

10-
def case_insensitive(p: Type) -> None:
9+
def case_insensitive(p: type) -> None:
1110
@patcher.Patch(p)
1211
class CaseInsensitive:
1312
# case insensitive attributes for COM methods and properties
@@ -32,7 +31,7 @@ def __setattr__(self, name, value):
3231
object.__setattr__(self, self.__map_case__.get(name.lower(), name), value)
3332

3433

35-
def reference_fix(pp: Type) -> None:
34+
def reference_fix(pp: type) -> None:
3635
@patcher.Patch(pp)
3736
class ReferenceFix:
3837
def __setitem__(self, index, value):
@@ -62,15 +61,15 @@ def __setitem__(self, index, value):
6261
CopyComPointer(value, self) # type: ignore
6362

6463

65-
def sized(itf: Type) -> None:
64+
def sized(itf: type) -> None:
6665
@patcher.Patch(itf)
6766
class _:
6867
def __len__(self):
6968
"Return the the 'self.Count' property."
7069
return self.Count
7170

7271

73-
def callable_and_subscriptable(itf: Type) -> None:
72+
def callable_and_subscriptable(itf: type) -> None:
7473
@patcher.Patch(itf)
7574
class _:
7675
# 'Item' is the 'default' value. Make it available by
@@ -123,7 +122,7 @@ def __setitem__(self, index, value):
123122
raise TypeError(msg)
124123

125124

126-
def iterator(itf: Type) -> None:
125+
def iterator(itf: type) -> None:
127126
@patcher.Patch(itf)
128127
class _:
129128
def __iter__(self):

comtypes/_post_coinit/activeobj.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from ctypes import HRESULT, POINTER, OleDLL, byref, c_ulong, c_void_p
22
from ctypes.wintypes import DWORD, LPVOID
3-
from typing import TYPE_CHECKING, Optional, Type, TypeVar, overload
3+
from typing import TYPE_CHECKING, Optional, TypeVar, overload
44
from typing import Union as _UnionT
55

66
from comtypes import GUID
@@ -34,9 +34,9 @@ def RevokeActiveObject(handle: int) -> None:
3434
@overload
3535
def GetActiveObject(clsid: GUID, interface: None = None) -> IUnknown: ...
3636
@overload
37-
def GetActiveObject(clsid: GUID, interface: Type[_T_IUnknown]) -> _T_IUnknown: ...
37+
def GetActiveObject(clsid: GUID, interface: type[_T_IUnknown]) -> _T_IUnknown: ...
3838
def GetActiveObject(
39-
clsid: GUID, interface: Optional[Type[IUnknown]] = None
39+
clsid: GUID, interface: Optional[type[IUnknown]] = None
4040
) -> IUnknown:
4141
"""Retrieves a pointer to a running object"""
4242
p = POINTER(IUnknown)()

0 commit comments

Comments
 (0)