Skip to content

Commit fb15f91

Browse files
newwingbirdjunkmd
andauthored
Updating by fstring (#667)
* 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]>
1 parent 1ea74f5 commit fb15f91

File tree

11 files changed

+107
-125
lines changed

11 files changed

+107
-125
lines changed

comtypes/client/_code_cache.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,23 +48,23 @@ def _find_gen_dir():
4848
# check type of executable image to determine a subdirectory
4949
# where generated modules are placed.
5050
ftype = getattr(sys, "frozen", None)
51-
version_str = "%d%d" % sys.version_info[:2]
51+
pymaj, pymin = sys.version_info[:2]
5252
if ftype == None:
5353
# Python script
54-
subdir = r"Python\Python%s\comtypes_cache" % version_str
54+
subdir = rf"Python\Python{pymaj:d}{pymin:d}\comtypes_cache"
5555
basedir = _get_appdata_dir()
5656

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

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

7070
gen_dir = os.path.join(basedir, subdir)

comtypes/client/_constants.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ def _get_members(self, tinfo, ta):
118118
# XXX is necessary warning? should use logging?
119119
# import comtypes.tools
120120
# if comtypes.tools.__warn_on_munge__:
121-
# print("# Fixing keyword as VAR_CONST for %s" % name)
121+
# print(f"# Fixing keyword as VAR_CONST for {name}")
122122
name += "_"
123123
members[name] = vdesc._.lpvarValue[0].value
124124
return _frozen_attr_dict(members)

comtypes/client/_events.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ def __getattr__(self, name):
227227
def handler(self, this, *args, **kw):
228228
# XXX handler is called with 'this'. Should we really print "None" instead?
229229
args = (None,) + args
230-
print("Event %s(%s)" % (name, ", ".join([repr(a) for a in args])))
230+
print(f"Event {name}({', '.join([repr(a) for a in args])})")
231231

232232
return comtypes.instancemethod(handler, self, EventDumper)
233233

comtypes/client/_generate.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -139,20 +139,16 @@ def _load_tlib(obj: Any) -> typeinfo.ITypeLib:
139139
elif isinstance(obj, GUID):
140140
clsid = str(obj)
141141
# lookup associated typelib in registry
142-
with winreg.OpenKey(
143-
winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\TypeLib" % clsid
144-
) as key:
142+
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\TypeLib") as key:
145143
libid = winreg.EnumValue(key, 0)[1]
146-
with winreg.OpenKey(
147-
winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\Version" % clsid
148-
) as key:
144+
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\Version") as key:
149145
ver = winreg.EnumValue(key, 0)[1].split(".")
150146
return typeinfo.LoadRegTypeLib(GUID(libid), int(ver[0]), int(ver[1]), 0)
151147
# obj is a sequence containing libid
152148
elif isinstance(obj, (tuple, list)):
153149
libid, ver = obj[0], obj[1:]
154150
if not ver: # case of version numbers are not containing
155-
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"TypeLib\%s" % libid) as key:
151+
with winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"TypeLib\{libid}") as key:
156152
ver = [int(v, base=16) for v in winreg.EnumKey(key, 0).split(".")]
157153
return typeinfo.LoadRegTypeLib(GUID(libid), *ver)
158154
# obj is a COMObject implementation
@@ -161,7 +157,7 @@ def _load_tlib(obj: Any) -> typeinfo.ITypeLib:
161157
# obj is a pointer of ITypeLib
162158
elif isinstance(obj, ctypes.POINTER(typeinfo.ITypeLib)):
163159
return obj # type: ignore
164-
raise TypeError("'%r' is not supported type for loading typelib" % obj)
160+
raise TypeError(f"'{obj!r}' is not supported type for loading typelib")
165161

166162

167163
def _get_existing_module(tlib: typeinfo.ITypeLib) -> Optional[types.ModuleType]:

comtypes/client/lazybind.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def __setitem__(self, name, value):
6767

6868
def __iter__(self):
6969
"""Explicitly disallow iteration."""
70-
msg = "%r is not iterable" % self.disp
70+
msg = f"{self.disp!r} is not iterable"
7171
raise TypeError(msg)
7272

7373

