Skip to content

Commit

Permalink
Updating by fstring (#667)
Browse files Browse the repository at this point in the history
* Refactor string formatting in `_code_cache.py`

* Refactor string formatting in `_events.py`

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

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

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

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

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

* Refactor string formatting in `_constants.py` to use f-strings. one comment line...

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

* Fixed after PR reviewed

* fix mistakes

* Improved code

* Fix `register.py` to use raw-fstring

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

* Fix path separators in `_code_cache.py` for consistency across platforms

* Refactor string representations in `helpers.py` to use f-strings for improved readability

* Fix script path handling in `register.py` to include script path in CLSID registration

* Apply suggestions from code review

* Update comtypes/server/register.py

* Update comtypes/errorinfo.py

* Update register.py

---------

Co-authored-by: Jun Komoda <[email protected]>
  • Loading branch information
newwingbird and junkmd authored Nov 21, 2024
1 parent 1ea74f5 commit fb15f91
Show file tree
Hide file tree
Showing 11 changed files with 107 additions and 125 deletions.
8 changes: 4 additions & 4 deletions comtypes/client/_code_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,23 +48,23 @@ def _find_gen_dir():
# check type of executable image to determine a subdirectory
# where generated modules are placed.
ftype = getattr(sys, "frozen", None)
version_str = "%d%d" % sys.version_info[:2]
pymaj, pymin = sys.version_info[:2]
if ftype == None:
# Python script
subdir = r"Python\Python%s\comtypes_cache" % version_str
subdir = rf"Python\Python{pymaj:d}{pymin:d}\comtypes_cache"
basedir = _get_appdata_dir()

elif ftype == "dll":
# dll created with py2exe
path = _get_module_filename(sys.frozendllhandle)
base = os.path.splitext(os.path.basename(path))[0]
subdir = r"comtypes_cache\%s-%s" % (base, version_str)
subdir = rf"comtypes_cache\{base}-{pymaj:d}{pymin:d}"
basedir = tempfile.gettempdir()

else: # ftype in ('windows_exe', 'console_exe')
# exe created by py2exe
base = os.path.splitext(os.path.basename(sys.executable))[0]
subdir = r"comtypes_cache\%s-%s" % (base, version_str)
subdir = rf"comtypes_cache\{base}-{pymaj:d}{pymin:d}"
basedir = tempfile.gettempdir()

gen_dir = os.path.join(basedir, subdir)
Expand Down
2 changes: 1 addition & 1 deletion comtypes/client/_constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _get_members(self, tinfo, ta):
# XXX is necessary warning? should use logging?
# import comtypes.tools
# if comtypes.tools.__warn_on_munge__:
# print("# Fixing keyword as VAR_CONST for %s" % name)
# print(f"# Fixing keyword as VAR_CONST for {name}")
name += "_"
members[name] = vdesc._.lpvarValue[0].value
return _frozen_attr_dict(members)
Expand Down
2 changes: 1 addition & 1 deletion comtypes/client/_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def __getattr__(self, name):
def handler(self, this, *args, **kw):
# XXX handler is called with 'this'. Should we really print "None" instead?
args = (None,) + args
print("Event %s(%s)" % (name, ", ".join([repr(a) for a in args])))
print(f"Event {name}({', '.join([repr(a) for a in args])})")

return comtypes.instancemethod(handler, self, EventDumper)

Expand Down
12 changes: 4 additions & 8 deletions comtypes/client/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,20 +139,16 @@ def _load_tlib(obj: Any) -> typeinfo.ITypeLib:
elif isinstance(obj, GUID):
clsid = str(obj)
# lookup associated typelib in registry
with winreg.OpenKey(
winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\TypeLib" % clsid
) as key:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\TypeLib") as key:
libid = winreg.EnumValue(key, 0)[1]
with winreg.OpenKey(
winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\Version" % clsid
) as key:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\Version") as key:
ver = winreg.EnumValue(key, 0)[1].split(".")
return typeinfo.LoadRegTypeLib(GUID(libid), int(ver[0]), int(ver[1]), 0)
# obj is a sequence containing libid
elif isinstance(obj, (tuple, list)):
libid, ver = obj[0], obj[1:]
if not ver: # case of version numbers are not containing
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"TypeLib\%s" % libid) as key:
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"TypeLib\{libid}") as key:
ver = [int(v, base=16) for v in winreg.EnumKey(key, 0).split(".")]
return typeinfo.LoadRegTypeLib(GUID(libid), *ver)
# obj is a COMObject implementation
Expand All @@ -161,7 +157,7 @@ def _load_tlib(obj: Any) -> typeinfo.ITypeLib:
# obj is a pointer of ITypeLib
elif isinstance(obj, ctypes.POINTER(typeinfo.ITypeLib)):
return obj # type: ignore
raise TypeError("'%r' is not supported type for loading typelib" % obj)
raise TypeError(f"'{obj!r}' is not supported type for loading typelib")


