Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating by fstring #667

Merged
merged 21 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
517a75a
Refactor string formatting in `_code_cache.py`
newwingbird Nov 17, 2024
9e1aa7e
Refactor string formatting in `_events.py`
newwingbird Nov 17, 2024
efdaf99
Refactor string formatting in `_generate.py` to use f-strings
newwingbird Nov 17, 2024
53db14e
Refactor string formatting in `lazybind.py` to use f-strings
newwingbird Nov 17, 2024
9fd2305
Refactor string formatting in `errorinfo.py` to use f-strings
newwingbird Nov 17, 2024
f6a269b
Refactor string formatting in `inprocserver.py` to use f-strings
newwingbird Nov 17, 2024
f20d769
Refactor string formatting in `register.py` to use f-strings
newwingbird Nov 17, 2024
c5e0589
Refactor string formatting in `_constants.py` to use f-strings. one c…
newwingbird Nov 17, 2024
9cfd602
Refactor string formatting in `w_getopt.py` to use f-strings
newwingbird Nov 17, 2024
56e0eef
Fixed after PR reviewed
newwingbird Nov 17, 2024
0838f71
fix mistakes
newwingbird Nov 17, 2024
e87b4dc
Improved code
newwingbird Nov 17, 2024
a0d76ad
Fix `register.py` to use raw-fstring
newwingbird Nov 17, 2024
97b670e
Refactor string formatting in `codegenerator.py` to use f-strings
newwingbird Nov 20, 2024
0dbbf23
Fix path separators in `_code_cache.py` for consistency across platforms
newwingbird Nov 20, 2024
994c4ab
Refactor string representations in `helpers.py` to use f-strings for …
newwingbird Nov 20, 2024
2efb298
Fix script path handling in `register.py` to include script path in C…
newwingbird Nov 20, 2024
784e9e6
Apply suggestions from code review
junkmd Nov 20, 2024
0073f81
Update comtypes/server/register.py
junkmd Nov 20, 2024
df9e5b0
Update comtypes/errorinfo.py
junkmd Nov 20, 2024
d78a877
Update register.py
junkmd Nov 20, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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"
junkmd marked this conversation as resolved.
Show resolved Hide resolved
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})"
junkmd marked this conversation as resolved.
Show resolved Hide resolved
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
36 changes: 14 additions & 22 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 @@ -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}")
junkmd marked this conversation as resolved.
Show resolved Hide resolved
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