@@ -151,7 +151,7 @@ def __getattr__(self, name):
151151
if descr.cParams == 1:
152152
return self._comobj._invoke(descr.memid, descr.invkind, 0)
153153
else:
154-
raise RuntimeError("funckind %d not yet implemented" % descr.funckind)
154+
raise RuntimeError(f"funckind {descr.funckind:d} not yet implemented")
155155
put = self.__bind(name, DISPATCH_PROPERTYPUT)
156156
putref = self.__bind(name, DISPATCH_PROPERTYPUTREF)
157157
return NamedProperty(self, descr, put, putref)

comtypes/errorinfo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,9 +103,9 @@ def ReportException(
103103
tb = tb.tb_next
104104
line = tb.tb_frame.f_lineno
105105
name = tb.tb_frame.f_globals["__name__"]
106-
text = "%s: %s (%s, line %d)" % (typ, value, name, line)
106+
text = f"{typ}: {value} ({name}, line {line:d})"
107107
else:
108-
text = "%s: %s" % (typ, value)
108+
text = f"{typ}: {value}"
109109
return ReportError(
110110
text,
111111
iid,

comtypes/server/inprocserver.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def inproc_find_class(clsid):
4444
if _clsid_to_class:
4545
return _clsid_to_class[clsid]
4646

47-
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, "CLSID\\%s\\InprocServer32" % clsid)
47+
key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, f"CLSID\\{clsid}\\InprocServer32")
4848
try:
4949
pathdir = winreg.QueryValueEx(key, "PythonPath")[0]
5050
except:

comtypes/server/register.py

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def nodebug(self, cls):
100100
'DeleteKey( %s\\CLSID\\%s\\Logging"'
101101
% (_explain(winreg.HKEY_CLASSES_ROOT), clsid)
102102
)
103-
hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s" % clsid)
103+
hkey = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}")
104104
winreg.DeleteKey(hkey, "Logging")
105105
except WindowsError as detail:
106106
if get_winerror(detail) != 2:
@@ -115,7 +115,7 @@ def debug(self, cls, levels, format):
115115
'CreateKey( %s\\CLSID\\%s\\Logging"'
116116
% (_explain(winreg.HKEY_CLASSES_ROOT), clsid)
117117
)
118-
hkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, r"CLSID\%s\Logging" % clsid)
118+
hkey = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, rf"CLSID\{clsid}\Logging")
119119
for item in levels:
120120
name, value = item.split("=")
121121
v = getattr(logging, value)
@@ -230,7 +230,7 @@ def _get_full_classname(self, cls):
230230
modname = cls.__module__
231231
if modname == "__main__":
232232
modname = os.path.splitext(os.path.basename(sys.argv[0]))[0]
233-
return "%s.%s" % (modname, cls.__name__)
233+
return f"{modname}.{cls.__name__}"
234234

235235
def _get_pythonpath(self, cls):
236236
"""Return the filesystem path of the module containing 'cls'."""
@@ -278,30 +278,30 @@ def _registry_entries(self, cls):
278278
)
279279
if reg_desc:
280280
reg_desc = reg_desc.replace(".", " ")
281-
append(HKCR, "CLSID\\%s" % reg_clsid, "", reg_desc)
281+
append(HKCR, f"CLSID\\{reg_clsid}", "", reg_desc)
282282

283283
reg_progid = getattr(cls, "_reg_progid_", None)
284284
if reg_progid:
285285
# for ProgIDFromCLSID:
286-
append(HKCR, "CLSID\\%s\\ProgID" % reg_clsid, "", reg_progid) # 1
286+
append(HKCR, f"CLSID\\{reg_clsid}\\ProgID", "", reg_progid) # 1
287287

288288
# for CLSIDFromProgID
289289
if reg_desc:
290290
append(HKCR, reg_progid, "", reg_desc) # 2
291-
append(HKCR, "%s\\CLSID" % reg_progid, "", reg_clsid) # 3
291+
append(HKCR, f"{reg_progid}\\CLSID", "", reg_clsid) # 3
292292

293293
reg_novers_progid = getattr(cls, "_reg_novers_progid_", None)
294294
if reg_novers_progid:
295295
append(
296296
HKCR,
297-
"CLSID\\%s\\VersionIndependentProgID" % reg_clsid, # 1a
297+
f"CLSID\\{reg_clsid}\\VersionIndependentProgID", # 1a
298298
"",
299299
reg_novers_progid,
300300
)
301301
if reg_desc:
302302
append(HKCR, reg_novers_progid, "", reg_desc) # 2a
303-
append(HKCR, "%s\\CurVer" % reg_novers_progid, "", reg_progid) #
304-
append(HKCR, "%s\\CLSID" % reg_novers_progid, "", reg_clsid) # 3a
303+
append(HKCR, f"{reg_novers_progid}\\CurVer", "", reg_progid) #
304+
append(HKCR, f"{reg_novers_progid}\\CLSID", "", reg_clsid) # 3a
305305

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

