From fbbc52d3945352b7280d1e5d59a1a59bfdb13b2d Mon Sep 17 00:00:00 2001 From: moi15moi <80980684+moi15moi@users.noreply.github.com> Date: Tue, 28 Jan 2025 16:38:00 -0500 Subject: [PATCH 1/2] Use PyUpgrade to upgrade to Python 3.8 syntax Run: pre-commit run pyupgrade --all-files With this .pre-commit-config.yaml file: ``` repos: - repo: https://github.com/asottile/pyupgrade rev: v3.19.1 hooks: - id: pyupgrade args: [--py38-plus] ``` --- comtypes/_comobject.py | 12 +++--- comtypes/_memberspec.py | 14 +++---- comtypes/_npsupport.py | 2 +- .../_cominterface_meta_patcher.py | 10 ++--- comtypes/_post_coinit/unknwn.py | 8 ++-- comtypes/_vtbl.py | 8 ++-- comtypes/automation.py | 2 +- comtypes/client/_code_cache.py | 2 +- comtypes/client/_constants.py | 2 +- comtypes/client/_events.py | 12 +++--- comtypes/client/_generate.py | 2 +- comtypes/client/dynamic.py | 6 +-- comtypes/client/lazybind.py | 6 +-- comtypes/errorinfo.py | 2 +- comtypes/hresult.py | 2 +- comtypes/messageloop.py | 2 +- comtypes/patcher.py | 4 +- comtypes/persist.py | 2 +- comtypes/safearray.py | 6 +-- comtypes/server/automation.py | 4 +- comtypes/server/connectionpoints.py | 6 +-- comtypes/server/inprocserver.py | 4 +- comtypes/server/localserver.py | 2 +- comtypes/server/register.py | 14 +++---- comtypes/test/__init__.py | 6 +-- comtypes/test/find_memleak.py | 2 +- comtypes/test/test_agilent.py | 2 +- comtypes/test/test_comserver.py | 4 +- comtypes/test/test_createwrappers.py | 2 +- comtypes/test/test_dispifc_records.py | 2 - comtypes/test/test_dispifc_safearrays.py | 2 - comtypes/test/test_dispinterface.py | 2 +- comtypes/test/test_excel.py | 6 +-- comtypes/test/test_getactiveobj.py | 2 +- comtypes/test/test_midl_safearray_create.py | 2 - comtypes/test/test_msscript.py | 2 +- comtypes/test/test_npsupport.py | 2 +- comtypes/test/test_recordinfo.py | 2 - comtypes/test/test_server.py | 14 +++---- comtypes/test/test_storage.py | 2 +- comtypes/test/test_stream.py | 4 +- comtypes/test/test_urlhistory.py | 2 +- comtypes/test/test_variant.py | 12 ++---- comtypes/test/test_word.py | 2 +- comtypes/tools/codegenerator/codegenerator.py | 2 +- comtypes/tools/codegenerator/comments.py | 2 +- comtypes/tools/codegenerator/heads.py | 10 ++--- comtypes/tools/codegenerator/helpers.py | 14 +++---- comtypes/tools/codegenerator/namespaces.py | 6 +-- comtypes/tools/codegenerator/packing.py | 6 +-- comtypes/tools/codegenerator/typeannotator.py | 4 +- comtypes/tools/tlbparser.py | 8 ++-- comtypes/tools/typedesc.py | 28 +++++++------- comtypes/tools/typedesc_base.py | 38 +++++++++---------- comtypes/viewobject.py | 2 +- docs/source/conf.py | 1 - setup.py | 2 +- test_pip_install.py | 4 +- 58 files changed, 157 insertions(+), 178 deletions(-) diff --git a/comtypes/_comobject.py b/comtypes/_comobject.py index 69b889f80..5bc7a307c 100644 --- a/comtypes/_comobject.py +++ b/comtypes/_comobject.py @@ -140,7 +140,7 @@ def _InterlockedDecrement(ob: c_long) -> int: _PostQuitMessage.restype = None -class LocalServer(object): +class LocalServer: _queue: Optional[queue.Queue] = None def run(self, classobjects: Sequence["hints.localserver.ClassFactory"]) -> None: @@ -182,7 +182,7 @@ def Unlock(self) -> None: _PostQuitMessage(0) -class InprocServer(object): +class InprocServer: def __init__(self) -> None: self.locks = c_long(0) @@ -203,7 +203,7 @@ def DllCanUnloadNow(self) -> int: _T_IUnknown = TypeVar("_T_IUnknown", bound=IUnknown) -class COMObject(object): +class COMObject: _com_interfaces_: ClassVar[List[Type[IUnknown]]] _outgoing_interfaces_: ClassVar[List[Type["hints.IDispatch"]]] _instances_: ClassVar[Dict["COMObject", None]] = {} @@ -214,7 +214,7 @@ class COMObject(object): _dispimpl_: Dict[Tuple[int, int], Callable[..., Any]] def __new__(cls, *args, **kw): - self = super(COMObject, cls).__new__(cls) + self = super().__new__(cls) if isinstance(self, c_void_p): # We build the VTables only for direct instances of # CoClass, not for POINTERs to CoClass. @@ -410,7 +410,7 @@ def IProvideClassInfo_GetClassInfo(self) -> ITypeInfo: try: self.__typelib except AttributeError: - raise WindowsError(hresult.E_NOTIMPL) + raise OSError(hresult.E_NOTIMPL) return self.__typelib.GetTypeInfoOfGuid(self._reg_clsid_) ################################################################ @@ -419,7 +419,7 @@ def IProvideClassInfo_GetClassInfo(self) -> ITypeInfo: def IProvideClassInfo2_GetGUID(self, dwGuidKind: int) -> GUID: # GUIDKIND_DEFAULT_SOURCE_DISP_IID = 1 if dwGuidKind != 1: - raise WindowsError(hresult.E_INVALIDARG) + raise OSError(hresult.E_INVALIDARG) return self._outgoing_interfaces_[0]._iid_ ################################################################ diff --git a/comtypes/_memberspec.py b/comtypes/_memberspec.py index 4132c6c2f..8e02105dd 100644 --- a/comtypes/_memberspec.py +++ b/comtypes/_memberspec.py @@ -126,7 +126,7 @@ class helpstring(str): "Specifies the helpstring for a COM method or property." -class defaultvalue(object): +class defaultvalue: "Specifies the default value for parameters marked optional." def __init__(self, value): @@ -313,7 +313,7 @@ def prepare_parameter(v): return call_with_inout -class PropertyMapping(object): +class PropertyMapping: def __init__(self): self._data: Dict[Tuple[str, _DocType, int], List[_PropFunc]] = {} @@ -353,7 +353,7 @@ def put_or_putref(self, *args): yield (name, doc, nargs, fget, fset) -class PropertyGenerator(object): +class PropertyGenerator: def __init__(self, cls_name: str) -> None: self._mapping = PropertyMapping() self._cls_name = cls_name @@ -431,7 +431,7 @@ def to_propputref_keys(self, m: _DispMemberSpec) -> Tuple[str, _DocType, int]: return m.name, None, len(m.argspec) - 1 -class ComMemberGenerator(object): +class ComMemberGenerator: def __init__(self, cls_name: str, vtbl_offset: int, iid: "comtypes.GUID") -> None: self._vtbl_offset = vtbl_offset self._iid = iid @@ -476,7 +476,7 @@ def properties(self): return iter(self._props) -class DispMemberGenerator(object): +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) @@ -572,7 +572,7 @@ def properties(self): # Should they be implemented in C for speed? -class bound_named_property(object): +class bound_named_property: def __init__(self, name, fget, fset, instance): self.name = name self.instance = instance @@ -613,7 +613,7 @@ def __iter__(self): raise TypeError(msg) -class named_property(object): +class named_property: def __init__(self, name, fget=None, fset=None, doc=None): self.name = name self.fget = fget diff --git a/comtypes/_npsupport.py b/comtypes/_npsupport.py index 760463ff8..2a638ca5a 100644 --- a/comtypes/_npsupport.py +++ b/comtypes/_npsupport.py @@ -124,7 +124,7 @@ def isndarray(self, value): if hasattr(value, "__array_interface__"): raise ValueError( ( - "Argument {0} appears to be a numpy.ndarray, but " + "Argument {} appears to be a numpy.ndarray, but " "comtypes numpy support has not been enabled. Please " "try calling comtypes.npsupport.enable_numpy_interop()" " before passing ndarrays as parameters." diff --git a/comtypes/_post_coinit/_cominterface_meta_patcher.py b/comtypes/_post_coinit/_cominterface_meta_patcher.py index 21da07a3e..d3b84ee00 100644 --- a/comtypes/_post_coinit/_cominterface_meta_patcher.py +++ b/comtypes/_post_coinit/_cominterface_meta_patcher.py @@ -10,7 +10,7 @@ def case_insensitive(p: Type) -> None: @patcher.Patch(p) - class CaseInsensitive(object): + class CaseInsensitive: # case insensitive attributes for COM methods and properties def __getattr__(self, name): """Implement case insensitive access to methods and properties""" @@ -35,7 +35,7 @@ def __setattr__(self, name, value): def reference_fix(pp: Type) -> None: @patcher.Patch(pp) - class ReferenceFix(object): + class ReferenceFix: def __setitem__(self, index, value): # We override the __setitem__ method of the # POINTER(POINTER(interface)) type, so that the COM @@ -65,7 +65,7 @@ def __setitem__(self, index, value): def sized(itf: Type) -> None: @patcher.Patch(itf) - class _(object): + class _: def __len__(self): "Return the the 'self.Count' property." return self.Count @@ -73,7 +73,7 @@ def __len__(self): def callable_and_subscriptable(itf: Type) -> None: @patcher.Patch(itf) - class _(object): + class _: # 'Item' is the 'default' value. Make it available by # calling the instance (Not sure this makes sense, but # win32com does this also). @@ -128,7 +128,7 @@ def __setitem__(self, index, value): def iterator(itf: Type) -> None: @patcher.Patch(itf) - class _(object): + class _: def __iter__(self): "Return an iterator over the _NewEnum collection." # This method returns a pointer to _some_ _NewEnum interface. diff --git a/comtypes/_post_coinit/unknwn.py b/comtypes/_post_coinit/unknwn.py index e1e29c2ed..139a5774d 100644 --- a/comtypes/_post_coinit/unknwn.py +++ b/comtypes/_post_coinit/unknwn.py @@ -32,7 +32,7 @@ def _shutdown( else: try: func() - except WindowsError: + except OSError: pass # Set the flag which means that calling obj.Release() is no longer # needed. @@ -284,13 +284,13 @@ def __eq__(self, other): return False # get the value property of the c_void_p baseclass, this is the pointer value return ( - super(_compointer_base, self).value == super(_compointer_base, other).value + super().value == super(_compointer_base, other).value ) def __hash__(self): """Return the hash value of the pointer.""" # hash the pointer values - return hash(super(_compointer_base, self).value) + return hash(super().value) # redefine the .value property; return the object itself. def __get_value(self): @@ -299,7 +299,7 @@ def __get_value(self): value = property(__get_value, doc="""Return self.""") def __repr__(self): - ptr = super(_compointer_base, self).value + ptr = super().value return f"<{self.__class__.__name__} ptr=0x{ptr or 0:x} at {id(self):x}>" # This fixes the problem when there are multiple python interface types diff --git a/comtypes/_vtbl.py b/comtypes/_vtbl.py index d313b6089..40a3656d6 100644 --- a/comtypes/_vtbl.py +++ b/comtypes/_vtbl.py @@ -96,7 +96,7 @@ def call_with_this(*args, **kw): except comtypes.ReturnHRESULT as err: (hr, text) = err.args return ReportError(text, iid=interface._iid_, clsid=clsid, hresult=hr) - except (COMError, WindowsError) as details: + except (COMError, OSError) as details: _error( "Exception in %s.%s implementation:", interface.__name__, @@ -204,7 +204,7 @@ def call_without_this(this, *args): msg = f"{source}: {descr}" hr = HRESULT_FROM_WIN32(hr) return ReportError(msg, iid=interface._iid_, clsid=clsid, hresult=hr) - except WindowsError as details: + except OSError as details: _error( "Exception in %s.%s implementation:", interface.__name__, @@ -231,11 +231,11 @@ def call_without_this(this, *args): return call_without_this -class _MethodFinder(object): +class _MethodFinder: def __init__(self, inst: "hints.COMObject") -> None: self.inst = inst # map lower case names to names with correct spelling. - self.names = dict([(n.lower(), n) for n in dir(inst)]) + self.names = {n.lower(): n for n in dir(inst)} def get_impl( self, diff --git a/comtypes/automation.py b/comtypes/automation.py index 7e6203f44..cdddb5659 100644 --- a/comtypes/automation.py +++ b/comtypes/automation.py @@ -609,7 +609,7 @@ def ChangeType(self, typecode): @comtypes.patcher.Patch(POINTER(VARIANT)) -class _(object): +class _: # Override the default .from_param classmethod of POINTER(VARIANT). # This allows to pass values which can be stored in VARIANTs as # function parameters declared as POINTER(VARIANT). See diff --git a/comtypes/client/_code_cache.py b/comtypes/client/_code_cache.py index a404cb683..2288634e9 100644 --- a/comtypes/client/_code_cache.py +++ b/comtypes/client/_code_cache.py @@ -115,7 +115,7 @@ def _create_comtypes_gen_package(): ofi = open(comtypes_init, "w") ofi.write("# comtypes.gen package, directory for generated files.\n") ofi.close() - except (OSError, IOError) as details: + except OSError as details: logger.info("Creating comtypes.gen package failed: %s", details) module = sys.modules["comtypes.gen"] = types.ModuleType("comtypes.gen") comtypes.gen = module diff --git a/comtypes/client/_constants.py b/comtypes/client/_constants.py index e090c2190..644606cca 100644 --- a/comtypes/client/_constants.py +++ b/comtypes/client/_constants.py @@ -43,7 +43,7 @@ def setdefault(self, key, default=None): raise TypeError -class Constants(object): +class Constants: """This class loads the type library from the supplied object, then exposes constants and enumerations in the type library as attributes. diff --git a/comtypes/client/_events.py b/comtypes/client/_events.py index 930473b73..fe386001e 100644 --- a/comtypes/client/_events.py +++ b/comtypes/client/_events.py @@ -57,7 +57,7 @@ class SECURITY_ATTRIBUTES(Structure): _CloseHandle.restype = BOOL -class _AdviseConnection(object): +class _AdviseConnection: def __init__(self, source, interface, receiver): self.cp = None self.cookie = None @@ -83,7 +83,7 @@ def __del__(self): try: if self.cookie is not None: self.cp.Unadvise(self.cookie) - except (comtypes.COMError, WindowsError): + except (comtypes.COMError, OSError): # Are we sure we want to ignore errors here? pass @@ -187,7 +187,7 @@ class _SinkMethodFinder(_MethodFinder): """ def __init__(self, inst, sink): - super(_SinkMethodFinder, self).__init__(inst) + super().__init__(inst) self.sink = sink def find_method(self, fq_name, mthname): @@ -207,7 +207,7 @@ def find_method(self, fq_name, mthname): def _find_method(self, fq_name, mthname): try: - return super(_SinkMethodFinder, self).find_method(fq_name, mthname) + return super().find_method(fq_name, mthname) except AttributeError: try: return getattr(self.sink, fq_name) @@ -261,7 +261,7 @@ def GetEvents(source, sink, interface=None): return _AdviseConnection(source, interface, rcv) -class EventDumper(object): +class EventDumper: """Universal sink for COM events.""" def __getattr__(self, name): @@ -342,7 +342,7 @@ def HandlerRoutine(dwCtrlType): handles, ctypes.byref(ctypes.c_ulong()), ) - except WindowsError as details: + except OSError as details: if details.winerror != RPC_S_CALLPENDING: # timeout expired raise else: diff --git a/comtypes/client/_generate.py b/comtypes/client/_generate.py index 381556931..5f61a5761 100644 --- a/comtypes/client/_generate.py +++ b/comtypes/client/_generate.py @@ -213,7 +213,7 @@ def _create_module(modulename: str, code: str) -> types.ModuleType: return _my_import(modulename) -class ModuleGenerator(object): +class ModuleGenerator: def __init__(self, tlib: typeinfo.ITypeLib, pathname: Optional[str]) -> None: self.wrapper_name = codegenerator.name_wrapper_module(tlib) self.friendly_name = codegenerator.name_friendly_module(tlib) diff --git a/comtypes/client/dynamic.py b/comtypes/client/dynamic.py index 8a219cd87..1783e57fd 100644 --- a/comtypes/client/dynamic.py +++ b/comtypes/client/dynamic.py @@ -28,7 +28,7 @@ def Dispatch(obj): if isinstance(obj, ctypes.POINTER(automation.IDispatch)): try: tinfo = obj.GetTypeInfo(0) - except (COMError, WindowsError): + except (COMError, OSError): return _Dispatch(obj) return lazybind.Dispatch(obj, tinfo) return obj @@ -60,7 +60,7 @@ def __setitem__(self, *args: Any) -> None: ) -class _Dispatch(object): +class _Dispatch: """Expose methods and properties via fully dynamic dispatch.""" _comobj: automation.IDispatch @@ -161,7 +161,7 @@ def __iter__(self) -> "_Collection": # ) -class _Collection(object): +class _Collection: def __init__(self, enum: automation.IEnumVARIANT): self.enum = enum diff --git a/comtypes/client/lazybind.py b/comtypes/client/lazybind.py index 97993882c..f68d09841 100644 --- a/comtypes/client/lazybind.py +++ b/comtypes/client/lazybind.py @@ -13,7 +13,7 @@ from comtypes.typeinfo import FUNC_PUREVIRTUAL, FUNC_DISPATCH -class FuncDesc(object): +class FuncDesc: """Stores important FUNCDESC properties by copying them from a real FUNCDESC instance. """ @@ -29,7 +29,7 @@ def __init__(self, **kw): _all_slice = slice(None, None, None) -class NamedProperty(object): +class NamedProperty: def __init__(self, disp, get, put, putref): self.get = get self.put = put @@ -84,7 +84,7 @@ def __iter__(self): # objects do not (could be added, would probably be expensive) -class Dispatch(object): +class Dispatch: """Dynamic dispatch for an object the exposes type information. Binding at runtime is done via ITypeComp::Bind calls. """ diff --git a/comtypes/errorinfo.py b/comtypes/errorinfo.py index 22cab0575..6687ef034 100644 --- a/comtypes/errorinfo.py +++ b/comtypes/errorinfo.py @@ -95,7 +95,7 @@ def ReportError( clsid = GUID(clsid) try: progid = clsid.as_progid() - except WindowsError: + except OSError: pass else: ei.SetSource( diff --git a/comtypes/hresult.py b/comtypes/hresult.py index cb527910a..2424a5160 100644 --- a/comtypes/hresult.py +++ b/comtypes/hresult.py @@ -60,7 +60,7 @@ def MAKE_HRESULT(sev, fac, code): # A hresult is SIGNED in comtypes from ctypes import c_long - return c_long((sev << 31 | fac << 16 | code)).value + return c_long(sev << 31 | fac << 16 | code).value SEVERITY_ERROR = 1 diff --git a/comtypes/messageloop.py b/comtypes/messageloop.py index e08a16b49..cbff26363 100644 --- a/comtypes/messageloop.py +++ b/comtypes/messageloop.py @@ -15,7 +15,7 @@ DispatchMessage = _user32.DispatchMessageA -class _MessageLoop(object): +class _MessageLoop: def __init__(self): self._filters = [] diff --git a/comtypes/patcher.py b/comtypes/patcher.py index 5e5bf4887..73bef4058 100644 --- a/comtypes/patcher.py +++ b/comtypes/patcher.py @@ -1,4 +1,4 @@ -class Patch(object): +class Patch: """ Implements a class decorator suitable for patching an existing class with a new namespace. @@ -69,7 +69,7 @@ def no_replace(f): return f -class ReferenceEmptyClass(object): +class ReferenceEmptyClass: """ This empty class will serve as a reference for attributes present on any class. diff --git a/comtypes/persist.py b/comtypes/persist.py index 4fa7c9d65..017ac1740 100644 --- a/comtypes/persist.py +++ b/comtypes/persist.py @@ -268,7 +268,7 @@ class DictPropertyBag(COMObject): _com_interfaces_ = [IPropertyBag] def __init__(self, **kw): - super(DictPropertyBag, self).__init__() + super().__init__() self.values = kw def Read(self, this, name, pVar, errorlog): diff --git a/comtypes/safearray.py b/comtypes/safearray.py index 6330d5526..dbe14b852 100644 --- a/comtypes/safearray.py +++ b/comtypes/safearray.py @@ -15,7 +15,7 @@ _safearray_type_cache = {} -class _SafeArrayAsNdArrayContextManager(object): +class _SafeArrayAsNdArrayContextManager: """Context manager allowing safe arrays to be extracted as ndarrays. This is thread-safe. @@ -108,7 +108,7 @@ def _make_safearray_type(itemtype): raise TypeError(itemtype) @Patch(POINTER(sa_type)) - class _(object): + class _: # Should explain the ideas how SAFEARRAY is used in comtypes _itemtype_ = itemtype # a ctypes type _vartype_ = vartype # a VARTYPE value: VT_... @@ -376,7 +376,7 @@ def _get_row(self, dim, indices, lowerbounds, upperbounds): return tuple(result) # for compatibility with pywin32. @Patch(POINTER(POINTER(sa_type))) - class __(object): + class __: @classmethod def from_param(cls, value): if isinstance(value, cls._type_): diff --git a/comtypes/server/automation.py b/comtypes/server/automation.py index e38c73a2e..39385b3cf 100644 --- a/comtypes/server/automation.py +++ b/comtypes/server/automation.py @@ -23,7 +23,7 @@ def __init__(self, items): items # keep, so that we can restore our iterator (in Reset, and Clone). ) self.seq = iter(self.items) - super(VARIANTEnumerator, self).__init__() + super().__init__() def Next(self, this, celt, rgVar, pCeltFetched): if not rgVar: @@ -76,7 +76,7 @@ class COMCollection(COMObject): def __init__(self, itemtype, collection): self.collection = collection self.itemtype = itemtype - super(COMCollection, self).__init__() + super().__init__() def _get_Item(self, this, pathname, pitem): if not pitem: diff --git a/comtypes/server/connectionpoints.py b/comtypes/server/connectionpoints.py index 004672e88..556732c04 100644 --- a/comtypes/server/connectionpoints.py +++ b/comtypes/server/connectionpoints.py @@ -18,7 +18,7 @@ class ConnectionPointImpl(COMObject): _com_interfaces_ = [IConnectionPoint] def __init__(self, sink_interface, sink_typeinfo): - super(ConnectionPointImpl, self).__init__() + super().__init__() self._connections = {} self._cookie = 0 self._sink_interface = sink_interface @@ -118,7 +118,7 @@ def _call_sinks(self, name, *args, **kw): return results -class ConnectableObjectMixin(object): +class ConnectableObjectMixin: """Mixin which implements IConnectionPointContainer. Call Fire_Event(interface, methodname, *args, **kw) to fire an @@ -127,7 +127,7 @@ class ConnectableObjectMixin(object): """ def __init__(self): - super(ConnectableObjectMixin, self).__init__() + super().__init__() self.__connections = {} tlib = LoadRegTypeLib(*self._reg_typelib_) diff --git a/comtypes/server/inprocserver.py b/comtypes/server/inprocserver.py index 33f7e8c2d..349447ac5 100644 --- a/comtypes/server/inprocserver.py +++ b/comtypes/server/inprocserver.py @@ -18,7 +18,7 @@ class ClassFactory(COMObject): _com_interfaces_ = [IClassFactory] def __init__(self, cls: Type[COMObject]) -> None: - super(ClassFactory, self).__init__() + super().__init__() self._cls = cls def IClassFactory_CreateInstance( @@ -87,7 +87,7 @@ def _setup_logging(clsid: GUID) -> None: try: hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\Logging" % clsid) - except WindowsError: + except OSError: return from comtypes.logutil import NTDebugHandler diff --git a/comtypes/server/localserver.py b/comtypes/server/localserver.py index 234b177ba..69d558737 100644 --- a/comtypes/server/localserver.py +++ b/comtypes/server/localserver.py @@ -52,7 +52,7 @@ class ClassFactory(comtypes.COMObject): regcls: int = REGCLS_MULTIPLEUSE def __init__(self, cls: Type[comtypes.COMObject], *args, **kw) -> None: - super(ClassFactory, self).__init__() + super().__init__() self._cls = cls self._register_class() self._args = args diff --git a/comtypes/server/register.py b/comtypes/server/register.py index 39ad2df51..94ff14c5d 100644 --- a/comtypes/server/register.py +++ b/comtypes/server/register.py @@ -105,7 +105,7 @@ def _delete_key(hkey: int, subkey: str, *, force: bool) -> None: else: _debug("DeleteKey %s\\%s", _explain(hkey), subkey) winreg.DeleteKey(hkey, subkey) - except WindowsError as detail: + except OSError as detail: if get_winerror(detail) != 2: raise @@ -113,7 +113,7 @@ def _delete_key(hkey: int, subkey: str, *, force: bool) -> None: _Entry = Tuple[int, str, str, str] -class Registrar(object): +class Registrar: """COM class registration. The COM class can override what this does by implementing @@ -139,10 +139,10 @@ def nodebug(self, cls: Type) -> None: """Delete logging entries from the registry.""" clsid = cls._reg_clsid_ try: - _debug('DeleteKey( %s\\CLSID\\%s\\Logging"' % (_explain(HKCR), clsid)) + _debug('DeleteKey( {}\\CLSID\\{}\\Logging"'.format(_explain(HKCR), clsid)) hkey = winreg.OpenKey(HKCR, rf"CLSID\{clsid}") winreg.DeleteKey(hkey, "Logging") - except WindowsError as detail: + except OSError as detail: if get_winerror(detail) != 2: raise @@ -151,7 +151,7 @@ def debug(self, cls: Type, levels: List[str], format: Optional[str]) -> None: # handlers # format clsid = cls._reg_clsid_ - _debug('CreateKey( %s\\CLSID\\%s\\Logging"' % (_explain(HKCR), clsid)) + _debug('CreateKey( {}\\CLSID\\{}\\Logging"'.format(_explain(HKCR), clsid)) hkey = winreg.CreateKey(HKCR, rf"CLSID\{clsid}\Logging") for item in levels: name, value = item.split("=") @@ -166,7 +166,7 @@ def debug(self, cls: Type, levels: List[str], format: Optional[str]) -> None: _debug("DeleteValue(format)") try: winreg.DeleteValue(hkey, "format") - except WindowsError as detail: + except OSError as detail: if get_winerror(detail) != 2: raise @@ -231,7 +231,7 @@ def _unregister(self, cls: Type, force: bool = False) -> None: try: _debug("UnRegisterTypeLib(%s, %s, %s)", *tlib) UnRegisterTypeLib(*tlib) - except WindowsError as detail: + except OSError as detail: if not get_winerror(detail) in ( TYPE_E_REGISTRYACCESS, TYPE_E_CANTLOADLIBRARY, diff --git a/comtypes/test/__init__.py b/comtypes/test/__init__.py index 8b168e7af..f884fb49b 100644 --- a/comtypes/test/__init__.py +++ b/comtypes/test/__init__.py @@ -81,7 +81,7 @@ def find_package_modules(package, mask): path = package.__path__[0] for fnm in os.listdir(path): if fnmatch.fnmatchcase(fnm, mask): - yield "%s.%s" % (package.__name__, os.path.splitext(fnm)[0]) + yield "{}.{}".format(package.__name__, os.path.splitext(fnm)[0]) def get_tests(package, mask, verbosity): @@ -134,7 +134,7 @@ def cleanup(): ctypes._win_functype_cache = wfc.copy() gc.collect() - test = unittest.makeSuite(testcase) + test = unittest.defaultTestLoader.loadTestsFromTestCase(testcase) for i in range(5): rc = sys.gettotalrefcount() runner.run(test) @@ -204,7 +204,7 @@ def run_tests(package, mask, verbosity, search_leaks): skipped, testcases = get_tests(package, mask, verbosity) runner = TestRunner(verbosity=verbosity) - suites = [unittest.makeSuite(o) for o in testcases] + suites = [unittest.defaultTestLoader.loadTestsFromTestCase(o) for o in testcases] suite = unittest.TestSuite(suites) result = runner.run(suite, skipped) diff --git a/comtypes/test/find_memleak.py b/comtypes/test/find_memleak.py index 88cf7f07c..c85dd3e57 100644 --- a/comtypes/test/find_memleak.py +++ b/comtypes/test/find_memleak.py @@ -39,7 +39,7 @@ def dump(self): POINTER(PROCESS_MEMORY_COUNTERS), DWORD, ) -except WindowsError: +except OSError: # cannot search for memory leaks on Windows CE def find_memleak(func, loops=None): return 0 diff --git a/comtypes/test/test_agilent.py b/comtypes/test/test_agilent.py index c3a20283c..3bb3dfc6c 100644 --- a/comtypes/test/test_agilent.py +++ b/comtypes/test/test_agilent.py @@ -11,7 +11,7 @@ try: GUID.from_progid("Agilent546XX.Agilent546XX") -except WindowsError: +except OSError: pass else: diff --git a/comtypes/test/test_comserver.py b/comtypes/test/test_comserver.py index 3c4994411..48dc6026d 100644 --- a/comtypes/test/test_comserver.py +++ b/comtypes/test/test_comserver.py @@ -22,7 +22,7 @@ def setUpModule(): try: register(comtypes.test.TestComServer.TestComServer) - except WindowsError as e: + except OSError as e: if e.winerror != 5: # [Error 5] Access is denied raise e raise unittest.SkipTest( @@ -35,7 +35,7 @@ def tearDownModule(): unregister(comtypes.test.TestComServer.TestComServer) -class BaseServerTest(object): +class BaseServerTest: def create_object(self) -> Any: ... def _find_memleak(self, func): diff --git a/comtypes/test/test_createwrappers.py b/comtypes/test/test_createwrappers.py index 9143f478a..d8bd42a06 100644 --- a/comtypes/test/test_createwrappers.py +++ b/comtypes/test/test_createwrappers.py @@ -51,7 +51,7 @@ def add_test(fname): def test(self): try: comtypes.typeinfo.LoadTypeLibEx(fname) - except WindowsError: + except OSError: return comtypes.client.GetModule(fname) diff --git a/comtypes/test/test_dispifc_records.py b/comtypes/test/test_dispifc_records.py index 7666d6122..d57666e68 100644 --- a/comtypes/test/test_dispifc_records.py +++ b/comtypes/test/test_dispifc_records.py @@ -1,5 +1,3 @@ -# coding: utf-8 - import unittest from comtypes import CLSCTX_LOCAL_SERVER diff --git a/comtypes/test/test_dispifc_safearrays.py b/comtypes/test/test_dispifc_safearrays.py index 08694d12a..59cf5c994 100644 --- a/comtypes/test/test_dispifc_safearrays.py +++ b/comtypes/test/test_dispifc_safearrays.py @@ -1,5 +1,3 @@ -# coding: utf-8 - from ctypes import byref, c_double, pointer import unittest diff --git a/comtypes/test/test_dispinterface.py b/comtypes/test/test_dispinterface.py index bf2a9747a..3e896c2fa 100644 --- a/comtypes/test/test_dispinterface.py +++ b/comtypes/test/test_dispinterface.py @@ -16,7 +16,7 @@ def setUpModule(): try: register(comtypes.test.TestDispServer.TestDispServer) - except WindowsError as e: + except OSError as e: if e.winerror != 5: # [Error 5] Access is denied raise e raise unittest.SkipTest( diff --git a/comtypes/test/test_excel.py b/comtypes/test/test_excel.py index b982cd52b..2d5af589a 100644 --- a/comtypes/test/test_excel.py +++ b/comtypes/test/test_excel.py @@ -1,5 +1,3 @@ -# -*- coding: latin-1 -*- - import datetime import sys import unittest @@ -26,7 +24,7 @@ IMPORT_FAILED = True -class BaseBindTest(object): +class BaseBindTest: # `dynamic = True/False` must be defined in subclasses! dynamic: ClassVar[bool] @@ -122,7 +120,7 @@ def test(self): sh.Range[sh.Cells.Item[4, 1], sh.Cells.Item[6, 3]].Select() -PY_VER = "Python {0}.{1}.{2}".format(*sys.version_info[:3]) +PY_VER = "Python {}.{}.{}".format(*sys.version_info[:3]) @unittest.skipIf(IMPORT_FAILED, "This depends on Excel.") diff --git a/comtypes/test/test_getactiveobj.py b/comtypes/test/test_getactiveobj.py index 82fa415fa..b7ff799d1 100644 --- a/comtypes/test/test_getactiveobj.py +++ b/comtypes/test/test_getactiveobj.py @@ -29,7 +29,7 @@ class Test_Word(unittest.TestCase): def setUp(self): try: comtypes.client.GetActiveObject("Word.Application") - except WindowsError: + except OSError: pass else: # seems word is running, we cannot test this. diff --git a/comtypes/test/test_midl_safearray_create.py b/comtypes/test/test_midl_safearray_create.py index 594e0a57c..8c3ff8ee4 100644 --- a/comtypes/test/test_midl_safearray_create.py +++ b/comtypes/test/test_midl_safearray_create.py @@ -1,5 +1,3 @@ -# coding: utf-8 - from ctypes import c_int, pointer, HRESULT, POINTER import unittest diff --git a/comtypes/test/test_msscript.py b/comtypes/test/test_msscript.py index 84568abf0..8c0c9d5cc 100644 --- a/comtypes/test/test_msscript.py +++ b/comtypes/test/test_msscript.py @@ -10,7 +10,7 @@ try: GUID.from_progid("MSScriptControl.ScriptControl") CreateObject("MSScriptControl.ScriptControl") -except WindowsError: +except OSError: # doesn't exist on Windows CE or in 64-bit. pass else: diff --git a/comtypes/test/test_npsupport.py b/comtypes/test/test_npsupport.py index 6f8c94aff..8ae23f5cd 100644 --- a/comtypes/test/test_npsupport.py +++ b/comtypes/test/test_npsupport.py @@ -70,7 +70,7 @@ def call_disabled(self): from comtypes import npsupport if npsupport.enabled: - raise EnvironmentError( + raise OSError( "Expected numpy interop not to be enabled but it is." ) with self.assertRaises(disabled_error): diff --git a/comtypes/test/test_recordinfo.py b/comtypes/test/test_recordinfo.py index 4f47fa92c..6484bdfbb 100644 --- a/comtypes/test/test_recordinfo.py +++ b/comtypes/test/test_recordinfo.py @@ -1,5 +1,3 @@ -# coding: utf-8 - import unittest from comtypes import typeinfo diff --git a/comtypes/test/test_server.py b/comtypes/test/test_server.py index f6c28eb3f..56f2952eb 100644 --- a/comtypes/test/test_server.py +++ b/comtypes/test/test_server.py @@ -8,7 +8,7 @@ raise unittest.SkipTest("This test module cannot run as-is. Investigate why") -class TypeLib(object): +class TypeLib: """This class collects IDL code fragments and eventually writes them into a .IDL file. The compile() method compiles the IDL file into a typelibrary and registers it. A function is also @@ -46,7 +46,7 @@ def compile(self): curdir = os.path.dirname(__file__) idl_path = os.path.join(curdir, "mylib.idl") tlb_path = os.path.join(curdir, "mylib.tlb") - if not os.path.isfile(idl_path) or open(idl_path, "r").read() != code: + if not os.path.isfile(idl_path) or open(idl_path).read() != code: open(idl_path, "w").write(code) os.system( r'call "%%VS71COMNTOOLS%%vsvars32.bat" && ' @@ -64,7 +64,7 @@ def compile(self): return tlb_path -class Interface(object): +class Interface: def __init__(self, header): self.header = header self.code = "" @@ -257,7 +257,7 @@ def DoSomething(self): def test_events(self): p = wrap(self.create()) - class Handler(object): + class Handler: called = 0 def OnSomething(self, this): @@ -269,7 +269,7 @@ def OnSomething(self, this): p.DoSomething() self.assertEqual(handler.called, 1) - class Handler(object): + class Handler: called = 0 def IMyEventInterface_OnSomething(self): @@ -292,7 +292,7 @@ def DoSomethingElse(self): def test_DoSomethingElse(self): p = wrap(self.create()) - class Handler(object): + class Handler: called = 0 def OnSomethingElse(self): @@ -305,7 +305,7 @@ def OnSomethingElse(self): p.DoSomethingElse() self.assertEqual(handler.called, 1) - class Handler(object): + class Handler: called = 0 def OnSomethingElse(self, this, presult): diff --git a/comtypes/test/test_storage.py b/comtypes/test/test_storage.py index a8717c2ca..18d22245c 100644 --- a/comtypes/test/test_storage.py +++ b/comtypes/test/test_storage.py @@ -52,7 +52,7 @@ def test_CreateStream(self): filepath = Path(storage.Stat(STATFLAG_DEFAULT).pwcsName) self.assertTrue(filepath.exists()) stream = storage.CreateStream("example", self.CREATE_STM_FLAG, 0, 0) - test_data = "Some data".encode("utf-8") + test_data = b"Some data" pv = (c_ubyte * len(test_data)).from_buffer(bytearray(test_data)) stream.RemoteWrite(pv, len(test_data)) stream.Commit(STGC_DEFAULT) diff --git a/comtypes/test/test_stream.py b/comtypes/test/test_stream.py index a270aee26..2efe1e39c 100644 --- a/comtypes/test/test_stream.py +++ b/comtypes/test/test_stream.py @@ -36,7 +36,7 @@ def _create_stream() -> IStream: class Test_RemoteWrite(ut.TestCase): def test_RemoteWrite(self): stream = _create_stream() - test_data = "Some data".encode("utf-8") + test_data = b"Some data" pv = (c_ubyte * len(test_data)).from_buffer(bytearray(test_data)) written = stream.RemoteWrite(pv, len(test_data)) @@ -48,7 +48,7 @@ def test_RemoteWrite(self): class Test_RemoteRead(ut.TestCase): def test_RemoteRead(self): stream = _create_stream() - test_data = "Some data".encode("utf-8") + test_data = b"Some data" pv = (c_ubyte * len(test_data)).from_buffer(bytearray(test_data)) stream.RemoteWrite(pv, len(test_data)) diff --git a/comtypes/test/test_urlhistory.py b/comtypes/test/test_urlhistory.py index 60ca3bbab..5511da5ff 100644 --- a/comtypes/test/test_urlhistory.py +++ b/comtypes/test/test_urlhistory.py @@ -16,7 +16,7 @@ # generated code directly is to monkey-patch the # _STATURL.__ctypes_from_outparam__ method like this. @Patch(urlhistLib._STATURL) -class _(object): +class _: def __ctypes_from_outparam__(self): from comtypes.util import cast_field diff --git a/comtypes/test/test_variant.py b/comtypes/test/test_variant.py index 88db242e3..2a21749ff 100644 --- a/comtypes/test/test_variant.py +++ b/comtypes/test/test_variant.py @@ -114,10 +114,7 @@ def test_dispparams(self): self.assertEqual(result, values) def test_pythonobjects(self): - if sys.version_info >= (3, 0): - objects = [None, 42, 3.14, True, False, "abc", "abc", 7] - else: - objects = [None, 42, 3.14, True, False, "abc", "abc", 7] + objects = [None, 42, 3.14, True, False, "abc", "abc", 7] for x in objects: v = VARIANT(x) self.assertEqual(x, v.value) @@ -302,13 +299,10 @@ def check_perf(rep=20000): by_var = byref(variable) ptr_var = pointer(variable) - if sys.version_info >= (3, 0): - import pickle - else: - import cPickle as pickle + import pickle try: previous = pickle.load(open("result.pickle", "rb")) - except IOError: + except OSError: previous = {} results = {} diff --git a/comtypes/test/test_word.py b/comtypes/test/test_word.py index d1e6370ab..693fca412 100644 --- a/comtypes/test/test_word.py +++ b/comtypes/test/test_word.py @@ -26,7 +26,7 @@ ################################################################ -class _Sink(object): +class _Sink: def __init__(self): self.events = [] diff --git a/comtypes/tools/codegenerator/codegenerator.py b/comtypes/tools/codegenerator/codegenerator.py index 7c1757414..4b196ceac 100644 --- a/comtypes/tools/codegenerator/codegenerator.py +++ b/comtypes/tools/codegenerator/codegenerator.py @@ -42,7 +42,7 @@ ] -class CodeGenerator(object): +class CodeGenerator: def __init__(self, known_symbols=None, known_interfaces=None) -> None: self.stream = io.StringIO() self.imports = namespaces.ImportedNamespaces() diff --git a/comtypes/tools/codegenerator/comments.py b/comtypes/tools/codegenerator/comments.py index 0f6f4f86d..57f5b4a31 100644 --- a/comtypes/tools/codegenerator/comments.py +++ b/comtypes/tools/codegenerator/comments.py @@ -3,7 +3,7 @@ from comtypes.tools import typedesc -class ComInterfaceBodyImplCommentWriter(object): +class ComInterfaceBodyImplCommentWriter: def __init__(self, stream: io.StringIO): self.stream = stream diff --git a/comtypes/tools/codegenerator/heads.py b/comtypes/tools/codegenerator/heads.py index 3f1ed8b26..250844bff 100644 --- a/comtypes/tools/codegenerator/heads.py +++ b/comtypes/tools/codegenerator/heads.py @@ -13,7 +13,7 @@ def _to_docstring(orig: str, depth: int = 1) -> str: return f'{indent}"""{repled}"""' -class StructureHeadWriter(object): +class StructureHeadWriter: def __init__(self, stream: io.StringIO) -> None: self.stream = stream @@ -67,7 +67,7 @@ def write(self, head: typedesc.StructureHead, basenames: Sequence[str]) -> None: print(" pass", file=self.stream) -class LibraryHeadWriter(object): +class LibraryHeadWriter: def __init__(self, stream: io.StringIO) -> None: self.stream = stream @@ -93,7 +93,7 @@ def write(self, lib: typedesc.TypeLib) -> None: ) -class CoClassHeadWriter(object): +class CoClassHeadWriter: def __init__(self, stream: io.StringIO, filename: Optional[str]) -> None: self.stream = stream self.filename = filename @@ -117,7 +117,7 @@ def write(self, coclass: typedesc.CoClass) -> None: ) -class ComInterfaceHeadWriter(object): +class ComInterfaceHeadWriter: def __init__(self, stream: io.StringIO) -> None: self.stream = stream @@ -172,7 +172,7 @@ def write(self, head: typedesc.ComInterfaceHead, basename: str) -> None: print(annotations, file=self.stream) -class DispInterfaceHeadWriter(object): +class DispInterfaceHeadWriter: def __init__(self, stream: io.StringIO) -> None: self.stream = stream diff --git a/comtypes/tools/codegenerator/helpers.py b/comtypes/tools/codegenerator/helpers.py index 1509cf616..2cd8c2588 100644 --- a/comtypes/tools/codegenerator/helpers.py +++ b/comtypes/tools/codegenerator/helpers.py @@ -6,7 +6,7 @@ from comtypes.tools.codegenerator.modulenamer import name_wrapper_module -class lcid(object): +class lcid: def __repr__(self): return "_lcid" @@ -14,7 +14,7 @@ def __repr__(self): lcid = lcid() -class dispid(object): +class dispid: def __init__(self, memid): self.memid = memid @@ -22,7 +22,7 @@ def __repr__(self): return f"dispid({self.memid})" -class helpstring(object): +class helpstring: def __init__(self, text): self.text = text @@ -100,7 +100,7 @@ def _to_arg_definition( return code -class ComMethodGenerator(object): +class ComMethodGenerator: def __init__(self, m: typedesc.ComMethod, isdual: bool) -> None: self._m = m self._isdual = isdual @@ -208,7 +208,7 @@ def _iter_args(self) -> Iterator[Tuple[str, str, List[str], _DefValType]]: yield (type_name, arg_name, idlflags, default) -class DispMethodGenerator(object): +class DispMethodGenerator: def __init__(self, m: typedesc.DispMethod) -> None: self._m = m self.data: List[str] = [] @@ -262,7 +262,7 @@ def _iter_args(self) -> Iterator[Tuple[str, str, List[str], _DefValType]]: yield (type_name, arg_name, idlflags, default) -class DispPropertyGenerator(object): +class DispPropertyGenerator: def __init__(self, m: typedesc.DispProperty) -> None: self._m = m self._to_type_name = TypeNamer() @@ -290,7 +290,7 @@ def _get_common_elms(self) -> Tuple[List[_IdlFlagType], str, str]: return (idlflags, type_name, self._m.name) -class TypeNamer(object): +class TypeNamer: def __call__(self, t: Any) -> str: # Return a string, containing an expression which can be used # to refer to the type. Assumes the 'from ctypes import *' diff --git a/comtypes/tools/codegenerator/namespaces.py b/comtypes/tools/codegenerator/namespaces.py index 06fe82b03..3ad901f24 100644 --- a/comtypes/tools/codegenerator/namespaces.py +++ b/comtypes/tools/codegenerator/namespaces.py @@ -7,7 +7,7 @@ import warnings -class ImportedNamespaces(object): +class ImportedNamespaces: def __init__(self) -> None: self.data: Dict[str, Optional[str]] = {} @@ -124,7 +124,7 @@ def getvalue(self) -> str: return "\n".join(lines) -class DeclaredNamespaces(object): +class DeclaredNamespaces: def __init__(self) -> None: self.data: Dict[Tuple[str, str], Optional[str]] = {} @@ -160,7 +160,7 @@ def getvalue(self) -> str: return "\n".join(lines) -class EnumerationNamespaces(object): +class EnumerationNamespaces: def __init__(self) -> None: self.data: Dict[str, List[Tuple[str, int]]] = {} diff --git a/comtypes/tools/codegenerator/packing.py b/comtypes/tools/codegenerator/packing.py index 68c18fea1..adc0c1bf1 100644 --- a/comtypes/tools/codegenerator/packing.py +++ b/comtypes/tools/codegenerator/packing.py @@ -63,12 +63,10 @@ class PackingError(Exception): # XXX These should be filtered out in gccxmlparser. -dont_assert_size = set( - [ +dont_assert_size = { "__si_class_type_info_pseudo", "__class_type_info_pseudo", - ] -) +} def storage(t): diff --git a/comtypes/tools/codegenerator/typeannotator.py b/comtypes/tools/codegenerator/typeannotator.py index efd617fc6..c168c6c5c 100644 --- a/comtypes/tools/codegenerator/typeannotator.py +++ b/comtypes/tools/codegenerator/typeannotator.py @@ -266,7 +266,7 @@ def to_method_annotator(self, m: typedesc.ComMethod) -> ComMethodAnnotator: return ComMethodAnnotator(m) -class ComInterfaceMembersAnnotator(object): +class ComInterfaceMembersAnnotator: def __init__(self, itf: typedesc.ComInterface): self.itf = itf @@ -306,7 +306,7 @@ def to_method_annotator(self, m: typedesc.DispMethod) -> DispMethodAnnotator: return DispMethodAnnotator(m) -class DispInterfaceMembersAnnotator(object): +class DispInterfaceMembersAnnotator: def __init__(self, itf: typedesc.DispInterface): self.itf = itf diff --git a/comtypes/tools/tlbparser.py b/comtypes/tools/tlbparser.py index b689a703a..3f5e5fd59 100644 --- a/comtypes/tools/tlbparser.py +++ b/comtypes/tools/tlbparser.py @@ -107,7 +107,7 @@ def midlSAFEARRAY(typ): ################################################################ -class Parser(object): +class Parser: tlib: typeinfo.ITypeLib items: Dict[str, Any] @@ -357,8 +357,7 @@ def ParseDispatch( # CLF: 12/14/2012 Do this in a way that does not exclude other methods. # I have encountered typlibs where only "QueryInterface", "AddRef" # and "Release" are to be skipped. - ignored_names = set( - [ + ignored_names = { "QueryInterface", "AddRef", "Release", @@ -366,8 +365,7 @@ def ParseDispatch( "GetTypeInfo", "GetIDsOfNames", "Invoke", - ] - ) + } for i in range(ta.cFuncs): fd = tinfo.GetFuncDesc(i) diff --git a/comtypes/tools/typedesc.py b/comtypes/tools/typedesc.py index 8a6b9f426..d52cce0ed 100644 --- a/comtypes/tools/typedesc.py +++ b/comtypes/tools/typedesc.py @@ -9,7 +9,7 @@ from comtypes.tools.typedesc_base import * -class TypeLib(object): +class TypeLib: def __init__( self, name: str, guid: str, major: int, minor: int, doc: Optional[str] = None ) -> None: @@ -23,7 +23,7 @@ def __repr__(self): return f"" -class Constant(object): +class Constant: def __init__( self, name: str, @@ -37,7 +37,7 @@ def __init__( self.doc = doc -class External(object): +class External: def __init__( self, tlib: ITypeLib, @@ -60,13 +60,13 @@ def get_head(self) -> "External": return self -class SAFEARRAYType(object): +class SAFEARRAYType: def __init__(self, typ: Any) -> None: self.typ = typ self.align = self.size = ctypes.sizeof(ctypes.c_void_p) * 8 -class ComMethod(object): +class ComMethod: # custom COM method, parsed from typelib def __init__( self, @@ -91,7 +91,7 @@ def add_argument( self.arguments.append((typ, name, idlflags, default)) -class DispMethod(object): +class DispMethod: # dispatchable COM method, parsed from typelib def __init__( self, @@ -116,7 +116,7 @@ def add_argument( self.arguments.append((typ, name, idlflags, default)) -class DispProperty(object): +class DispProperty: # dispatchable COM property, parsed from typelib def __init__( self, dispid: int, name: str, typ: Any, idlflags: List[str], doc: Optional[Any] @@ -128,17 +128,17 @@ def __init__( self.doc = doc -class DispInterfaceHead(object): +class DispInterfaceHead: def __init__(self, itf: "DispInterface") -> None: self.itf = itf -class DispInterfaceBody(object): +class DispInterfaceBody: def __init__(self, itf: "DispInterface") -> None: self.itf = itf -class DispInterface(object): +class DispInterface: def __init__( self, name: str, @@ -166,17 +166,17 @@ def get_head(self) -> DispInterfaceHead: return self.itf_head -class ComInterfaceHead(object): +class ComInterfaceHead: def __init__(self, itf: "ComInterface") -> None: self.itf = itf -class ComInterfaceBody(object): +class ComInterfaceBody: def __init__(self, itf: "ComInterface") -> None: self.itf = itf -class ComInterface(object): +class ComInterface: def __init__( self, name: str, @@ -208,7 +208,7 @@ def get_head(self) -> ComInterfaceHead: _Interface = _UnionT[ComInterface, DispInterface] -class CoClass(object): +class CoClass: def __init__( self, name: str, diff --git a/comtypes/tools/typedesc_base.py b/comtypes/tools/typedesc_base.py index d9a94b29b..8f85be5b7 100644 --- a/comtypes/tools/typedesc_base.py +++ b/comtypes/tools/typedesc_base.py @@ -5,7 +5,7 @@ import comtypes -class Argument(object): +class Argument: "a Parameter in the argument list of a callable (Function, Method, ...)" def __init__(self, atype, name): @@ -13,7 +13,7 @@ def __init__(self, atype, name): self.name = name -class _HasArgs(object): +class _HasArgs: def __init__(self): self.arguments = [] @@ -37,7 +37,7 @@ def fixup_argtypes(self, typemap): ################ -class Alias(object): +class Alias: # a C preprocessor alias, like #define A B def __init__(self, name, alias, typ=None): self.name = name @@ -45,7 +45,7 @@ def __init__(self, name, alias, typ=None): self.typ = typ -class Macro(object): +class Macro: # a C preprocessor definition with arguments def __init__(self, name, args, body): # all arguments are strings, args is the literal argument list @@ -56,7 +56,7 @@ def __init__(self, name, args, body): self.body = body -class File(object): +class File: def __init__(self, name): self.name = name @@ -107,7 +107,7 @@ def __init__(self, name, returns): self.returns = returns -class FundamentalType(object): +class FundamentalType: location = None def __init__(self, name, size, align): @@ -117,7 +117,7 @@ def __init__(self, name, size, align): self.align = int(align) -class PointerType(object): +class PointerType: location = None def __init__(self, typ, size, align): @@ -126,7 +126,7 @@ def __init__(self, typ, size, align): self.align = int(align) -class Typedef(object): +class Typedef: location = None def __init__(self, name, typ): @@ -134,7 +134,7 @@ def __init__(self, name, typ): self.typ = typ -class ArrayType(object): +class ArrayType: location = None def __init__(self, typ: Any, min: int, max: int) -> None: @@ -143,21 +143,21 @@ def __init__(self, typ: Any, min: int, max: int) -> None: self.max = max -class StructureHead(object): +class StructureHead: location = None def __init__(self, struct: "_Struct_Union_Base") -> None: self.struct = struct -class StructureBody(object): +class StructureBody: location = None def __init__(self, struct: "_Struct_Union_Base") -> None: self.struct = struct -class _Struct_Union_Base(object): +class _Struct_Union_Base: name: str align: int members: List[_UnionT["Field", Method, Constructor]] @@ -198,7 +198,7 @@ def __init__( self.size = int(size) else: self.size = None - super(Structure, self).__init__() + super().__init__() class Union(_Struct_Union_Base): @@ -220,10 +220,10 @@ def __init__( self.size = int(size) else: self.size = None - super(Union, self).__init__() + super().__init__() -class Field(object): +class Field: def __init__( self, name: str, typ: Any, bits: Optional[Any], offset: SupportsInt ) -> None: @@ -233,14 +233,14 @@ def __init__( self.offset = int(offset) -class CvQualifiedType(object): +class CvQualifiedType: def __init__(self, typ, const, volatile): self.typ = typ self.const = const self.volatile = volatile -class Enumeration(object): +class Enumeration: location = None def __init__(self, name: str, size: SupportsInt, align: SupportsInt) -> None: @@ -253,14 +253,14 @@ def add_value(self, v: "EnumValue") -> None: self.values.append(v) -class EnumValue(object): +class EnumValue: def __init__(self, name: str, value: int, enumeration: Enumeration) -> None: self.name = name self.value = value self.enumeration = enumeration -class Variable(object): +class Variable: location = None def __init__(self, name, typ, init=None): diff --git a/comtypes/viewobject.py b/comtypes/viewobject.py index a7499ef6d..e6b3205bb 100644 --- a/comtypes/viewobject.py +++ b/comtypes/viewobject.py @@ -57,7 +57,7 @@ class tagExtentInfo(Structure): def __init__(self, *args, **kw): self.cb = sizeof(self) - super(tagExtentInfo, self).__init__(*args, **kw) + super().__init__(*args, **kw) def __repr__(self): size = (self.sizelProposed.cx, self.sizelProposed.cy) diff --git a/docs/source/conf.py b/docs/source/conf.py index 92b749d4e..aa7d6532a 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # comtypes documentation build configuration file, created by # sphinx-quickstart on Mon Apr 07 16:12:34 2014. diff --git a/setup.py b/setup.py index 407cdfcbd..36e08d922 100644 --- a/setup.py +++ b/setup.py @@ -59,7 +59,7 @@ def run(self): for name in self.tests: package = __import__(name, globals(), locals(), ['*']) sys.stdout.write( - "Testing package %s %s\n" % (name, (sys.version, sys.platform, os.name)) + "Testing package {} {}\n".format(name, (sys.version, sys.platform, os.name)) ) package_failure = comtypes.test.run_tests( package, "test_*.py", self.verbose, self.refcounts diff --git a/test_pip_install.py b/test_pip_install.py index 09e333e34..87049b9c8 100644 --- a/test_pip_install.py +++ b/test_pip_install.py @@ -32,14 +32,14 @@ def test_pip_install(self): subprocess.check_call([self.pip_exe, 'install', self.target_package]) def test_no_cache_dir_custom_location(self): - """Test that 'pip install comtypes-x.y.z.zip --no-cache-dir --target="...\custom location"' works""" + r"""Test that 'pip install comtypes-x.y.z.zip --no-cache-dir --target="...\custom location"' works""" custom_dir = os.path.join(os.getcwd(), 'custom location') if os.path.exists(custom_dir): shutil.rmtree(custom_dir) os.makedirs(custom_dir) # this test catches issue #158 - subprocess.check_call('{0} install {1} --no-cache-dir --target="{2}"' \ + subprocess.check_call('{} install {} --no-cache-dir --target="{}"' \ ''.format(self.pip_exe, self.target_package, custom_dir)) From cb7c88496564c373e275f42617e5e318ef2bddd6 Mon Sep 17 00:00:00 2001 From: moi15moi <80980684+moi15moi@users.noreply.github.com> Date: Tue, 28 Jan 2025 16:44:03 -0500 Subject: [PATCH 2/2] Format code with Ruff --- comtypes/_post_coinit/unknwn.py | 4 +--- comtypes/test/test_npsupport.py | 4 +--- comtypes/test/test_variant.py | 1 + comtypes/tools/codegenerator/packing.py | 4 ++-- comtypes/tools/tlbparser.py | 14 +++++++------- 5 files changed, 12 insertions(+), 15 deletions(-) diff --git a/comtypes/_post_coinit/unknwn.py b/comtypes/_post_coinit/unknwn.py index 139a5774d..5a0b6f1d9 100644 --- a/comtypes/_post_coinit/unknwn.py +++ b/comtypes/_post_coinit/unknwn.py @@ -283,9 +283,7 @@ def __eq__(self, other): if not isinstance(other, _compointer_base): return False # get the value property of the c_void_p baseclass, this is the pointer value - return ( - super().value == super(_compointer_base, other).value - ) + return super().value == super(_compointer_base, other).value def __hash__(self): """Return the hash value of the pointer.""" diff --git a/comtypes/test/test_npsupport.py b/comtypes/test/test_npsupport.py index 8ae23f5cd..aa4994286 100644 --- a/comtypes/test/test_npsupport.py +++ b/comtypes/test/test_npsupport.py @@ -70,9 +70,7 @@ def call_disabled(self): from comtypes import npsupport if npsupport.enabled: - raise OSError( - "Expected numpy interop not to be enabled but it is." - ) + raise OSError("Expected numpy interop not to be enabled but it is.") with self.assertRaises(disabled_error): func(self) diff --git a/comtypes/test/test_variant.py b/comtypes/test/test_variant.py index 2a21749ff..73e642d33 100644 --- a/comtypes/test/test_variant.py +++ b/comtypes/test/test_variant.py @@ -300,6 +300,7 @@ def check_perf(rep=20000): ptr_var = pointer(variable) import pickle + try: previous = pickle.load(open("result.pickle", "rb")) except OSError: diff --git a/comtypes/tools/codegenerator/packing.py b/comtypes/tools/codegenerator/packing.py index adc0c1bf1..ba706eea6 100644 --- a/comtypes/tools/codegenerator/packing.py +++ b/comtypes/tools/codegenerator/packing.py @@ -64,8 +64,8 @@ class PackingError(Exception): # XXX These should be filtered out in gccxmlparser. dont_assert_size = { - "__si_class_type_info_pseudo", - "__class_type_info_pseudo", + "__si_class_type_info_pseudo", + "__class_type_info_pseudo", } diff --git a/comtypes/tools/tlbparser.py b/comtypes/tools/tlbparser.py index 3f5e5fd59..2079aecce 100644 --- a/comtypes/tools/tlbparser.py +++ b/comtypes/tools/tlbparser.py @@ -358,13 +358,13 @@ def ParseDispatch( # I have encountered typlibs where only "QueryInterface", "AddRef" # and "Release" are to be skipped. ignored_names = { - "QueryInterface", - "AddRef", - "Release", - "GetTypeInfoCount", - "GetTypeInfo", - "GetIDsOfNames", - "Invoke", + "QueryInterface", + "AddRef", + "Release", + "GetTypeInfoCount", + "GetTypeInfo", + "GetIDsOfNames", + "Invoke", } for i in range(ta.cFuncs):