From fd8bfa7753fe95b9e51a7913f81a1df66cddea25 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 4 Jun 2024 14:17:15 -0400 Subject: [PATCH] Prefer more f-strings and non-printf-style format --- Pythonwin/pywin/framework/app.py | 4 +- Pythonwin/pywin/framework/editor/document.py | 8 +- Pythonwin/pywin/framework/interact.py | 4 +- Pythonwin/pywin/framework/intpyapp.py | 4 +- Pythonwin/pywin/scintilla/IDLEenvironment.py | 4 +- Pythonwin/pywin/scintilla/view.py | 13 +- Pythonwin/pywin/tools/hierlist.py | 4 +- Pythonwin/pywin/tools/regedit.py | 6 +- com/win32com/client/build.py | 20 ++- com/win32com/client/dynamic.py | 12 +- com/win32com/client/gencache.py | 18 +-- com/win32com/client/genpy.py | 19 +-- com/win32com/client/makepy.py | 8 +- com/win32com/client/tlbrowse.py | 4 +- com/win32com/makegw/makegw.py | 52 ++------ com/win32com/makegw/makegwparse.py | 115 ++++-------------- com/win32com/server/dispatcher.py | 8 +- com/win32com/server/register.py | 4 +- com/win32com/test/testDCOM.py | 4 +- com/win32com/test/testDynamic.py | 4 +- com/win32com/test/testvb.py | 23 ++-- com/win32com/test/util.py | 7 +- com/win32com/universal.py | 4 +- com/win32comext/adsi/demos/test.py | 4 +- com/win32comext/axscript/client/framework.py | 4 +- .../shell/demos/servers/empty_volume_cache.py | 8 +- .../shell/demos/servers/folder_view.py | 9 +- ruff.toml | 4 +- setup.py | 3 +- win32/Demos/eventLogDemo.py | 4 +- win32/Demos/win32wnet/testwnet.py | 4 +- win32/Lib/win32evtlogutil.py | 5 +- win32/scripts/VersionStamp/vssutil.py | 7 +- win32/scripts/setup_d.py | 8 +- win32/test/test_odbc.py | 6 +- win32/test/test_win32trace.py | 4 +- 36 files changed, 102 insertions(+), 317 deletions(-) diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index f0c4d6d3e..4d1ae2247 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -334,9 +334,7 @@ def __init__(self, idd=win32ui.IDD_ABOUTBOX): dialog.Dialog.__init__(self, idd) def OnInitDialog(self): - text = "Pythonwin - Python IDE and GUI Framework for Windows.\n\n{}\n\nPython is {}\n\n{}\n\n{}\n\n{}".format( - win32ui.copyright, sys.copyright, scintilla, idle, contributors - ) + text = f"Pythonwin - Python IDE and GUI Framework for Windows.\n\n{win32ui.copyright}\n\nPython is {sys.copyright}\n\n{scintilla}\n\n{idle}\n\n{contributors}" self.SetDlgItemText(win32ui.IDC_EDIT1, text) # Get the build number - written by installers. # For distutils build, read pywin32.version.txt diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index a78cb3eea..c7ff78f09 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -158,17 +158,13 @@ def CheckExternalDocumentUpdated(self): except OSError as exc: if not self.bReportedFileNotFound: print( - "The file '{}' is open for editing, but\nchecking it for changes caused the error: {}".format( - self.GetPathName(), exc.strerror - ) + f"The file '{self.GetPathName()}' is open for editing, but\nchecking it for changes caused the error: {exc.strerror}" ) self.bReportedFileNotFound = 1 return if self.bReportedFileNotFound: print( - "The file '{}' has re-appeared - continuing to watch for changes...".format( - self.GetPathName() - ) + f"The file '{self.GetPathName()}' has re-appeared - continuing to watch for changes..." ) self.bReportedFileNotFound = ( 0 # Once found again we want to start complaining. diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index d93934e0e..50d4b3e4d 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -337,9 +337,7 @@ def Init(self): f"PythonWin {sys.version} on {sys.platform}{suffix}.\n" ) sys.stderr.write( - "Portions {} - see 'Help/About PythonWin' for further copyright information.\n".format( - win32ui.copyright - ) + f"Portions {win32ui.copyright} - see 'Help/About PythonWin' for further copyright information.\n" ) else: sys.stderr.write(self.banner) diff --git a/Pythonwin/pywin/framework/intpyapp.py b/Pythonwin/pywin/framework/intpyapp.py index acbd34cc1..fc4a99e6a 100644 --- a/Pythonwin/pywin/framework/intpyapp.py +++ b/Pythonwin/pywin/framework/intpyapp.py @@ -317,9 +317,7 @@ def ProcessArgs(self, args, dde=None): # pywin.scintilla.document.CScintillaDocument.OnOpenDocument) # segfaults Pythonwin on recent PY3 builds (b228) win32ui.MessageBox( - "No such file: {}\n\nCommand Line: {}".format( - fname, win32api.GetCommandLine() - ), + f"No such file: {fname}\n\nCommand Line: {win32api.GetCommandLine()}", "Open file for edit", win32con.MB_ICONERROR, ) diff --git a/Pythonwin/pywin/scintilla/IDLEenvironment.py b/Pythonwin/pywin/scintilla/IDLEenvironment.py index 773abdc13..e9124d54d 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -517,9 +517,7 @@ def TestGet(fr, to, t, expected): got = t.get(fr, to) if got != expected: print( - "ERROR: get({}, {}) expected {}, but got {}".format( - repr(fr), repr(to), repr(expected), repr(got) - ) + f"ERROR: get({repr(fr)}, {repr(to)}) expected {repr(expected)}, but got {repr(got)}" ) diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index e94148750..8dca7de13 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -334,9 +334,7 @@ def AppendMenu(self, menu, text="", event=None, flags=None, checked=0): if cmdid is None: # No event of that name - no point displaying it. print( - 'View.AppendMenu(): Unknown event "{}" specified for menu text "{}" - ignored'.format( - event, text - ) + f'View.AppendMenu(): Unknown event "{event}" specified for menu text "{text}" - ignored' ) return keyname = configManager.get_key_binding(event, self._GetSubConfigNames()) @@ -512,9 +510,7 @@ def list2dict(l): pass except: win32ui.SetStatusText( - "Error attempting to get object attributes - {}".format( - repr(sys.exc_info()[0]) - ) + f"Error attempting to get object attributes - {repr(sys.exc_info()[0])}" ) # ensure all keys are strings. @@ -824,9 +820,8 @@ def LoadConfiguration(): configManager = ConfigManager(configName) if configManager.last_error: bTryDefault = 0 - msg = "Error loading configuration '{}'\n\n{}".format( - configName, - configManager.last_error, + msg = ( + f"Error loading configuration '{configName}'\n\n{configManager.last_error}" ) if configName != "default": msg += "\n\nThe default configuration will be loaded." diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 7ec29563a..bfe08da4f 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -99,9 +99,7 @@ def HierInit(self, parent, listControl=None): # Used when window first exists. lbid = listControl.GetDlgCtrlID() assert ( self.listBoxId is None or self.listBoxId == lbid - ), "An invalid listbox control ID has been specified (specified as {}, but exists as {})".format( - self.listBoxId, lbid - ) + ), f"An invalid listbox control ID has been specified (specified as {self.listBoxId}, but exists as {lbid})" self.listBoxId = lbid self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL) # self.list.AttachObject(self) diff --git a/Pythonwin/pywin/tools/regedit.py b/Pythonwin/pywin/tools/regedit.py index d8f854ff4..70a6aaac7 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -332,10 +332,8 @@ def __eq__(self, other): ) def __repr__(self): - return "<{} with root={}, key={}>".format( - self.__class__.__name__, - self.keyRoot, - self.keyName, + return ( + f"<{self.__class__.__name__} with root={self.keyRoot}, key={self.keyName}>" ) def GetText(self): diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index 7428c1369..b20c383eb 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -99,10 +99,10 @@ def __init__( def __repr__(self): return ( - "MapEntry(dispid={s.dispid}, desc={s.desc}, names={s.names}, doc={s.doc!r}, " - "resultCLSID={s.resultCLSID}, resultDocumentation={s.resultDocumentation}, " - "wasProperty={s.wasProperty}, hidden={s.hidden}" - ).format(s=self) + f"MapEntry(dispid={self.dispid}, desc={self.desc}, names={self.names}, doc={self.doc!r}, " + f"resultCLSID={self.resultCLSID}, resultDocumentation={self.resultDocumentation}, " + f"wasProperty={self.wasProperty}, hidden={self.hidden}" + ) def GetResultCLSID(self): rc = self.resultCLSID @@ -424,18 +424,12 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): ) s += f"{linePrefix}\tif ret is not None:\n" if rd == pythoncom.VT_UNKNOWN: - s += "{}\t\t# See if this IUnknown is really an IDispatch\n".format( - linePrefix - ) + s += f"{linePrefix}\t\t# See if this IUnknown is really an IDispatch\n" s += f"{linePrefix}\t\ttry:\n" - s += "{}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n".format( - linePrefix - ) + s += f"{linePrefix}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" s += f"{linePrefix}\t\texcept pythoncom.error:\n" s += f"{linePrefix}\t\t\treturn ret\n" - s += "{}\t\tret = Dispatch(ret, {}, {})\n".format( - linePrefix, repr(name), resclsid - ) + s += f"{linePrefix}\t\tret = Dispatch(ret, {repr(name)}, {resclsid})\n" s += "%s\treturn ret" % linePrefix elif rd == pythoncom.VT_BSTR: s = f"{linePrefix}\t# Result is a Unicode object\n" diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index ffe7e9e26..1bfca05a5 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -533,9 +533,7 @@ def _FlagAsMethod(self, *methodNames): def __AttrToID__(self, attr): debug_attr_print( - "Calling GetIDsOfNames for property {} in Dispatch container {}".format( - attr, self._username_ - ) + f"Calling GetIDsOfNames for property {attr} in Dispatch container {self._username_}" ) return self._oleobj_.GetIDsOfNames(0, attr) @@ -638,9 +636,7 @@ def __setattr__(self, attr, value): return # Allow property assignment. debug_attr_print( - "SetAttr called for {}.{}={} on DispatchContainer".format( - self._username_, attr, repr(value) - ) + f"SetAttr called for {self._username_}.{attr}={repr(value)} on DispatchContainer" ) if self._olerepr_: @@ -689,9 +685,7 @@ def __setattr__(self, attr, value): self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) self._olerepr_.propMap[attr] = entry debug_attr_print( - "__setattr__ property {} (id=0x{:x}) in Dispatch container {}".format( - attr, entry.dispid, self._username_ - ) + f"__setattr__ property {attr} (id=0x{entry.dispid:x}) in Dispatch container {self._username_}" ) return except pythoncom.com_error: diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 385478561..6b5d56929 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -415,9 +415,7 @@ def ForgetAboutTypelibInterface(typelib_ob): except KeyError: # Not worth raising an exception - maybe they don't know we only remember for demand generated, etc. print( - "ForgetAboutTypelibInterface:: Warning - type library with info {} is not being remembered!".format( - info - ) + f"ForgetAboutTypelibInterface:: Warning - type library with info {info} is not being remembered!" ) # and drop any version redirects to it for key, val in list(versionRedirectMap.items()): @@ -513,10 +511,7 @@ def EnsureModule( bValidateFile = 0 if module is not None and bValidateFile: assert not is_readonly, "Can't validate in a read-only gencache" - filePathPrefix = "{}\\{}".format( - GetGeneratePath(), - GetGeneratedFileName(typelibCLSID, lcid, major, minor), - ) + filePathPrefix = f"{GetGeneratePath()}\\{GetGeneratedFileName(typelibCLSID, lcid, major, minor)}" filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".py" if __debug__: @@ -550,10 +545,7 @@ def EnsureModule( bReloadNeeded = 1 else: minor = module.MinorVersion - filePathPrefix = "{}\\{}".format( - GetGeneratePath(), - GetGeneratedFileName(typelibCLSID, lcid, major, minor), - ) + filePathPrefix = f"{GetGeneratePath()}\\{GetGeneratedFileName(typelibCLSID, lcid, major, minor)}" filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".pyc" # print("Trying py stat: ", filePath) @@ -748,9 +740,7 @@ def Rebuild(verbose=1): AddModuleToCache(iid, lcid, major, minor, verbose, 0) except: print( - "Could not add module {} - {}: {}".format( - info, sys.exc_info()[0], sys.exc_info()[1] - ) + f"Could not add module {info} - {sys.exc_info()[0]}: {sys.exc_info()[1]}" ) if verbose and len(infos): # Don't bother reporting this when directory is empty! print("Done.") diff --git a/com/win32com/client/genpy.py b/com/win32com/client/genpy.py index 7a4d061f6..87c19ad1b 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -553,9 +553,7 @@ def WriteClassBody(self, generator): if generator.bBuildHidden or not entry.hidden: if entry.GetResultName(): print( - "\t\t# Method '{}' returns object of type '{}'".format( - key, entry.GetResultName() - ), + f"\t\t# Method '{key}' returns object of type '{entry.GetResultName()}'", file=stream, ) details = entry.desc @@ -776,12 +774,7 @@ def WriteClass(self, generator): file=stream, ) print( - "{} = sys.modules['{}.{}'].{}".format( - ref.python_name, - generator.base_mod_name, - ref.python_name, - ref.python_name, - ), + f"{ref.python_name} = sys.modules['{generator.base_mod_name}.{ref.python_name}'].{ref.python_name}", file=stream, ) # And pretend we have written it - the name is now available as if we had! @@ -1190,9 +1183,7 @@ def do_generate(self): for record in recordItems.values(): if record.clsid == pythoncom.IID_NULL: print( - "\t###{}: {}, # Record disabled because it doesn't have a non-null GUID".format( - repr(record.doc[0]), repr(str(record.clsid)) - ), + f"\t###{repr(record.doc[0])}: {repr(str(record.clsid))}, # Record disabled because it doesn't have a non-null GUID", file=stream, ) else: @@ -1372,9 +1363,7 @@ def do_gen_child_item(self, oleitem): oleitem.WriteClass(self) if oleitem.bWritten: print( - 'win32com.client.CLSIDToClass.RegisterCLSID( "{}", {} )'.format( - oleitem.clsid, oleitem.python_name - ), + f'win32com.client.CLSIDToClass.RegisterCLSID( "{oleitem.clsid}", {oleitem.python_name} )', file=self.file, ) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 9f05ab5b5..79e66fb67 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -105,16 +105,12 @@ def ShowInfo(spec): desc = tlb.GetDocumentation(-1)[0] print(desc) print( - " {}, lcid={}, major={}, minor={}".format( - tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor - ) + f" {tlbSpec.clsid}, lcid={tlbSpec.lcid}, major={tlbSpec.major}, minor={tlbSpec.minor}" ) print(" >>> # Use these commands in Python code to auto generate .py support") print(" >>> from win32com.client import gencache") print( - " >>> gencache.EnsureModule('{}', {}, {}, {})".format( - tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor - ) + f" >>> gencache.EnsureModule('{tlbSpec.clsid}', {tlbSpec.lcid}, {tlbSpec.major}, {tlbSpec.minor})" ) diff --git a/com/win32com/client/tlbrowse.py b/com/win32com/client/tlbrowse.py index 1a8d64909..ac83e3432 100644 --- a/com/win32com/client/tlbrowse.py +++ b/com/win32com/client/tlbrowse.py @@ -155,9 +155,7 @@ def _GetMainInfoTypes(self): typeFlags = attr[11] desc = doc[0] - desc += ", Flags=0x{:x}, typeKind=0x{:x}, typeFlags=0x{:x}".format( - flags, typeKind, typeFlags - ) + desc += f", Flags=0x{flags:x}, typeKind=0x{typeKind:x}, typeFlags=0x{typeFlags:x}" if flags & pythoncom.IMPLTYPEFLAG_FSOURCE: desc += "(Source)" infos.append(("Implements", desc)) diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 61e48ab37..8ffdb9306 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -248,20 +248,14 @@ def _write_ifc_cpp(f, interface): argsCOM += ", " + comArgName except makegwparse.error_not_supported as why: f.write( - '// *** The input argument {} of type "{}" was not processed ***\n// Please check the conversion function is appropriate and exists!\n'.format( - arg.name, arg.raw_type - ) + f'// *** The input argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// Please check the conversion function is appropriate and exists!\n' ) f.write(f"\t{arg.type} {arg.name};\n\tPyObject *ob{arg.name};\n") f.write( - "\t// @pyparm |{}||Description for {}\n".format( - arg.type, arg.name, arg.name - ) - ) - codePost += "\tif (bPythonIsHappy && !PyObject_As{}( ob{}, &{} )) bPythonIsHappy = FALSE;\n".format( - arg.type, arg.name, arg.name + f"\t// @pyparm |{arg.name}||Description for {arg.name}\n" ) + codePost += f"\tif (bPythonIsHappy && !PyObject_As{arg.type}( ob{arg.name}, &{arg.name} )) bPythonIsHappy = FALSE;\n" formatChars += "O" argsParseTuple += ", &ob%s" % arg.name @@ -274,9 +268,7 @@ def _write_ifc_cpp(f, interface): f.write(codePobjects) f.write(codeCobjects) f.write( - '\tif ( !PyArg_ParseTuple(args, "{}:{}"{}) )\n\t\treturn NULL;\n'.format( - formatChars, method.name, argsParseTuple - ) + f'\tif ( !PyArg_ParseTuple(args, "{formatChars}:{method.name}"{argsParseTuple}) )\n\t\treturn NULL;\n' ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") @@ -313,16 +305,12 @@ def _write_ifc_cpp(f, interface): codeDecl += argCvt.DeclareParseArgTupleInputConverter() except makegwparse.error_not_supported as why: f.write( - '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( - arg.name, arg.raw_type, why - ) + f'// *** The output argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// {why}\n' ) continue if formatChars: f.write( - '{}\n{}\tPyObject *pyretval = Py_BuildValue("{}"{});\n{}\treturn pyretval;'.format( - codeDecl, codePre, formatChars, codeVarsPass, codePost - ) + f'{codeDecl}\n{codePre}\tPyObject *pyretval = Py_BuildValue("{formatChars}"{codeVarsPass});\n{codePost}\treturn pyretval;' ) else: f.write("\tPy_RETURN_NONE;\n") @@ -332,9 +320,7 @@ def _write_ifc_cpp(f, interface): f.write("static struct PyMethodDef Py%s_methods[] =\n{\n" % name) for method in interface.methods: f.write( - '\t{{ "{}", Py{}::{}, 1 }}, // @pymeth {}|Description of {}\n'.format( - method.name, interface.name, method.name, method.name, method.name - ) + f'\t{{ "{method.name}", Py{interface.name}::{method.name}, 1 }}, // @pymeth {method.name}|Description of {method.name}\n' ) interfacebase = interface.base @@ -383,9 +369,7 @@ class {gname} : public {base_name}, public {name} ) if interface.base != "IUnknown": f.write( - "\t// {}\n\t// *** Manually add {} method decls here\n\n".format( - interface.base, interface.base - ) + f"\t// {interface.base}\n\t// *** Manually add {interface.base} method decls here\n\n" ) else: f.write("\n\n") @@ -472,19 +456,13 @@ def _write_gw_cpp(f, interface): codePost += argCvt.GetBuildForGatewayPostCode() except makegwparse.error_not_supported as why: f.write( - '// *** The input argument {} of type "{}" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - {}\n'.format( - arg.name, arg.raw_type, why - ) + f'// *** The input argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// - Please ensure this conversion function exists, and is appropriate\n// - {why}\n' ) f.write( - "\tPyObject *ob{} = PyObject_From{}({});\n".format( - arg.name, arg.type, arg.name - ) + f"\tPyObject *ob{arg.name} = PyObject_From{arg.type}({arg.name});\n" ) f.write( - '\tif (ob{}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( - arg.name, method.name - ) + f'\tif (ob{arg.name}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{method.name}");\n' ) codePost += "\tPy_DECREF(ob%s);\n" % arg.name formatChars += "O" @@ -530,9 +508,7 @@ def _write_gw_cpp(f, interface): needConversion = needConversion or argCvt.NeedUSES_CONVERSION() except makegwparse.error_not_supported as why: f.write( - '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( - arg.name, arg.raw_type, why - ) + f'// *** The output argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// {why}\n' ) if formatChars: # If I have any to actually process. @@ -543,9 +519,7 @@ def _write_gw_cpp(f, interface): if codePobjects: f.write(codePobjects) f.write( - '\tif (!{}(result, "{}" {}))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( - parseFn, formatChars, argsParseTuple, method.name - ) + f'\tif (!{parseFn}(result, "{formatChars}" {argsParseTuple}))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("{method.name}");\n' ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index 308b0766d..a1e45edd6 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -207,11 +207,7 @@ def GetBuildForGatewayPostCode(self): return s def GetAutoduckString(self): - return "// @pyparm {}|{}||Description for {}".format( - self._GetPythonTypeDesc(), - self.arg.name, - self.arg.name, - ) + return f"// @pyparm {self._GetPythonTypeDesc()}|{self.arg.name}||Description for {self.arg.name}" def _GetPythonTypeDesc(self): "Returns a string with the description of the type. Used for doco purposes" @@ -321,9 +317,7 @@ def GetBuildForInterfacePostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name def GetParsePostCode(self): - return "\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob{}, (ULONG_PTR *){})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 2) - ) + return f"\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob{self.arg.name}, (ULONG_PTR *){self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) @@ -364,9 +358,7 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 2) - ) + return f"\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) @@ -393,9 +385,7 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 2) - ) + return f"\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" def GetInterfaceArgCleanup(self): return "\tSysFreeString(%s);\n" % self.GetIndirectedArgName(None, 1) @@ -427,9 +417,7 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return "\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob{}, {})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 2) - ) + return f"\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" def GetInterfaceArgCleanup(self): return "\tPyWinObject_FreeTCHAR(%s);\n" % self.GetIndirectedArgName(None, 1) @@ -451,10 +439,7 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (!PyWinObject_AsIID(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, - self.arg.name, - ) + return f"\tif (!PyWinObject_AsIID(ob{self.arg.name}, &{self.arg.name})) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): # notdirected = self.GetIndirectedArgName(self.arg.indirectionLevel, 0) @@ -483,11 +468,7 @@ def _GetPythonTypeDesc(self): def GetParsePostCode(self): # variable was declared with only the builtinIndirection ### NOTE: this is an [in] ... so use only builtin - return '\tif (!PyTime_Check(ob{})) {{\n\t\tPyErr_SetString(PyExc_TypeError, "The argument must be a PyTime object");\n\t\tbPythonIsHappy = FALSE;\n\t}}\n\tif (!((PyTime *)ob{})->GetTime({})) bPythonIsHappy = FALSE;\n'.format( - self.arg.name, - self.arg.name, - self.GetIndirectedArgName(self.builtinIndirection, 1), - ) + return f'\tif (!PyTime_Check(ob{self.arg.name})) {{\n\t\tPyErr_SetString(PyExc_TypeError, "The argument must be a PyTime object");\n\t\tbPythonIsHappy = FALSE;\n\t}}\n\tif (!((PyTime *)ob{self.arg.name})->GetTime({self.GetIndirectedArgName(self.builtinIndirection, 1)})) bPythonIsHappy = FALSE;\n' def GetBuildForInterfacePreCode(self): ### use just the builtinIndirection again... @@ -508,18 +489,11 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (!PyCom_PyObjectAsSTATSTG(ob{}, {}, 0/*flags*/)) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 1) - ) + return f"\tif (!PyCom_PyObjectAsSTATSTG(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)}, 0/*flags*/)) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob{} = PyCom_PyObjectFromSTATSTG({});\n\t// STATSTG doco says our responsibility to free\n\tif (({}).pwcsName) CoTaskMemFree(({}).pwcsName);\n".format( - self.arg.name, - self.GetIndirectedArgName(None, 1), - notdirected, - notdirected, - ) + return f"\tob{self.arg.name} = PyCom_PyObjectFromSTATSTG({self.GetIndirectedArgName(None, 1)});\n\t// STATSTG doco says our responsibility to free\n\tif (({notdirected}).pwcsName) CoTaskMemFree(({notdirected}).pwcsName);\n" class ArgFormatterGeneric(ArgFormatterPythonCOM): @@ -527,22 +501,14 @@ def _GetPythonTypeDesc(self): return "" % self.arg.type def GetParsePostCode(self): - return "\tif (!PyObject_As{}(ob{}, &{}) bPythonIsHappy = FALSE;\n".format( - self.arg.type, - self.arg.name, - self.GetIndirectedArgName(None, 1), - ) + return f"\tif (!PyObject_As{self.arg.type}(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)}) bPythonIsHappy = FALSE;\n" def GetInterfaceArgCleanup(self): return f"\tPyObject_Free{self.arg.type}({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob{} = PyObject_From{}({});\n".format( - self.arg.name, - self.arg.type, - self.GetIndirectedArgName(None, 1), - ) + return f"\tob{self.arg.name} = PyObject_From{self.arg.type}({self.GetIndirectedArgName(None, 1)});\n" class ArgFormatterIDLIST(ArgFormatterPythonCOM): @@ -550,19 +516,14 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (bPythonIsHappy && !PyObject_AsPIDL(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 1) - ) + return f"\tif (bPythonIsHappy && !PyObject_AsPIDL(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)})) bPythonIsHappy = FALSE;\n" def GetInterfaceArgCleanup(self): return f"\tPyObject_FreePIDL({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob{} = PyObject_FromPIDL({});\n".format( - self.arg.name, - self.GetIndirectedArgName(None, 1), - ) + return f"\tob{self.arg.name} = PyObject_FromPIDL({self.GetIndirectedArgName(None, 1)});\n" class ArgFormatterHANDLE(ArgFormatterPythonCOM): @@ -570,16 +531,11 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return "\tif (!PyWinObject_AsHANDLE(ob{}, &{}, FALSE) bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 1) - ) + return f"\tif (!PyWinObject_AsHANDLE(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)}, FALSE) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return "\tob{} = PyWinObject_FromHANDLE({});\n".format( - self.arg.name, - self.GetIndirectedArgName(None, 0), - ) + return f"\tob{self.arg.name} = PyWinObject_FromHANDLE({self.GetIndirectedArgName(None, 0)});\n" class ArgFormatterLARGE_INTEGER(ArgFormatterPythonCOM): @@ -590,19 +546,11 @@ def _GetPythonTypeDesc(self): return "" % self.GetKeyName() def GetParsePostCode(self): - return "\tif (!PyWinObject_As{}(ob{}, {})) bPythonIsHappy = FALSE;\n".format( - self.GetKeyName(), - self.arg.name, - self.GetIndirectedArgName(None, 1), - ) + return f"\tif (!PyWinObject_As{self.GetKeyName()}(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)})) bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 0) - return "\tob{} = PyWinObject_From{}({});\n".format( - self.arg.name, - self.GetKeyName(), - notdirected, - ) + return f"\tob{self.arg.name} = PyWinObject_From{self.GetKeyName()}({notdirected});\n" class ArgFormatterULARGE_INTEGER(ArgFormatterLARGE_INTEGER): @@ -612,11 +560,9 @@ def GetKeyName(self): class ArgFormatterInterface(ArgFormatterPythonCOM): def GetInterfaceCppObjectInfo(self): - return self.GetIndirectedArgName( - 1, self.arg.indirectionLevel - ), "{} * {}".format( - self.GetUnconstType(), - self.arg.name, + return ( + self.GetIndirectedArgName(1, self.arg.indirectionLevel), + f"{self.GetUnconstType()} * {self.arg.name}", ) def GetParsePostCode(self): @@ -626,25 +572,14 @@ def GetParsePostCode(self): else: # vs. in params for interface mode. sArg = self.GetIndirectedArgName(1, 2) - return "\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob{}, IID_{}, (void **){}, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n".format( - self.arg.name, self.arg.type, sArg - ) + return f"\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob{self.arg.name}, IID_{self.arg.type}, (void **){sArg}, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n" def GetBuildForInterfacePreCode(self): - return "\tob{} = PyCom_PyObjectFromIUnknown({}, IID_{}, FALSE);\n".format( - self.arg.name, - self.arg.name, - self.arg.type, - ) + return f"\tob{self.arg.name} = PyCom_PyObjectFromIUnknown({self.arg.name}, IID_{self.arg.type}, FALSE);\n" def GetBuildForGatewayPreCode(self): sPrefix = self._IndirectPrefix(self._GetDeclaredIndirection(), 1) - return "\tob{} = PyCom_PyObjectFromIUnknown({}{}, IID_{}, TRUE);\n".format( - self.arg.name, - sPrefix, - self.arg.name, - self.arg.type, - ) + return f"\tob{self.arg.name} = PyCom_PyObjectFromIUnknown({sPrefix}{self.arg.name}, IID_{self.arg.type}, TRUE);\n" def GetInterfaceArgCleanup(self): return f"\tif ({self.arg.name}) {self.arg.name}->Release();\n" @@ -652,9 +587,7 @@ def GetInterfaceArgCleanup(self): class ArgFormatterVARIANT(ArgFormatterPythonCOM): def GetParsePostCode(self): - return "\tif ( !PyCom_VariantFromPyObject(ob{}, {}) )\n\t\tbPythonIsHappy = FALSE;\n".format( - self.arg.name, self.GetIndirectedArgName(None, 1) - ) + return f"\tif ( !PyCom_VariantFromPyObject(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)}) )\n\t\tbPythonIsHappy = FALSE;\n" def GetBuildForGatewayPreCode(self): notdirected = self.GetIndirectedArgName(None, 1) diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index 95791a355..cee0c9d45 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -153,9 +153,7 @@ def _QueryInterface_(self, iid): rc = DispatcherBase._QueryInterface_(self, iid) if not rc: self._trace_( - "in {}._QueryInterface_ with unsupported IID {} ({})".format( - repr(self.policy._obj_), IIDToInterfaceName(iid), iid - ) + f"in {repr(self.policy._obj_)}._QueryInterface_ with unsupported IID {IIDToInterfaceName(iid)} ({iid})" ) return rc @@ -181,9 +179,7 @@ def _GetDispID_(self, name, fdex): def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): self._trace_( - "in {!r}._InvokeEx_-{}{!r} [{:x},{},{!r}]".format( - self.policy._obj_, dispid, args, wFlags, lcid, serviceProvider - ) + f"in {self.policy._obj_!r}._InvokeEx_-{dispid}{args!r} [{wFlags:x},{lcid},{serviceProvider!r}]" ) return DispatcherBase._InvokeEx_( self, dispid, lcid, wFlags, args, kwargs, serviceProvider diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 04ffdca37..3c3a5dcfa 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -594,9 +594,7 @@ def ReExecuteElevated(flags): print(os.path.splitdrive(cwd)[0], file=batf) print('cd "%s"' % os.getcwd(), file=batf) print( - '{} {} > "{}" 2>&1'.format( - win32api.GetShortPathName(exe_to_run), new_params, outfile - ), + f'{win32api.GetShortPathName(exe_to_run)} {new_params} > "{outfile}" 2>&1', file=batf, ) finally: diff --git a/com/win32com/test/testDCOM.py b/com/win32com/test/testDCOM.py index fea4d2040..1160f9b5e 100644 --- a/com/win32com/test/testDCOM.py +++ b/com/win32com/test/testDCOM.py @@ -35,9 +35,7 @@ def test(serverName): actualName = ob.Eval("win32api.GetComputerName()") if serverName.lower() != actualName.lower(): print( - "Error: The object created on server '{}' reported its name as '{}'".format( - serverName, actualName - ) + f"Error: The object created on server '{serverName}' reported its name as '{actualName}'" ) else: print("Object created and tested OK on server '%s'" % serverName) diff --git a/com/win32com/test/testDynamic.py b/com/win32com/test/testDynamic.py index 75765fb87..4e336253e 100644 --- a/com/win32com/test/testDynamic.py +++ b/com/win32com/test/testDynamic.py @@ -65,9 +65,7 @@ def Test(): client.TestSequence = v assert v == list( client.TestSequence - ), "Dynamic sequences not working! {!r}/{!r}".format( - repr(v), repr(client.testSequence) - ) + ), f"Dynamic sequences not working! {repr(v)!r}/{repr(client.testSequence)!r}" client.write("This", "output", "has", "come", "via", "testDynamic.py") # Check our new "_FlagAsMethod" works (kinda!) diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index ca5ab7689..480c1c742 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -336,14 +336,12 @@ def TestArrays(vbtest, bUseGenerated): assert testData == list(resultData) testData = ["hi", "from", "Python"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) - assert testData == list(byRefParam), "Expected '{}', got '{}'".format( - testData, - list(byRefParam), - ) - assert testData == list(resultData), "Expected '{}', got '{}'".format( - testData, - list(resultData), - ) + assert testData == list( + byRefParam + ), f"Expected '{testData}', got '{list(byRefParam)}'" + assert testData == list( + resultData + ), f"Expected '{testData}', got '{list(resultData)}'" # This time, we just pass Unicode, so the result should compare equal testData = [1, 2.0, "3"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) @@ -476,14 +474,7 @@ def TestStructs(vbtest): assert "foo" in str(exc), exc # test repr - it uses repr() of the sub-objects, so check it matches. - expected = ( - "com_struct(int_val={!r}, str_val={!r}, ob_val={!r}, sub_val={!r})".format( - s.int_val, - s.str_val, - s.ob_val, - s.sub_val, - ) - ) + expected = f"com_struct(int_val={s.int_val!r}, str_val={s.str_val!r}, ob_val={s.ob_val!r}, sub_val={s.sub_val!r})" if repr(s) != expected: print("Expected repr:", expected) print("Actual repr :", repr(s)) diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index fd3820a38..d66734a5c 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -54,12 +54,7 @@ def RegisterPythonServer(filename, progids=None, verbose=0): % (sys.version_info.major, sys.version_info.minor), ] if os.path.basename(dll) not in ok_files: - why_not = ( - "{!r} is registered against a different Python version ({})".format( - progid, - dll, - ) - ) + why_not = f"{progid!r} is registered against a different Python version ({dll})" break else: # print(f"Skipping registration of '{filename}' - already registered") diff --git a/com/win32com/universal.py b/com/win32com/universal.py index 14e0aa088..4b759fd70 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -215,9 +215,7 @@ def dispatch( retVal = retVal[1:] else: raise TypeError( - "Expected {} return values, got: {}".format( - len(meth._gw_out_args) + 1, len(retVal) - ) + f"Expected {len(meth._gw_out_args) + 1} return values, got: {len(retVal)}" ) else: retVal = [retVal] diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index 5e7467c22..43c85d6b8 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -158,9 +158,7 @@ def DumpSchema2(): iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface) if verbose_level >= 2: print( - "Class: Name={}, Flags={}, Primary Interface={}".format( - item.Name, desc, iid_name - ) + f"Class: Name={item.Name}, Flags={desc}, Primary Interface={iid_name}" ) nclass += 1 elif item_class == "property": diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index e4c69f7ba..3e836103e 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -766,9 +766,7 @@ def SetScriptSite(self, site): except: traceback.print_exc() trace( - "*** Debugger Manager could not initialize - {}: {}".format( - sys.exc_info()[0], sys.exc_info()[1] - ) + f"*** Debugger Manager could not initialize - {sys.exc_info()[0]}: {sys.exc_info()[1]}" ) self.debugManager = None diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index b5fb32e15..084e97c4f 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -155,9 +155,7 @@ def DllRegisterServer(): # See link at top of file. import winreg - kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( - EmptyVolumeCache._reg_desc_, - ) + kn = rf"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{EmptyVolumeCache._reg_desc_}" key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, kn) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, EmptyVolumeCache._reg_clsid_) @@ -165,9 +163,7 @@ def DllRegisterServer(): def DllUnregisterServer(): import winreg - kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( - EmptyVolumeCache._reg_desc_, - ) + kn = rf"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{EmptyVolumeCache._reg_desc_}" try: key = winreg.DeleteKey(winreg.HKEY_LOCAL_MACHINE, kn) except OSError as details: diff --git a/com/win32comext/shell/demos/servers/folder_view.py b/com/win32comext/shell/demos/servers/folder_view.py index f2d039a15..31287117f 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -821,10 +821,7 @@ def DllRegisterServer(): s = struct.pack("i", attr) winreg.SetValueEx(key, "Attributes", 0, winreg.REG_BINARY, s) # register the context menu handler under the FolderViewSampleType type. - keypath = "{}\\shellex\\ContextMenuHandlers\\{}".format( - ContextMenu._context_menu_type_, - ContextMenu._reg_desc_, - ) + keypath = f"{ContextMenu._context_menu_type_}\\shellex\\ContextMenuHandlers\\{ContextMenu._reg_desc_}" key = winreg.CreateKey(winreg.HKEY_CLASSES_ROOT, keypath) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, ContextMenu._reg_clsid_) propsys.PSRegisterPropertySchema(get_schema_fname()) @@ -837,9 +834,7 @@ def DllUnregisterServer(): paths = [ "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_, - "{}\\shellex\\ContextMenuHandlers\\{}".format( - ContextMenu._context_menu_type_, ContextMenu._reg_desc_ - ), + f"{ContextMenu._context_menu_type_}\\shellex\\ContextMenuHandlers\\{ContextMenu._reg_desc_}", ] for path in paths: try: diff --git a/ruff.toml b/ruff.toml index cd23d7822..8c5daa2a9 100644 --- a/ruff.toml +++ b/ruff.toml @@ -20,7 +20,7 @@ select = [ "UP030", # Use implicit references for positional format fields # TODO: Still lots of manual fixes needed # "UP031", # Use format specifiers instead of percent format - # "UP032", # Use f-string instead of format call + "UP032", # Use f-string instead of format call # Ensure modern type annotation syntax and best practices # Not including those covered by type-checkers @@ -37,7 +37,7 @@ select = [ # Explicit re-exports is fine in __init__.py, still a code smell elsewhere. "__init__.py" = ["PLC0414"] # TODO: Make adodbapi changes in their own PRs -"adodbapi/*" = ["C4", "YTT301", "UP031", "UP032", "ISC002"] +"adodbapi/*" = ["C4", "YTT301", "UP031", "UP032"] [lint.isort] combine-as-imports = true diff --git a/setup.py b/setup.py index a55cbef77..cd7e20dc4 100644 --- a/setup.py +++ b/setup.py @@ -634,8 +634,7 @@ def build_extensions(self): # typical path on newer Visual Studios # prefere corresponding version but accept different version same_version = vcverdir is not None and os.path.isdir( - vcbase[: m.start()] - + r"\VC\Redist\MSVC\{}{}".format(vcverdir, self.plat_dir) + vcbase[: m.start()] + rf"\VC\Redist\MSVC\{vcverdir}{self.plat_dir}" ) redist_globs.append( vcbase[: m.start()] diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index 918e4e081..1e327a80e 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -36,9 +36,7 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): user_desc = None if dumpEachRecord: print( - "Event record from {!r} generated at {}".format( - object.SourceName, object.TimeGenerated.Format() - ) + f"Event record from {object.SourceName!r} generated at {object.TimeGenerated.Format()}" ) if user_desc: print(user_desc) diff --git a/win32/Demos/win32wnet/testwnet.py b/win32/Demos/win32wnet/testwnet.py index 1ddbf7d7a..d13917cf2 100644 --- a/win32/Demos/win32wnet/testwnet.py +++ b/win32/Demos/win32wnet/testwnet.py @@ -85,9 +85,7 @@ def TestConnection(): fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print( - "Universal name of '{}' is '{}'".format( - fname, win32wnet.WNetGetUniversalName(fname) - ) + f"Universal name of '{fname}' is '{win32wnet.WNetGetUniversalName(fname)}'" ) except win32wnet.error as details: print(f"Couldn't get universal name of '{fname}': {details.strerror}") diff --git a/win32/Lib/win32evtlogutil.py b/win32/Lib/win32evtlogutil.py index f7b67a553..cebcadb2d 100644 --- a/win32/Lib/win32evtlogutil.py +++ b/win32/Lib/win32evtlogutil.py @@ -146,10 +146,7 @@ def FormatMessage(eventLogRecord, logType="Application"): # key to look under for the name of the message DLL that contains # the messages we need to extract with FormatMessage. So first get # the event log source name... - keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}\\{}".format( - logType, - eventLogRecord.SourceName, - ) + keyName = f"SYSTEM\\CurrentControlSet\\Services\\EventLog\\{logType}\\{eventLogRecord.SourceName}" # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index ee715757c..ca9d9e344 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -90,12 +90,7 @@ def VssLog(project, linePrefix="", noLabels=5, maxItems=150): if i.Comment: commentDesc = f"\n{linePrefix}\t{i.Comment}" lines.append( - "{}{}\t{}{}".format( - linePrefix, - time.asctime(time.localtime(int(i.Date))), - itemDesc, - commentDesc, - ) + f"{linePrefix}{time.asctime(time.localtime(int(i.Date)))}\t{itemDesc}{commentDesc}" ) if labelNum > noLabels: break diff --git a/win32/scripts/setup_d.py b/win32/scripts/setup_d.py index b458854d1..b72340283 100644 --- a/win32/scripts/setup_d.py +++ b/win32/scripts/setup_d.py @@ -50,9 +50,7 @@ def _docopy(src, dest): if not os.path.isfile(src): src = os.path.join(os.path.split(sys.argv[0])[0], src) print( - "Can not find {} or {} to copy".format( - os.path.abspath(orig_src), os.path.abspath(src) - ) + f"Can not find {os.path.abspath(orig_src)} or {os.path.abspath(src)} to copy" ) return 0 try: @@ -80,9 +78,7 @@ def _doregister(mod_name, dll_name): ) except winreg.error: print( - "Could not find the existing '{}' module registered in the registry".format( - mod_name - ) + f"Could not find the existing '{mod_name}' module registered in the registry" ) usage_and_die(4) # Create the debug key. diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 7b61cb354..30b1ce821 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -43,11 +43,7 @@ def setUp(self): newdb.Close() - conn_str = ( - "Driver={{Microsoft Access Driver (*.mdb)}};dbq={};Uid=;Pwd=;".format( - self.db_filename, - ) - ) + conn_str = f"Driver={{Microsoft Access Driver (*.mdb)}};dbq={self.db_filename};Uid=;Pwd=;" # print("Connection string:", conn_str) self.conn = odbc.odbc(conn_str) # And we expect a 'users' table for these tests. diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index 8cd79dbf3..c74a31605 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -258,9 +258,7 @@ def __init__(self, threadCount): def start(self): procHandle, threadHandle, procId, threadId = win32process.CreateProcess( None, # appName - 'python.exe "{}" /run_test_process {} {}'.format( - this_file, self.BucketCount, self.threadCount - ), + f'python.exe "{this_file}" /run_test_process {self.BucketCount} {self.threadCount}', None, # process security None, # thread security 0, # inherit handles