def _get_existing_module(tlib: typeinfo.ITypeLib) -> Optional[types.ModuleType]:
Expand Down
4 changes: 2 additions & 2 deletions comtypes/client/lazybind.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def __setitem__(self, name, value):

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


Expand Down Expand Up @@ -151,7 +151,7 @@ def __getattr__(self, name):
if descr.cParams == 1:
return self._comobj._invoke(descr.memid, descr.invkind, 0)
else:
raise RuntimeError("funckind %d not yet implemented" % descr.funckind)
raise RuntimeError(f"funckind {descr.funckind:d} not yet implemented")
put = self.__bind(name, DISPATCH_PROPERTYPUT)
putref = self.__bind(name, DISPATCH_PROPERTYPUTREF)
return NamedProperty(self, descr, put, putref)
Expand Down
4 changes: 2 additions & 2 deletions comtypes/errorinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,9 +103,9 @@ def ReportException(
tb = tb.tb_next
line = tb.tb_frame.f_lineno
name = tb.tb_frame.f_globals["__name__"]
text = "%s: %s (%s, line %d)" % (typ, value, name, line)
text = f"{typ}: {value} ({name}, line {line:d})"
else:
text = "%s: %s" % (typ, value)
text = f"{typ}: {value}"
return ReportError(
text,
iid,
Expand Down
2 changes: 1 addition & 1 deletion comtypes/server/inprocserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def inproc_find_class(clsid):
if _clsid_to_class:
return _clsid_to_class[clsid]

key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID\\%s\\InprocServer32" % clsid)
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, f"CLSID\\{clsid}\\InprocServer32")
try:
pathdir = winreg.QueryValueEx(key, "PythonPath")[0]
except:
Expand Down
48 changes: 20 additions & 28 deletions comtypes/server/register.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def nodebug(self, cls):
'DeleteKey( %s\\CLSID\\%s\\Logging"'
% (_explain(winreg.HKEY_CLASSES_ROOT), clsid)
)
hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s" % clsid)
hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}")
winreg.DeleteKey(hkey, "Logging")
except WindowsError as detail:
if get_winerror(detail) != 2:
Expand All @@ -115,7 +115,7 @@ def debug(self, cls, levels, format):
'CreateKey( %s\\CLSID\\%s\\Logging"'
% (_explain(winreg.HKEY_CLASSES_ROOT), clsid)
)
hkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\Logging" % clsid)
hkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\Logging")
for item in levels:
name, value = item.split("=")
v = getattr(logging, value)
Expand Down Expand Up @@ -230,7 +230,7 @@ def _get_full_classname(self, cls):
modname = cls.__module__
if modname == "__main__":
modname = os.path.splitext(os.path.basename(sys.argv[0]))[0]
return "%s.%s" % (modname, cls.__name__)
return f"{modname}.{cls.__name__}"

def _get_pythonpath(self, cls):
"""Return the filesystem path of the module containing 'cls'."""
Expand Down Expand Up @@ -278,30 +278,30 @@ def _registry_entries(self, cls):
)
if reg_desc:
reg_desc = reg_desc.replace(".", " ")
append(HKCR, "CLSID\\%s" % reg_clsid, "", reg_desc)
append(HKCR, f"CLSID\\{reg_clsid}", "", reg_desc)

reg_progid = getattr(cls, "_reg_progid_", None)
if reg_progid:
# for ProgIDFromCLSID:
append(HKCR, "CLSID\\%s\\ProgID" % reg_clsid, "", reg_progid) # 1
append(HKCR, f"CLSID\\{reg_clsid}\\ProgID", "", reg_progid) # 1

# for CLSIDFromProgID
if reg_desc:
append(HKCR, reg_progid, "", reg_desc) # 2
append(HKCR, "%s\\CLSID" % reg_progid, "", reg_clsid) # 3
append(HKCR, f"{reg_progid}\\CLSID", "", reg_clsid) # 3

