diff --git a/comtypes/client/_code_cache.py b/comtypes/client/_code_cache.py index 7ba7cfbfd..a404cb683 100644 --- a/comtypes/client/_code_cache.py +++ b/comtypes/client/_code_cache.py @@ -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) diff --git a/comtypes/client/_constants.py b/comtypes/client/_constants.py index bc9f6e918..e090c2190 100644 --- a/comtypes/client/_constants.py +++ b/comtypes/client/_constants.py @@ -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) diff --git a/comtypes/client/_events.py b/comtypes/client/_events.py index 4a275ecc9..8c5d730e9 100644 --- a/comtypes/client/_events.py +++ b/comtypes/client/_events.py @@ -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) diff --git a/comtypes/client/_generate.py b/comtypes/client/_generate.py index 1d105a33b..381556931 100644 --- a/comtypes/client/_generate.py +++ b/comtypes/client/_generate.py @@ -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 @@ -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]: diff --git a/comtypes/client/lazybind.py b/comtypes/client/lazybind.py index d5feabc4b..97993882c 100644 --- a/comtypes/client/lazybind.py +++ b/comtypes/client/lazybind.py @@ -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) @@ -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) diff --git a/comtypes/errorinfo.py b/comtypes/errorinfo.py index 55e6ee62f..e04dc8ea4 100644 --- a/comtypes/errorinfo.py +++ b/comtypes/errorinfo.py @@ -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, diff --git a/comtypes/server/inprocserver.py b/comtypes/server/inprocserver.py index 60fe440d3..57935c30a 100644 --- a/comtypes/server/inprocserver.py +++ b/comtypes/server/inprocserver.py @@ -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: diff --git a/comtypes/server/register.py b/comtypes/server/register.py index 9a9e86b4f..41c6ffc74 100644 --- a/comtypes/server/register.py +++ b/comtypes/server/register.py @@ -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: @@ -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) @@ -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'.""" @@ -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) @@ -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. @@ -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 ( @@ -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), ) @@ -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 @@ -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" ) diff --git a/comtypes/server/w_getopt.py b/comtypes/server/w_getopt.py index 0c45ea917..b0ae0b9e4 100644 --- a/comtypes/server/w_getopt.py +++ b/comtypes/server/w_getopt.py @@ -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]) diff --git a/comtypes/tools/codegenerator/codegenerator.py b/comtypes/tools/codegenerator/codegenerator.py index 5d207ea0d..5244afd7c 100644 --- a/comtypes/tools/codegenerator/codegenerator.py +++ b/comtypes/tools/codegenerator/codegenerator.py @@ -128,9 +128,9 @@ def _generate_typelib_path(self, filename): path = self._make_relative_path(filename, comtypes.gen.__path__[0]) self.imports.add("os") definition = ( - "os.path.normpath(\n" - " os.path.abspath(os.path.join(os.path.dirname(__file__),\n" - " %r)))" % path + f"os.path.normpath(\n" + f" os.path.abspath(os.path.join(os.path.dirname(__file__),\n" + f" {path!r})))" ) self.declarations.add("typelib_path", definition) p = os.path.normpath( @@ -293,7 +293,7 @@ def _to_docstring(self, orig: str, depth: int = 1) -> str: indent = " " * depth # some chars are replaced to avoid causing a `SyntaxError` repled = orig.replace("\\", r"\\").replace('"', r"'") - return '%s"""%s"""' % (indent, repled) + return f'{indent}"""{repled}"""' def ArrayType(self, tp: typedesc.ArrayType) -> None: self.generate(get_real_type(tp.typ)) @@ -347,7 +347,7 @@ def StructureHead(self, head: typedesc.StructureHead) -> None: self.more.add(struct) if head.struct.location: self.last_item_class = False - print("# %s %s" % head.struct.location, file=self.stream) + print(f"# {head.struct.location}", file=self.stream) basenames = [self._to_type_name(b) for b in head.struct.bases] if basenames: self.imports.add("comtypes", "GUID") @@ -362,7 +362,7 @@ def StructureHead(self, head: typedesc.StructureHead) -> None: m.name for m in head.struct.members if type(m) is typedesc.Method ] print( - "class %s(%s):" % (head.struct.name, ", ".join(basenames)), + f"class {head.struct.name}({', '.join(basenames)}):", file=self.stream, ) print( @@ -397,7 +397,7 @@ def StructureHead(self, head: typedesc.StructureHead) -> None: print("assert 0, 'cannot generate code for IUnknown'", file=self.stream) print(file=self.stream) print(file=self.stream) - print("class %s(_com_interface):" % head.struct.name, file=self.stream) + print(f"class {head.struct.name}(_com_interface):", file=self.stream) print(" pass", file=self.stream) print(file=self.stream) print(file=self.stream) @@ -408,10 +408,10 @@ def StructureHead(self, head: typedesc.StructureHead) -> None: self.last_item_class = True - print("class %s(Structure):" % head.struct.name, file=self.stream) + print(f"class {head.struct.name}(Structure):", file=self.stream) if hasattr(head.struct, "_recordinfo_"): print( - " _recordinfo_ = %r" % (head.struct._recordinfo_,), + f" _recordinfo_ = {head.struct._recordinfo_!r}", file=self.stream, ) else: @@ -425,7 +425,7 @@ def StructureHead(self, head: typedesc.StructureHead) -> None: self.last_item_class = True - print("class %s(Union):" % head.struct.name, file=self.stream) + print(f"class {head.struct.name}(Union):", file=self.stream) print(" pass", file=self.stream) print(file=self.stream) print(file=self.stream) @@ -462,14 +462,14 @@ def StructureBody(self, body: typedesc.StructureBody) -> None: pack = packing.calc_packing(body.struct, fields) if pack is not None: self.last_item_class = False - print("%s._pack_ = %s" % (body.struct.name, pack), file=self.stream) + print(f"{body.struct.name}._pack_ = {pack}", file=self.stream) except packing.PackingError as details: # if packing fails, write a warning comment to the output. import warnings message = "Structure %s: %s" % (body.struct.name, details) warnings.warn(message, UserWarning) - print("# WARNING: %s" % details, file=self.stream) + print(f"# WARNING: {details}", file=self.stream) self.last_item_class = False if fields: @@ -482,9 +482,9 @@ def StructureBody(self, body: typedesc.StructureBody) -> None: self.last_item_class = False - print("%s._fields_ = [" % body.struct.name, file=self.stream) + print(f"{body.struct.name}._fields_ = [", file=self.stream) if body.struct.location: - print(" # %s %s" % body.struct.location, file=self.stream) + print(f" # {body.struct.location}", file=self.stream) # unnamed fields will get autogenerated names "_", "_1". "_2", "_3", ... unnamed_index = 0 for f in fields: @@ -495,20 +495,19 @@ def StructureBody(self, body: typedesc.StructureBody) -> None: fieldname = "_" unnamed_index += 1 print( - " # Unnamed field renamed to '%s'" % fieldname, + f" # Unnamed field renamed to '{fieldname}'", file=self.stream, ) else: fieldname = f.name if f.bits is None: print( - " ('%s', %s)," % (fieldname, self._to_type_name(f.typ)), + f" ('{fieldname}', {self._to_type_name(f.typ)}),", file=self.stream, ) else: print( - " ('%s', %s, %s)," - % (fieldname, self._to_type_name(f.typ), f.bits), + f" ('{fieldname}', {self._to_type_name(f.typ)}, {f.bits}),", file=self.stream, ) print("]", file=self.stream) @@ -524,14 +523,12 @@ def StructureBody(self, body: typedesc.StructureBody) -> None: print(file=self.stream) size = body.struct.size // 8 print( - "assert sizeof(%s) == %s, sizeof(%s)" - % (body.struct.name, size, body.struct.name), + f"assert sizeof({body.struct.name}) == {size}, sizeof({body.struct.name})", file=self.stream, ) align = body.struct.align // 8 print( - "assert alignment(%s) == %s, alignment(%s)" - % (body.struct.name, align, body.struct.name), + f"assert alignment({body.struct.name}) == {align}, alignment({body.struct.name})", file=self.stream, ) @@ -542,27 +539,24 @@ def StructureBody(self, body: typedesc.StructureBody) -> None: print(file=self.stream) self.last_item_class = False - print("%s._methods_ = [" % body.struct.name, file=self.stream) + print(f"{body.struct.name}._methods_ = [", file=self.stream) if body.struct.location: - print("# %s %s" % body.struct.location, file=self.stream) + print(f"# {body.struct.location}", file=self.stream) for m in methods: if m.location: - print(" # %s %s" % m.location, file=self.stream) + print(f" # {m.location}", file=self.stream) print( ( - " COMMETHOD(\n" - " [], \n" - " %s,\n" - " '%s',\n" - ) - % (self._to_type_name(m.returns), m.name), + f" COMMETHOD(\n" + f" [], \n" + f" {self._to_type_name(m.returns)},\n" + f" '{m.name}',\n" + ), file=self.stream, ) for a in m.iterArgTypes(): - print( - " ([], %s),\n" % self._to_type_name(a), file=self.stream - ) + print(f" ([], {self._to_type_name(a)}),\n", file=self.stream) print(" ),", file=self.stream) print("]", file=self.stream) @@ -589,10 +583,10 @@ def TypeLib(self, lib: typedesc.TypeLib) -> None: print(self._to_docstring(lib.doc), file=self.stream) if lib.name: - print(" name = %r" % lib.name, file=self.stream) + print(f" name = {lib.name!r}", file=self.stream) print( - " _reg_typelib_ = (%r, %r, %r)" % (lib.guid, lib.major, lib.minor), + f" _reg_typelib_ = ({lib.guid!r}, {lib.major!r}, {lib.minor!r})", file=self.stream, ) print(file=self.stream) @@ -608,7 +602,7 @@ def External(self, ext: typedesc.External) -> None: def Constant(self, tp: typedesc.Constant) -> None: self.last_item_class = False print( - "%s = %r # Constant %s" % (tp.name, tp.value, self._to_type_name(tp.typ)), + f"{tp.name} = {tp.value!r} # Constant {self._to_type_name(tp.typ)}", file=self.stream, ) self.names.add(tp.name) @@ -650,11 +644,11 @@ def CoClass(self, coclass: typedesc.CoClass) -> None: self.last_item_class = True - print("class %s(CoClass):" % coclass.name, file=self.stream) + print(f"class {coclass.name}(CoClass):", file=self.stream) if coclass.doc: print(self._to_docstring(coclass.doc), file=self.stream) - print(" _reg_clsid_ = GUID(%r)" % coclass.clsid, file=self.stream) - print(" _idlflags_ = %s" % coclass.idlflags, file=self.stream) + print(f" _reg_clsid_ = GUID({coclass.clsid!r})", file=self.stream) + print(f" _idlflags_ = {coclass.idlflags}", file=self.stream) if self.filename is not None: print(" _typelib_path_ = typelib_path", file=self.stream) # X print @@ -663,7 +657,7 @@ def CoClass(self, coclass: typedesc.CoClass) -> None: libid = coclass.tlibattr.guid wMajor, wMinor = coclass.tlibattr.wMajorVerNum, coclass.tlibattr.wMinorVerNum print( - " _reg_typelib_ = (%r, %s, %s)" % (str(libid), wMajor, wMinor), + f" _reg_typelib_ = ({str(libid)!r}, {wMajor}, {wMinor})", file=self.stream, ) print(file=self.stream) @@ -678,13 +672,13 @@ def CoClass(self, coclass: typedesc.CoClass) -> None: if implemented: self.last_item_class = False print( - "%s._com_interfaces_ = [%s]" % (coclass.name, ", ".join(implemented)), + f"{coclass.name}._com_interfaces_ = [{', '.join(implemented)}]", file=self.stream, ) if sources: self.last_item_class = False print( - "%s._outgoing_interfaces_ = [%s]" % (coclass.name, ", ".join(sources)), + f"{coclass.name}._outgoing_interfaces_ = [{', '.join(sources)}]", file=self.stream, ) @@ -773,13 +767,13 @@ def ComInterfaceHead(self, head: typedesc.ComInterfaceHead) -> None: self.last_item_class = True - print("class %s(%s):" % (head.itf.name, basename), file=self.stream) + print(f"class {head.itf.name}({basename}):", file=self.stream) if head.itf.doc: print(self._to_docstring(head.itf.doc), file=self.stream) print(" _case_insensitive_ = True", file=self.stream) - print(" _iid_ = GUID(%r)" % head.itf.iid, file=self.stream) - print(" _idlflags_ = %s" % head.itf.idlflags, file=self.stream) + print(f" _iid_ = GUID({head.itf.iid!r})", file=self.stream) + print(f" _idlflags_ = {head.itf.idlflags}", file=self.stream) if self._is_enuminterface(head.itf): print(file=self.stream) @@ -826,7 +820,7 @@ def ComInterfaceBody(self, body: typedesc.ComInterfaceBody) -> None: print(file=self.stream) self.last_item_class = False - print("%s._methods_ = [" % body.itf.name, file=self.stream) + print(f"{body.itf.name}._methods_ = [", file=self.stream) for m in body.itf.members: if isinstance(m, typedesc.ComMethod): self.make_ComMethod(m, "dual" in body.itf.idlflags) @@ -839,8 +833,8 @@ def ComInterfaceBody(self, body: typedesc.ComInterfaceBody) -> None: "################################################################", file=self.stream, ) - print("# code template for %s implementation" % body.itf.name, file=self.stream) - print("# class %s_Impl(object):" % body.itf.name, file=self.stream) + print(f"# code template for {body.itf.name} implementation", file=self.stream) + print(f"# class {body.itf.name}_Impl(object):", file=self.stream) methods = {} for m in body.itf.members: @@ -862,43 +856,43 @@ def ComInterfaceBody(self, body: typedesc.ComInterfaceBody) -> None: for name, (typ, inargs, outargs, doc) in methods.items(): if typ == 0: # method print( - "# def %s(%s):" % (name, ", ".join(["self"] + inargs)), + f"# def {name}({', '.join(['self'] + inargs)}):", file=self.stream, ) - print("# %r" % (doc or "-no docstring-"), file=self.stream) - print("# #return %s" % (", ".join(outargs)), file=self.stream) + print(f"# {(doc or '-no docstring-')!r}", file=self.stream) + print(f"# #return {', '.join(outargs)}", file=self.stream) elif typ == 1: # propget print("# @property", file=self.stream) print( - "# def %s(%s):" % (name, ", ".join(["self"] + inargs)), + f"# def {name}({', '.join(['self'] + inargs)}):", file=self.stream, ) - print("# %r" % (doc or "-no docstring-"), file=self.stream) - print("# #return %s" % (", ".join(outargs)), file=self.stream) + print(f"# {(doc or '-no docstring-')!r}", file=self.stream) + print(f"# #return {', '.join(outargs)}", file=self.stream) elif typ == 2: # propput print( - "# def _set(%s):" % ", ".join(["self"] + inargs + outargs), + f"# def _set({', '.join(['self'] + inargs + outargs)}):", file=self.stream, ) - print("# %r" % (doc or "-no docstring-"), file=self.stream) + print(f"# {(doc or '-no docstring-')!r}", file=self.stream) print( - "# %s = property(fset = _set, doc = _set.__doc__)" % name, + f"# {name} = property(fset = _set, doc = _set.__doc__)", file=self.stream, ) elif typ == 3: # propget + propput print( - "# def _get(%s):" % ", ".join(["self"] + inargs), + f"# def _get({', '.join(['self'] + inargs)}):", file=self.stream, ) - print("# %r" % (doc or "-no docstring-"), file=self.stream) - print("# #return %s" % (", ".join(outargs)), file=self.stream) + print(f"# {(doc or '-no docstring-')!r}", file=self.stream) + print(f"# #return {', '.join(outargs)}", file=self.stream) print( - "# def _set(%s):" % ", ".join(["self"] + inargs + outargs), + f"# def _set({', '.join(['self'] + inargs + outargs)}):", file=self.stream, ) - print("# %r" % (doc or "-no docstring-"), file=self.stream) + print(f"# {(doc or '-no docstring-')!r}", file=self.stream) print( - "# %s = property(_get, _set, doc = _set.__doc__)" % name, + f"# {name} = property(_get, _set, doc = _set.__doc__)", file=self.stream, ) else: @@ -921,12 +915,12 @@ def DispInterfaceHead(self, head: typedesc.DispInterfaceHead) -> None: self.last_item_class = True - print("class %s(%s):" % (head.itf.name, basename), file=self.stream) + print(f"class {head.itf.name}({basename}):", file=self.stream) if head.itf.doc: print(self._to_docstring(head.itf.doc), file=self.stream) print(" _case_insensitive_ = True", file=self.stream) - print(" _iid_ = GUID(%r)" % head.itf.iid, file=self.stream) - print(" _idlflags_ = %s" % head.itf.idlflags, file=self.stream) + print(f" _iid_ = GUID({head.itf.iid!r})", file=self.stream) + print(f" _idlflags_ = {head.itf.idlflags}", file=self.stream) print(" _methods_ = []", file=self.stream) annotations = typeannotator.DispInterfaceMembersAnnotator(head.itf).generate() @@ -955,7 +949,7 @@ def DispInterfaceBody(self, body: typedesc.DispInterfaceBody) -> None: self.last_item_class = False - print("%s._disp_methods_ = [" % body.itf.name, file=self.stream) + print(f"{body.itf.name}._disp_methods_ = [", file=self.stream) for m in body.itf.members: if isinstance(m, typedesc.DispMethod): self.make_DispMethod(m) diff --git a/comtypes/tools/codegenerator/helpers.py b/comtypes/tools/codegenerator/helpers.py index e99a858c0..89b031058 100644 --- a/comtypes/tools/codegenerator/helpers.py +++ b/comtypes/tools/codegenerator/helpers.py @@ -22,7 +22,7 @@ def __init__(self, memid): self.memid = memid def __repr__(self): - return "dispid(%s)" % self.memid + return f"dispid({self.memid})" class helpstring(object): @@ -30,7 +30,7 @@ def __init__(self, text): self.text = text def __repr__(self): - return "helpstring(%r)" % self.text + return f"helpstring({self.text!r})" # XXX Should this be in ctypes itself? @@ -299,22 +299,22 @@ def __call__(self, t: Any) -> str: # to refer to the type. Assumes the 'from ctypes import *' # namespace is available. if isinstance(t, typedesc.SAFEARRAYType): - return "_midlSAFEARRAY(%s)" % self(t.typ) + return f"_midlSAFEARRAY({self(t.typ)})" # if isinstance(t, typedesc.CoClass): # return "%s._com_interfaces_[0]" % t.name if isinstance(t, typedesc.Typedef): return t.name if isinstance(t, typedesc.PointerType): _t, pcnt = self._inspect_PointerType(t) - return "%s%s%s" % ("POINTER(" * pcnt, self(_t), ")" * pcnt) + return f"{'POINTER(' * pcnt}{self(_t)}{')' * pcnt}" elif isinstance(t, typedesc.ArrayType): - return "%s * %s" % (self(t.typ), int(t.max) + 1) + return f"{self(t.typ)} * {int(t.max) + 1}" elif isinstance(t, typedesc.FunctionType): args = [self(x) for x in [t.returns] + list(t.iterArgTypes())] if "__stdcall__" in t.attributes: - return "WINFUNCTYPE(%s)" % ", ".join(args) + return f"WINFUNCTYPE({', '.join(args)})" else: - return "CFUNCTYPE(%s)" % ", ".join(args) + return f"CFUNCTYPE({', '.join(args)})" elif isinstance(t, typedesc.CvQualifiedType): # const and volatile are ignored return "%s" % self(t.typ) @@ -334,7 +334,7 @@ def __call__(self, t: Any) -> str: # t.symbol_name - symbol to generate # t.tlib - the ITypeLib pointer to the typelibrary containing the symbols definition modname = name_wrapper_module(t.tlib) - return "%s.%s" % (modname, t.symbol_name) + return f"{modname}.{t.symbol_name}" return t.name def _inspect_PointerType(