@@ -310,21 +310,16 @@ def _registry_entries(self, cls):
310310
):
311311
exe = sys.executable
312312
if " " in exe:
313-
exe = '"%s"' % exe
313+
exe = f'"{exe}"'
314314
if not hasattr(sys, "frozen"):
315315
if not __debug__:
316-
exe = "%s -O" % exe
316+
exe = f"{exe} -O"
317317
script = os.path.abspath(sys.modules[cls.__module__].__file__)
318318
if " " in script:
319-
script = '"%s"' % script
320-
append(
321-
HKCR,
322-
"CLSID\\%s\\LocalServer32" % reg_clsid,
323-
"",
324-
"%s %s" % (exe, script),
325-
)
319+
script = f'"{script}"'
320+
append(HKCR, rf"CLSID\{reg_clsid}\LocalServer32", "", f"{exe} {script}")
326321
else:
327-
append(HKCR, "CLSID\\%s\\LocalServer32" % reg_clsid, "", "%s" % exe)
322+
append(HKCR, rf"CLSID\{reg_clsid}\LocalServer32", "", f"{exe}")
328323

329324
# Register InprocServer32 only when run from script or from
330325
# py2exe dll server, not from py2exe exe server.
@@ -333,7 +328,7 @@ def _registry_entries(self, cls):
333328
"dll",
334329
):
335330
append(
336-
HKCR, "CLSID\\%s\\InprocServer32" % reg_clsid, "", self._get_serverdll()
331+
HKCR, rf"CLSID\{reg_clsid}\InprocServer32", "", self._get_serverdll()
337332
)
338333
# only for non-frozen inproc servers the PythonPath/PythonClass is needed.
339334
if (
@@ -342,13 +337,13 @@ def _registry_entries(self, cls):
342337
):
343338
append(
344339
HKCR,
345-
"CLSID\\%s\\InprocServer32" % reg_clsid,
340+
rf"CLSID\{reg_clsid}\InprocServer32",
346341
"PythonClass",
347342
self._get_full_classname(cls),
348343
)
349344
append(
350345
HKCR,
351-
"CLSID\\%s\\InprocServer32" % reg_clsid,
346+
rf"CLSID\{reg_clsid}\InprocServer32",
352347
"PythonPath",
353348
self._get_pythonpath(cls),
354349
)
@@ -357,14 +352,14 @@ def _registry_entries(self, cls):
357352
if reg_threading is not None:
358353
append(
359354
HKCR,
360-
"CLSID\\%s\\InprocServer32" % reg_clsid,
355+
rf"CLSID\{reg_clsid}\InprocServer32",
361356
"ThreadingModel",
362357
reg_threading,
363358
)
364359

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

369364
return table
370365

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

382377

383378
def UseCommandLine(*classes):
384-
usage = (
385-
"""Usage: %s [-regserver] [-unregserver] [-nodebug] [-f logformat] [-l loggername=level]"""
386-
% sys.argv[0]
387-
)
379+
usage = f"""Usage: {sys.argv[0]} [-regserver] [-unregserver] [-nodebug] [-f logformat] [-l loggername=level]"""
388380
opts, args = w_getopt.w_getopt(
389381
sys.argv[1:], "regserver unregserver embedding l: f: nodebug"
390382
)

comtypes/server/w_getopt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ def w_getopt(args, options):
2929
try:
3030
opts.append((arg, args[1]))
3131
except IndexError:
32-
raise GetoptError("option '%s' requires an argument" % args[0])
32+
raise GetoptError(f"option '{args[0]}' requires an argument")
3333
args = args[1:]
3434
elif arg in options:
3535
opts.append((arg, ""))
3636
else:
37-
raise GetoptError("invalid option '%s'" % args[0])
37+
raise GetoptError(f"invalid option '{args[0]}'")
3838
args = args[1:]
3939
else:
4040
arguments.append(args[0])

0 commit comments

Comments
 (0)