reg_novers_progid = getattr(cls, "_reg_novers_progid_", None)
if reg_novers_progid:
append(
HKCR,
"CLSID\\%s\\VersionIndependentProgID" % reg_clsid, # 1a
f"CLSID\\{reg_clsid}\\VersionIndependentProgID", # 1a
"",
reg_novers_progid,
)
if reg_desc:
append(HKCR, reg_novers_progid, "", reg_desc) # 2a
append(HKCR, "%s\\CurVer" % reg_novers_progid, "", reg_progid) #
append(HKCR, "%s\\CLSID" % reg_novers_progid, "", reg_clsid) # 3a
append(HKCR, f"{reg_novers_progid}\\CurVer", "", reg_progid) #
append(HKCR, f"{reg_novers_progid}\\CLSID", "", reg_clsid) # 3a

clsctx = getattr(cls, "_reg_clsctx_", 0)

Expand All @@ -310,21 +310,16 @@ def _registry_entries(self, cls):
):
exe = sys.executable
if " " in exe:
exe = '"%s"' % exe
exe = f'"{exe}"'
if not hasattr(sys, "frozen"):
if not __debug__:
exe = "%s -O" % exe
exe = f"{exe} -O"
script = os.path.abspath(sys.modules[cls.__module__].__file__)
if " " in script:
script = '"%s"' % script
append(
HKCR,
"CLSID\\%s\\LocalServer32" % reg_clsid,
"",
"%s %s" % (exe, script),
)
script = f'"{script}"'
append(HKCR, rf"CLSID\{reg_clsid}\LocalServer32", "", f"{exe} {script}")
else:
append(HKCR, "CLSID\\%s\\LocalServer32" % reg_clsid, "", "%s" % exe)
append(HKCR, rf"CLSID\{reg_clsid}\LocalServer32", "", f"{exe}")

# Register InprocServer32 only when run from script or from
# py2exe dll server, not from py2exe exe server.
Expand All @@ -333,7 +328,7 @@ def _registry_entries(self, cls):
"dll",
):
append(
HKCR, "CLSID\\%s\\InprocServer32" % reg_clsid, "", self._get_serverdll()
HKCR, rf"CLSID\{reg_clsid}\InprocServer32", "", self._get_serverdll()
)
# only for non-frozen inproc servers the PythonPath/PythonClass is needed.
if (
Expand All @@ -342,13 +337,13 @@ def _registry_entries(self, cls):
):
append(
HKCR,
"CLSID\\%s\\InprocServer32" % reg_clsid,
rf"CLSID\{reg_clsid}\InprocServer32",
"PythonClass",
self._get_full_classname(cls),
)
append(
HKCR,
"CLSID\\%s\\InprocServer32" % reg_clsid,
rf"CLSID\{reg_clsid}\InprocServer32",
"PythonPath",
self._get_pythonpath(cls),
)
Expand All @@ -357,14 +352,14 @@ def _registry_entries(self, cls):
if reg_threading is not None:
append(
HKCR,
"CLSID\\%s\\InprocServer32" % reg_clsid,
rf"CLSID\{reg_clsid}\InprocServer32",
"ThreadingModel",
reg_threading,
)

reg_tlib = getattr(cls, "_reg_typelib_", None)
if reg_tlib is not None:
append(HKCR, "CLSID\\%s\\Typelib" % reg_clsid, "", reg_tlib[0])
append(HKCR, rf"CLSID\{reg_clsid}\Typelib", "", reg_tlib[0])

return table

Expand All @@ -381,10 +376,7 @@ def unregister(cls):


def UseCommandLine(*classes):
usage = (
"""Usage: %s [-regserver] [-unregserver] [-nodebug] [-f logformat] [-l loggername=level]"""
% sys.argv[0]
)
usage = f"""Usage: {sys.argv[0]} [-regserver] [-unregserver] [-nodebug] [-f logformat] [-l loggername=level]"""
opts, args = w_getopt.w_getopt(
sys.argv[1:], "regserver unregserver embedding l: f: nodebug"
)
Expand Down
4 changes: 2 additions & 2 deletions comtypes/server/w_getopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ def w_getopt(args, options):
try:
opts.append((arg, args[1]))
except IndexError:
raise GetoptError("option '%s' requires an argument" % args[0])
raise GetoptError(f"option '{args[0]}' requires an argument")
args = args[1:]
elif arg in options:
opts.append((arg, ""))
else:
raise GetoptError("invalid option '%s'" % args[0])
raise GetoptError(f"invalid option '{args[0]}'")
args = args[1:]
else:
arguments.append(args[0])
Expand Down
Loading

0 comments on commit fb15f91

Please sign in to comment.