Skip to content

Commit

Permalink
Refactor string formatting to use f-strings (#666)
Browse files Browse the repository at this point in the history
* Refactor string formatting in automation.py

* Refactor string formatting in _cominterface_meta_patcher.py

* Refactor string formatting to use f-strings in _comobject.py

* Refactor string formatting to use f-strings in _memberspec.py

* Refactor string formatting to use f-strings in _memberspec.py

* Updated modification.

Co-authored-by: Jun Komoda <[email protected]>

* Updated modification by review sugestion

* fmt by ruff

---------

Co-authored-by: Jun Komoda <[email protected]>
  • Loading branch information
newwingbird and junkmd authored Nov 16, 2024
1 parent e3b5e28 commit 1ea74f5
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 31 deletions.
11 changes: 5 additions & 6 deletions comtypes/_comobject.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ def winerror(exc):
# cases we return a generic error code.
return E_FAIL
raise TypeError(
"Expected comtypes.COMERROR or WindowsError instance, got %s"
% type(exc).__name__
f"Expected comtypes.COMERROR or WindowsError instance, got {type(exc).__name__}"
)


Expand Down Expand Up @@ -178,7 +177,7 @@ def call_without_this(this, *args):
args[args_out_idx[0]][0] = result
elif args_out != 0:
if len(result) != args_out:
msg = "Method should have returned a %s-tuple" % args_out
msg = f"Method should have returned a {args_out}-tuple"
raise ValueError(msg)
for i, value in enumerate(result):
args[args_out_idx[i]][0] = value
Expand All @@ -198,7 +197,7 @@ def call_without_this(this, *args):
except (ValueError, TypeError):
msg = str(details)
else:
msg = "%s: %s" % (source, descr)
msg = f"{source}: {descr}"
hr = HRESULT_FROM_WIN32(hr)
return ReportError(msg, iid=interface._iid_, clsid=clsid, hresult=hr)
except WindowsError as details:
Expand Down Expand Up @@ -251,7 +250,7 @@ def find_method(self, fq_name, mthname):
return getattr(self.inst, mthname)

def find_impl(self, interface, mthname, paramflags, idlflags):
fq_name = "%s_%s" % (interface.__name__, mthname)
fq_name = f"{interface.__name__}_{mthname}"
if interface._case_insensitive_:
# simple name, like 'QueryInterface'
mthname = self.names.get(mthname.lower(), mthname)
Expand Down Expand Up @@ -306,7 +305,7 @@ def _create_vtbl_type(fields, itf):
class Vtbl(Structure):
_fields_ = fields

Vtbl.__name__ = "Vtbl_%s" % itf.__name__
Vtbl.__name__ = f"Vtbl_{itf.__name__}"
_vtbl_types[fields] = Vtbl
return Vtbl

Expand Down
16 changes: 8 additions & 8 deletions comtypes/_memberspec.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def _resolve_argspec(
elif typ is ctypes.POINTER(VARIANT):
defval = ctypes.pointer(VARIANT.missing)
else:
# msg = ("'optional' only allowed for VARIANT and VARIANT*, not for %s" % typ.__name__)
# msg = f"'optional' only allowed for VARIANT and VARIANT*, not for {typ.__name__}"
# warnings.warn(msg, IDLWarning, stacklevel=2)
defval = typ()
if defval is _NOTHING:
Expand Down Expand Up @@ -176,11 +176,11 @@ def COMMETHOD(idlflags, restype, methodname, *argspec) -> _ComMemberSpec:
helptext = "".join(t for t in idlflags if isinstance(t, helpstring)) or None
paramflags, argtypes = _resolve_argspec(argspec)
if "propget" in idlflags:
name = "_get_%s" % methodname
name = f"_get_{methodname}"
elif "propput" in idlflags:
name = "_set_%s" % methodname
name = f"_set_{methodname}"
elif "propputref" in idlflags:
name = "_setref_%s" % methodname
name = f"_setref_{methodname}"
else:
name = methodname
return _ComMemberSpec(
Expand Down Expand Up @@ -382,7 +382,7 @@ def __iter__(self) -> Iterator[Tuple[str, _UnionT[property, "named_property"]]]:
# Hm, must be a descriptor where the __get__ method
# returns a bound object having __getitem__ and
# __setitem__ methods.
prop = named_property("%s.%s" % (self._cls_name, name), fget, fset, doc)
prop = named_property(f"{self._cls_name}.{name}", fget, fset, doc)
yield (name, prop)

def to_propget_keys(self, m: _MemberSpec) -> Tuple[str, _DocType, int]:
Expand Down Expand Up @@ -605,11 +605,11 @@ def __setitem__(self, index, value):
self.fset(self.instance, index, value)

def __repr__(self):
return "<bound_named_property %r at %x>" % (self.name, id(self))
return f"<bound_named_property {self.name!r} at {id(self):x}>"

def __iter__(self):
"""Explicitly disallow iteration."""
msg = "%r is not iterable" % self.name
msg = f"{self.name!r} is not iterable"
raise TypeError(msg)


Expand All @@ -630,4 +630,4 @@ def __set__(self, instance):
raise AttributeError("Unsettable attribute")

def __repr__(self):
return "<named_property %r at %x>" % (self.name, id(self))
return f"<named_property {self.name!r} at {id(self):x}>"
4 changes: 2 additions & 2 deletions comtypes/_post_coinit/_cominterface_meta_patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,8 @@ def __setitem__(self, index, value):
else:
raise
except TypeError:
msg = "%r object does not support item assignment"
raise TypeError(msg % type(self))
msg = f"{type(self)!r} object does not support item assignment"
raise TypeError(msg)


def iterator(itf: Type) -> None:
Expand Down
29 changes: 14 additions & 15 deletions comtypes/automation.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,14 +209,14 @@ def __del__(self):

def __repr__(self):
if self.vt & VT_BYREF:
return "VARIANT(vt=0x%x, byref(%r))" % (self.vt, self[0])
return f"VARIANT(vt=0x{self.vt:x}, byref({self[0]!r}))"
elif self is type(self).null:
return "VARIANT.null"
elif self is type(self).empty:
return "VARIANT.empty"
elif self is type(self).missing:
return "VARIANT.missing"
return "VARIANT(vt=0x%x, %r)" % (self.vt, self.value)
return f"VARIANT(vt=0x{self.vt:x}, {self.value!r})"

@classmethod
def from_param(cls, value):
Expand Down Expand Up @@ -425,7 +425,7 @@ def _set_value(self, value):
else:
self.vt = _ctype_to_vartype[type(ref)] | VT_BYREF
else:
raise TypeError("Cannot put %r in VARIANT" % value)
raise TypeError(f"Cannot put {value!r} in VARIANT")
# buffer -> SAFEARRAY of VT_UI1 ?

# c:/sf/pywin32/com/win32com/src/oleargs.cpp 197
Expand Down Expand Up @@ -521,7 +521,7 @@ def _get_value(self, dynamic=False):
typ = _vartype_to_ctype[self.vt & ~VT_ARRAY]
return cast(self._.pparray, _midlSAFEARRAY(typ)).unpack()
else:
raise NotImplementedError("typecode %d = 0x%x)" % (vt, vt))
raise NotImplementedError(f"typecode {vt} = 0x{vt:x})")

def __getitem__(self, index):
if index != 0:
Expand Down Expand Up @@ -711,17 +711,16 @@ class tagEXCEPINFO(Structure):
scode: int

def __repr__(self):
return "<EXCEPINFO %s>" % (
(
self.wCode,
self.bstrSource,
self.bstrDescription,
self.bstrHelpFile,
self.dwHelpContext,
self.pfnDeferredFillIn,
self.scode,
),
info = (
self.wCode,
self.bstrSource,
self.bstrDescription,
self.bstrHelpFile,
self.dwHelpContext,
self.pfnDeferredFillIn,
self.scode,
)
return f"<EXCEPINFO {info}>"


tagEXCEPINFO._fields_ = [
Expand Down Expand Up @@ -917,7 +916,7 @@ def Invoke(self, dispid: int, *args: Any, **kw: Any) -> Any:
raise COMError(
hresult,
text,
("TypeError: Parameter %s" % (argerr.value + 1), args),
(f"TypeError: Parameter {argerr.value + 1}", args),
)
raise
return result._get_value(dynamic=True)
Expand Down

0 comments on commit 1ea74f5

Please sign in to comment.