From fd8bfa7753fe95b9e51a7913f81a1df66cddea25 Mon Sep 17 00:00:00 2001 From: Avasam Date: Tue, 4 Jun 2024 14:17:15 -0400 Subject: [PATCH 1/3] 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 f0c4d6d3eb..4d1ae22477 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 a78cb3eea7..c7ff78f09e 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 d93934e0e0..50d4b3e4d9 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 acbd34cc1f..fc4a99e6ac 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 773abdc130..e9124d54d2 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 e941487509..8dca7de138 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 7ec29563a6..bfe08da4f8 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 d8f854ff45..70a6aaac79 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 7428c13692..b20c383ebd 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 ffe7e9e26b..1bfca05a54 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 3854785615..6b5d569299 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 7a4d061f6f..87c19ad1b6 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 9f05ab5b5a..79e66fb674 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 1a8d64909b..ac83e34324 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 61e48ab375..8ffdb9306f 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 308b0766df..a1e45edd64 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 95791a3554..cee0c9d456 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 04ffdca372..3c3a5dcfa9 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 fea4d20404..1160f9b5eb 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 75765fb876..4e336253e9 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 ca5ab7689c..480c1c742b 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 fd3820a38e..d66734a5c1 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 14e0aa0882..4b759fd70f 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 5e7467c223..43c85d6b83 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 e4c69f7ba8..3e836103e7 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 b5fb32e15e..084e97c4f6 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 f2d039a15a..31287117f2 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 cd23d7822b..8c5daa2a9d 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 a55cbef77c..cd7e20dc40 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 918e4e0816..1e327a80e0 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 1ddbf7d7a4..d13917cf2f 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 f7b67a553c..cebcadb2dc 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 ee715757c6..ca9d9e344b 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 b458854d1a..b723402839 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 7b61cb354d..30b1ce8210 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 8cd79dbf3a..c74a31605c 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 From 921a520a83ba94bf9a9f1b29da6249ff4bfac875 Mon Sep 17 00:00:00 2001 From: Avasam Date: Sat, 14 Dec 2024 13:25:50 -0500 Subject: [PATCH 2/3] git checkout upstream/main **.py --- AutoDuck/Dump2HHC.py | 28 +- AutoDuck/make.py | 4 +- AutoDuck/makedfromi.py | 2 +- AutoDuck/py2d.py | 31 +- Pythonwin/Scintilla/win32/DepGen.py | 45 + Pythonwin/pywin/Demos/app/basictimerapp.py | 2 +- Pythonwin/pywin/Demos/app/demoutils.py | 4 +- Pythonwin/pywin/Demos/cmdserver.py | 2 +- Pythonwin/pywin/Demos/objdoc.py | 2 +- Pythonwin/pywin/Demos/ocx/demoutils.py | 4 +- Pythonwin/pywin/Demos/ocx/ocxserialtest.py | 2 +- Pythonwin/pywin/Demos/ocx/ocxtest.py | 2 +- Pythonwin/pywin/debugger/fail.py | 2 +- Pythonwin/pywin/dialogs/ideoptions.py | 17 +- Pythonwin/pywin/dialogs/list.py | 19 +- Pythonwin/pywin/framework/app.py | 37 +- Pythonwin/pywin/framework/editor/document.py | 8 +- Pythonwin/pywin/framework/editor/editor.py | 12 +- Pythonwin/pywin/framework/editor/vss.py | 4 +- Pythonwin/pywin/framework/interact.py | 4 +- Pythonwin/pywin/framework/intpyapp.py | 10 +- Pythonwin/pywin/framework/scriptutils.py | 8 +- Pythonwin/pywin/framework/sgrepmdi.py | 31 +- Pythonwin/pywin/framework/startup.py | 2 +- Pythonwin/pywin/framework/stdin.py | 1 + Pythonwin/pywin/idle/AutoIndent.py | 6 +- Pythonwin/pywin/idle/CallTips.py | 4 +- Pythonwin/pywin/mfc/activex.py | 3 +- Pythonwin/pywin/mfc/dialog.py | 11 +- Pythonwin/pywin/scintilla/IDLEenvironment.py | 4 +- Pythonwin/pywin/scintilla/config.py | 2 +- Pythonwin/pywin/scintilla/configui.py | 2 +- Pythonwin/pywin/scintilla/document.py | 2 +- Pythonwin/pywin/scintilla/keycodes.py | 4 +- Pythonwin/pywin/scintilla/scintillacon.py | 1256 ++++++++++++++++- Pythonwin/pywin/scintilla/view.py | 13 +- Pythonwin/pywin/tools/browser.py | 15 +- Pythonwin/pywin/tools/hierlist.py | 4 +- Pythonwin/pywin/tools/regedit.py | 6 +- adodbapi/adodbapi.py | 23 +- adodbapi/examples/db_print.py | 2 +- adodbapi/examples/db_table_names.py | 2 +- adodbapi/process_connect_string.py | 14 +- adodbapi/test/adodbapitest.py | 37 +- adodbapi/test/dbapi20.py | 18 +- adodbapi/test/setuptestframework.py | 3 +- com/win32com/client/__init__.py | 4 +- com/win32com/client/build.py | 42 +- com/win32com/client/combrowse.py | 27 +- com/win32com/client/dynamic.py | 23 +- com/win32com/client/gencache.py | 18 +- com/win32com/client/genpy.py | 67 +- com/win32com/client/makepy.py | 15 +- com/win32com/client/selecttlb.py | 3 +- com/win32com/client/tlbrowse.py | 4 +- com/win32com/demos/outlookAddin.py | 4 +- com/win32com/makegw/makegw.py | 156 +- com/win32com/makegw/makegwenum.py | 8 +- com/win32com/makegw/makegwparse.py | 129 +- com/win32com/olectl.py | 2 +- com/win32com/server/connect.py | 4 +- com/win32com/server/dispatcher.py | 46 +- com/win32com/server/exception.py | 14 +- com/win32com/server/policy.py | 2 +- com/win32com/server/register.py | 13 +- com/win32com/servers/interp.py | 14 +- com/win32com/test/GenTestScripts.py | 6 +- com/win32com/test/errorSemantics.py | 6 +- com/win32com/test/testDCOM.py | 4 +- com/win32com/test/testDynamic.py | 6 +- com/win32com/test/testExchange.py | 1 - com/win32com/test/testGatewayAddresses.py | 2 +- com/win32com/test/testMSOffice.py | 18 +- com/win32com/test/testMSOfficeEvents.py | 4 +- com/win32com/test/testPersist.py | 14 +- com/win32com/test/testPippo.py | 5 +- com/win32com/test/testPyComTest.py | 2 +- com/win32com/test/testvb.py | 43 +- com/win32com/test/util.py | 7 +- com/win32com/universal.py | 4 +- com/win32com/util.py | 2 +- com/win32comext/adsi/demos/scp.py | 2 +- com/win32comext/adsi/demos/test.py | 4 +- com/win32comext/axdebug/adb.py | 3 +- com/win32comext/axdebug/codecontainer.py | 2 +- com/win32comext/axdebug/contexts.py | 4 +- com/win32comext/axdebug/documents.py | 5 +- com/win32comext/axdebug/dump.py | 6 +- com/win32comext/axdebug/util.py | 10 +- com/win32comext/axscript/client/debug.py | 7 +- com/win32comext/axscript/client/error.py | 8 +- com/win32comext/axscript/client/framework.py | 12 +- com/win32comext/axscript/client/pyscript.py | 4 +- .../axscript/client/scriptdispatch.py | 6 +- com/win32comext/axscript/test/leakTest.py | 4 +- com/win32comext/mapi/mapitags.py | 2 +- com/win32comext/mapi/mapiutil.py | 2 +- .../shell/demos/servers/empty_volume_cache.py | 8 +- .../shell/demos/servers/folder_view.py | 11 +- .../shell/demos/servers/shell_view.py | 4 +- isapi/samples/redirector_with_filter.py | 1 + isapi/simple.py | 1 + isapi/threaded_extension.py | 1 + pywin32_postinstall.py | 190 +-- setup.py | 382 ++--- win32/Demos/EvtFormatMessage.py | 2 +- win32/Demos/EvtSubscribe_push.py | 9 +- win32/Demos/GetSaveFileName.py | 12 +- win32/Demos/c_extension/setup.py | 2 +- win32/Demos/dde/ddeclient.py | 2 +- win32/Demos/dde/ddeserver.py | 2 +- win32/Demos/eventLogDemo.py | 4 +- win32/Demos/getfilever.py | 2 +- win32/Demos/pipes/runproc.py | 4 +- win32/Demos/security/GetTokenInformation.py | 8 +- win32/Demos/security/set_file_audit.py | 2 +- win32/Demos/security/sspi/simple_auth.py | 4 +- win32/Demos/security/sspi/socket_server.py | 2 +- win32/Demos/win32ts_logoff_disconnected.py | 2 +- win32/Demos/win32wnet/testwnet.py | 6 +- win32/Lib/commctrl.py | 2 +- win32/Lib/pywin32_testutil.py | 4 +- win32/Lib/pywintypes.py | 2 +- win32/Lib/regutil.py | 2 +- win32/Lib/win32con.py | 1 + win32/Lib/win32cryptcon.py | 2 +- win32/Lib/win32evtlogutil.py | 8 +- win32/Lib/win32gui_struct.py | 8 +- win32/Lib/win32pdhquery.py | 15 +- win32/Lib/win32rcparser.py | 1 + win32/Lib/win32timezone.py | 4 +- win32/scripts/VersionStamp/vssutil.py | 7 +- win32/scripts/h2py.py | 186 +++ win32/scripts/regsetup.py | 11 +- win32/scripts/setup_d.py | 10 +- win32/test/handles.py | 18 +- win32/test/test_odbc.py | 6 +- win32/test/test_win32api.py | 10 +- win32/test/test_win32clipboard.py | 5 +- win32/test/test_win32cred.py | 1 - win32/test/test_win32file.py | 11 +- win32/test/test_win32trace.py | 4 +- 142 files changed, 2376 insertions(+), 1117 deletions(-) create mode 100644 Pythonwin/Scintilla/win32/DepGen.py create mode 100644 win32/scripts/h2py.py diff --git a/AutoDuck/Dump2HHC.py b/AutoDuck/Dump2HHC.py index 343bdbca11..32c728c9db 100644 --- a/AutoDuck/Dump2HHC.py +++ b/AutoDuck/Dump2HHC.py @@ -293,9 +293,7 @@ def _genItemsFromDict(dict, cat, output, target, do_children=1): - """.format( - **locals() - ) + """.format(**locals()) ) if not do_children: continue @@ -339,9 +337,7 @@ def genTOC(cats, output, title, target):
    -""".format( - **locals() - ) +""".format(**locals()) ) for cat in cats: @@ -355,9 +351,7 @@ def genTOC(cats, output, title, target):
      - """.format( - **locals() - ) + """.format(**locals()) ) # Next write the overviews for this category output.write( @@ -368,9 +362,7 @@ def genTOC(cats, output, title, target):
        - """.format( - **locals() - ) + """.format(**locals()) ) _genItemsFromDict(cat.overviewTopics, cat, output, target) _genItemsFromDict(cat.extOverviewTopics, cat, output, target) @@ -387,9 +379,7 @@ def genTOC(cats, output, title, target):
          -""".format( - **locals() - ) +""".format(**locals()) ) _genItemsFromDict(cat.modules, cat, output, target) output.write( @@ -404,9 +394,7 @@ def genTOC(cats, output, title, target): -
            """.format( - **locals() - ) +
              """.format(**locals()) ) # Don't show 'children' for objects - params etc don't need their own child nodes! _genItemsFromDict(cat.objects, cat, output, target, do_children=0) @@ -423,9 +411,7 @@ def genTOC(cats, output, title, target):
                -""".format( - **locals() - ) +""".format(**locals()) ) _genItemsFromDict(cat.constants, cat, output, target) output.write( diff --git a/AutoDuck/make.py b/AutoDuck/make.py index d3b9ee39a3..c205aa0da8 100644 --- a/AutoDuck/make.py +++ b/AutoDuck/make.py @@ -26,5 +26,7 @@ ).splitlines()[-1] subprocess.run( - [nmake, "-E", "-f", "pywin32.mak"], cwd=os.path.dirname(sys.argv[0]), check=True + [nmake, f'PYTHON="{sys.executable}"', "-E", "-f", "pywin32.mak"], + cwd=os.path.dirname(sys.argv[0]), + check=True, ) diff --git a/AutoDuck/makedfromi.py b/AutoDuck/makedfromi.py index 4fd2f44acb..53edf0111a 100644 --- a/AutoDuck/makedfromi.py +++ b/AutoDuck/makedfromi.py @@ -20,7 +20,7 @@ def GetComments(line, lineNo, lines): if len(data) != 2: break if data[0].strip(): - break # Not a continutation! + break # Not a continuation! if data[1].strip().startswith("@"): # new command break diff --git a/AutoDuck/py2d.py b/AutoDuck/py2d.py index 647fb7121e..5000b5ec69 100644 --- a/AutoDuck/py2d.py +++ b/AutoDuck/py2d.py @@ -7,9 +7,6 @@ def ad_escape(s): return re.sub(r"([^<]*)<([^>]*)>", r"\g<1>\\<\g<2>\\>", s) -Print = __builtins__.__dict__["print"] - - class DocInfo: def __init__(self, name, ob): self.name = name @@ -75,7 +72,7 @@ def format_desc(desc): # 'first_para_of_docstring' # '@comm next para of docstring' # '@comm next para of docstring' ... etc - # BUT - also handling enbedded doctests, where we write + # BUT - also handling embedded doctests, where we write # '@iex >>> etc.' if not desc: return "" @@ -112,30 +109,30 @@ def build_module(fp, mod_name): elif name.upper() == name and isinstance(ob, (int, str)): constants.append((name, ob)) info = BuildInfo(mod_name, mod) - Print(f"// @module {mod_name}|{format_desc(info.desc)}", file=fp) + print(f"// @module {mod_name}|{format_desc(info.desc)}", file=fp) functions = [f for f in functions if should_build_function(f)] for ob in functions: - Print(f"// @pymeth {ob.name}|{ob.short_desc}", file=fp) + print(f"// @pymeth {ob.name}|{ob.short_desc}", file=fp) for ob in classes: # only classes with docstrings get printed. if not ob.ob.__doc__: continue ob_name = mod_name + "." + ob.name - Print(f"// @pyclass {ob.name}|{ob.short_desc}", file=fp) + print(f"// @pyclass {ob.name}|{ob.short_desc}", file=fp) for ob in functions: - Print( + print( f"// @pymethod |{mod_name}|{ob.name}|{format_desc(ob.desc)}", file=fp, ) for ai in BuildArgInfos(ob.ob): - Print(f"// @pyparm |{ai.name}|{ai.default}|{ai.short_desc}", file=fp) + print(f"// @pyparm |{ai.name}|{ai.default}|{ai.short_desc}", file=fp) for ob in classes: # only classes with docstrings get printed. if not ob.ob.__doc__: continue ob_name = mod_name + "." + ob.name - Print(f"// @object {ob_name}|{format_desc(ob.desc)}", file=fp) + print(f"// @object {ob_name}|{format_desc(ob.desc)}", file=fp) func_infos = [] # We need to iter the keys then to a getattr() so the funky descriptor # things work. @@ -146,20 +143,20 @@ def build_module(fp, mod_name): if should_build_function(info): func_infos.append(info) for fi in func_infos: - Print(f"// @pymeth {fi.name}|{fi.short_desc}", file=fp) + print(f"// @pymeth {fi.name}|{fi.short_desc}", file=fp) for fi in func_infos: - Print( + print( f"// @pymethod |{ob_name}|{fi.name}|{format_desc(fi.desc)}", file=fp, ) if hasattr(fi.ob, "im_self") and fi.ob.im_self is ob.ob: - Print("// @comm This is a @classmethod.", file=fp) - Print( + print("// @comm This is a @classmethod.", file=fp) + print( f"// @pymethod |{ob_name}|{fi.name}|{format_desc(fi.desc)}", file=fp, ) for ai in BuildArgInfos(fi.ob): - Print( + print( f"// @pyparm |{ai.name}|{ai.default}|{ai.short_desc}", file=fp, ) @@ -168,11 +165,11 @@ def build_module(fp, mod_name): desc = f"{name} = {val!r}" if isinstance(val, int): desc += f" (0x{val:x})" - Print(f"// @const {mod_name}|{name}|{desc}", file=fp) + print(f"// @const {mod_name}|{name}|{desc}", file=fp) def main(fp, args): - Print("// @doc", file=fp) + print("// @doc", file=fp) for arg in args: build_module(sys.stdout, arg) diff --git a/Pythonwin/Scintilla/win32/DepGen.py b/Pythonwin/Scintilla/win32/DepGen.py new file mode 100644 index 0000000000..4ab6f6f31b --- /dev/null +++ b/Pythonwin/Scintilla/win32/DepGen.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +# DepGen.py - produce a make dependencies file for Scintilla +# Copyright 2019 by Neil Hodgson +# The License.txt file describes the conditions under which this software may be distributed. +# Requires Python 3.6 or later + +import sys + +sys.path.append("..") + +from scripts import Dependencies + +topComment = "# Created by DepGen.py. To recreate, run DepGen.py.\n" + + +def Generate(): + sources = ["../src/*.cxx", "../lexlib/*.cxx", "../lexers/*.cxx"] + includes = ["../include", "../src", "../lexlib"] + + # Create the dependencies file for g++ + deps = Dependencies.FindDependencies( + ["../win32/*.cxx"] + sources, ["../win32"] + includes, ".o", "../win32/" + ) + + # Add ScintillaBaseL as the same as ScintillaBase + deps = Dependencies.InsertSynonym(deps, "ScintillaBase.o", "ScintillaBaseL.o") + + # Add CatalogueL as the same as Catalogue + deps = Dependencies.InsertSynonym(deps, "Catalogue.o", "CatalogueL.o") + + Dependencies.UpdateDependencies("../win32/deps.mak", deps, topComment) + + # Create the dependencies file for MSVC + + # Place the objects in $(DIR_O) and change extension from ".o" to ".obj" + deps = [ + ["$(DIR_O)/" + Dependencies.PathStem(obj) + ".obj", headers] + for obj, headers in deps + ] + + Dependencies.UpdateDependencies("../win32/nmdeps.mak", deps, topComment) + + +if __name__ == "__main__": + Generate() diff --git a/Pythonwin/pywin/Demos/app/basictimerapp.py b/Pythonwin/pywin/Demos/app/basictimerapp.py index c60271b952..6a21715de1 100644 --- a/Pythonwin/pywin/Demos/app/basictimerapp.py +++ b/Pythonwin/pywin/Demos/app/basictimerapp.py @@ -129,7 +129,7 @@ def OnTimer(self, id, timeVal): print("The last operation completed successfully.") except: t, v, tb = sys.exc_info() - str = f"Failed: {t}: {repr(v)}" + str = f"Failed: {t}: {v!r}" print(str) self.oldErr.write(str) tb = None # Prevent cycle diff --git a/Pythonwin/pywin/Demos/app/demoutils.py b/Pythonwin/pywin/Demos/app/demoutils.py index ee1fefcfad..171549a0eb 100644 --- a/Pythonwin/pywin/Demos/app/demoutils.py +++ b/Pythonwin/pywin/Demos/app/demoutils.py @@ -60,6 +60,4 @@ def NeedApp(): if __name__ == "__main__": - import demoutils - - demoutils.NotAScript() + NotAScript() diff --git a/Pythonwin/pywin/Demos/cmdserver.py b/Pythonwin/pywin/Demos/cmdserver.py index d3e24f4017..cb751f0847 100644 --- a/Pythonwin/pywin/Demos/cmdserver.py +++ b/Pythonwin/pywin/Demos/cmdserver.py @@ -47,7 +47,7 @@ def write(self, str): def Test(): num = 1 while num < 1000: - print("Hello there no " + str(num)) + print("Hello there no", num) win32api.Sleep(50) num += 1 diff --git a/Pythonwin/pywin/Demos/objdoc.py b/Pythonwin/pywin/Demos/objdoc.py index fff7925360..99261a03e1 100644 --- a/Pythonwin/pywin/Demos/objdoc.py +++ b/Pythonwin/pywin/Demos/objdoc.py @@ -41,7 +41,7 @@ def OnOpenDocument(self, name): class object_view(docview.EditView): def OnInitialUpdate(self): - self.ReplaceSel("Object is %s" % repr(self.GetDocument().object)) + self.ReplaceSel(f"Object is {self.GetDocument().object!r}") def demo(): diff --git a/Pythonwin/pywin/Demos/ocx/demoutils.py b/Pythonwin/pywin/Demos/ocx/demoutils.py index 80d8c2450b..171549a0eb 100644 --- a/Pythonwin/pywin/Demos/ocx/demoutils.py +++ b/Pythonwin/pywin/Demos/ocx/demoutils.py @@ -60,6 +60,4 @@ def NeedApp(): if __name__ == "__main__": - from . import demoutils - - demoutils.NotAScript() + NotAScript() diff --git a/Pythonwin/pywin/Demos/ocx/ocxserialtest.py b/Pythonwin/pywin/Demos/ocx/ocxserialtest.py index 326d312c8f..ae17127ec5 100644 --- a/Pythonwin/pywin/Demos/ocx/ocxserialtest.py +++ b/Pythonwin/pywin/Demos/ocx/ocxserialtest.py @@ -127,7 +127,7 @@ def test(): if __name__ == "__main__": - from . import demoutils + import demoutils if demoutils.NeedGoodGUI(): test() diff --git a/Pythonwin/pywin/Demos/ocx/ocxtest.py b/Pythonwin/pywin/Demos/ocx/ocxtest.py index 695f708b88..31a63a3e16 100644 --- a/Pythonwin/pywin/Demos/ocx/ocxtest.py +++ b/Pythonwin/pywin/Demos/ocx/ocxtest.py @@ -238,7 +238,7 @@ def demo(): if __name__ == "__main__": - from . import demoutils + import demoutils if demoutils.NeedGoodGUI(): testall() diff --git a/Pythonwin/pywin/debugger/fail.py b/Pythonwin/pywin/debugger/fail.py index dbb5320ae4..0afc70eb37 100644 --- a/Pythonwin/pywin/debugger/fail.py +++ b/Pythonwin/pywin/debugger/fail.py @@ -28,7 +28,7 @@ def b(): b = 1 pywin.debugger.set_trace() # After importing or running this module, you are likely to be - # sitting at the next line. This is because we explicitely + # sitting at the next line. This is because we explicitly # broke into the debugger using the "set_trace() function # "pywin.debugger.brk()" is a shorter alias for this. c() diff --git a/Pythonwin/pywin/dialogs/ideoptions.py b/Pythonwin/pywin/dialogs/ideoptions.py index cee8ee8931..da7c4c5779 100644 --- a/Pythonwin/pywin/dialogs/ideoptions.py +++ b/Pythonwin/pywin/dialogs/ideoptions.py @@ -114,26 +114,23 @@ def ChangeFormat(self, fmtAttribute, fmt): def OnFormatTitle(self, command, code): fmt = self.GetFormat(interact.formatTitle) if fmt: - formatTitle = fmt + interact.formatTitle = fmt interact.SaveFontPreferences() def OnFormatInput(self, command, code): - global formatInput - fmt = self.GetFormat(formatInput) + fmt = self.GetFormat(interact.formatInput) if fmt: - formatInput = fmt + interact.formatInput = fmt interact.SaveFontPreferences() def OnFormatOutput(self, command, code): - global formatOutput - fmt = self.GetFormat(formatOutput) + fmt = self.GetFormat(interact.formatOutput) if fmt: - formatOutput = fmt + interact.formatOutput = fmt interact.SaveFontPreferences() def OnFormatError(self, command, code): - global formatOutputError - fmt = self.GetFormat(formatOutputError) + fmt = self.GetFormat(interact.formatOutputError) if fmt: - formatOutputError = fmt + interact.formatOutputError = fmt interact.SaveFontPreferences() diff --git a/Pythonwin/pywin/dialogs/list.py b/Pythonwin/pywin/dialogs/list.py index 4e1877955d..377a7cade9 100644 --- a/Pythonwin/pywin/dialogs/list.py +++ b/Pythonwin/pywin/dialogs/list.py @@ -44,14 +44,17 @@ def OnListClick(self, id, code): return 1 def OnListItemChange(self, std, extra): - (hwndFrom, idFrom, code), ( - itemNotify, - sub, - newState, - oldState, - change, - point, - lparam, + ( + (hwndFrom, idFrom, code), + ( + itemNotify, + sub, + newState, + oldState, + change, + point, + lparam, + ), ) = (std, extra) oldSel = (oldState & commctrl.LVIS_SELECTED) != 0 newSel = (newState & commctrl.LVIS_SELECTED) != 0 diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index a7d183d067..931a007871 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -2,12 +2,15 @@ # The application is responsible for managing the main frame window. # # We also grab the FileOpen command, to invoke our Python editor -" The PythonWin application code. Manages most aspects of MDI, etc " +"The PythonWin application code. Manages most aspects of MDI, etc" + from __future__ import annotations +import builtins import os import sys import traceback +import warnings from typing import TYPE_CHECKING import regutil @@ -170,7 +173,7 @@ def OnIdle(self, count): try: thisRet = handler(handler, count) except: - print("Idle handler %s failed" % (repr(handler))) + print(f"Idle handler {handler!r} failed") traceback.print_exc() print("Idle handler removed from list") try: @@ -329,7 +332,7 @@ def _GetRegistryValue(key, val, default=None): return default -scintilla = "Scintilla is Copyright 1998-2008 Neil Hodgson (http://www.scintilla.org)" +scintilla = "Scintilla is Copyright 1998-2020 Neil Hodgson (https://www.scintilla.org)" idle = "This program uses IDLE extensions by Guido van Rossum, Tim Peters and others." contributors = "Thanks to the following people for making significant contributions: Roger Upole, Sidnei da Silva, Sam Rushing, Curt Hagenlocher, Dave Brennan, Roger Burnham, Gordon McMillan, Neil Hodgson, Laramie Leavitt. (let me know if I have forgotten you!)" @@ -340,29 +343,21 @@ def __init__(self, idd=win32ui.IDD_ABOUTBOX): dialog.Dialog.__init__(self, idd) def OnInitDialog(self): - 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}" + 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 + ) self.SetDlgItemText(win32ui.IDC_EDIT1, text) - # Get the build number - written by installers. - # For distutils build, read pywin32.version.txt import sysconfig site_packages = sysconfig.get_paths()["platlib"] + version_path = os.path.join(site_packages, "pywin32.version.txt") try: - build_no = ( - open(os.path.join(site_packages, "pywin32.version.txt")).read().strip() - ) - ver = "pywin32 build %s" % build_no + with open(version_path) as f: + ver = "pywin32 build %s" % f.read().strip() except OSError: ver = None - if ver is None: - # See if we are Part of Active Python - ver = _GetRegistryValue( - "SOFTWARE\\ActiveState\\ActivePython", "CurrentVersion" - ) - if ver is not None: - ver = f"ActivePython build {ver}" - if ver is None: - ver = "" + if not ver: + warnings.warn(f"Could not read pywin32's version from '{version_path}'") self.SetDlgItemText(win32ui.IDC_ABOUT_VERSION, ver) self.HookCommand(self.OnButHomePage, win32ui.IDC_BUTTON1) @@ -390,9 +385,7 @@ def Win32Input(prompt=None): def HookInput(): - import code - - sys.modules["builtins"].input = Win32Input + builtins.input = Win32Input def HaveGoodGUI(): diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index 2fba319452..1579dbfe62 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -157,13 +157,17 @@ def CheckExternalDocumentUpdated(self): except OSError as exc: if not self.bReportedFileNotFound: print( - f"The file '{self.GetPathName()}' is open for editing, but\nchecking it for changes caused the error: {exc.strerror}" + "The file '{}' is open for editing, but\nchecking it for changes caused the error: {}".format( + self.GetPathName(), exc.strerror + ) ) self.bReportedFileNotFound = 1 return if self.bReportedFileNotFound: print( - f"The file '{self.GetPathName()}' has re-appeared - continuing to watch for changes..." + "The file '{}' has re-appeared - continuing to watch for changes...".format( + self.GetPathName() + ) ) self.bReportedFileNotFound = ( 0 # Once found again we want to start complaining. diff --git a/Pythonwin/pywin/framework/editor/editor.py b/Pythonwin/pywin/framework/editor/editor.py index facb5b23f1..a83f20312a 100644 --- a/Pythonwin/pywin/framework/editor/editor.py +++ b/Pythonwin/pywin/framework/editor/editor.py @@ -9,7 +9,7 @@ # We now support reloading of externally modified documented # (eg, presumably by some other process, such as source control or # another editor. -# We also suport auto-loading of externally modified files. +# We also support auto-loading of externally modified files. # - if the current document has not been modified in this # editor, but has been modified on disk, then the file # can be automatically reloaded. @@ -19,7 +19,6 @@ import re -import regex import win32api import win32con import win32ui @@ -36,8 +35,8 @@ # from pywin.mfc.docview import EditView as ParentEditorView # from pywin.mfc.docview import Document as ParentEditorDocument -patImport = regex.symcomp(r"import \(.*\)") -patIndent = regex.compile(r"^\([ \t]*[~ \t]\)") +patImport = re.compile(r"import (?P.*)") +patIndent = re.compile(r"^([ \t]*[~ \t])") ID_LOCATE_FILE = 0xE200 ID_GOTO_LINE = 0xE2001 @@ -364,9 +363,10 @@ def OnRClick(self, params): # look for a module name line = self._obj_.GetLine().strip() flags = win32con.MF_STRING | win32con.MF_ENABLED - if patImport.match(line) == len(line): + matchResult = patImport.match(line) + if matchResult and matchResult[0] == line: menu.AppendMenu( - flags, ID_LOCATE_FILE, "&Locate %s.py" % patImport.group("name") + flags, ID_LOCATE_FILE, "&Locate %s.py" % matchResult.group("name") ) menu.AppendMenu(win32con.MF_SEPARATOR) menu.AppendMenu(flags, win32ui.ID_EDIT_UNDO, "&Undo") diff --git a/Pythonwin/pywin/framework/editor/vss.py b/Pythonwin/pywin/framework/editor/vss.py index 4a772acef2..c357c58a4b 100644 --- a/Pythonwin/pywin/framework/editor/vss.py +++ b/Pythonwin/pywin/framework/editor/vss.py @@ -86,7 +86,7 @@ def CheckoutFile(fileName): project, vssFname, database = rc if g_sourceSafe is None: g_sourceSafe = win32com.client.Dispatch("SourceSafe") - # SS seems a bit wierd. It defaults the arguments as empty strings, but + # SS seems a bit weird. It defaults the arguments as empty strings, but # then complains when they are used - so we pass "Missing" if not database: database = pythoncom.Missing @@ -99,6 +99,6 @@ def CheckoutFile(fileName): except: typ, val, tb = sys.exc_info() traceback.print_exc() - win32ui.MessageBox(f"{str(typ)} - {str(val)}", "Error checking out file") + win32ui.MessageBox(f"{typ} - {val}", "Error checking out file") tb = None # Cleanup a cycle return ok diff --git a/Pythonwin/pywin/framework/interact.py b/Pythonwin/pywin/framework/interact.py index 195a59a3b7..c26bf6e829 100644 --- a/Pythonwin/pywin/framework/interact.py +++ b/Pythonwin/pywin/framework/interact.py @@ -337,7 +337,9 @@ def Init(self): f"PythonWin {sys.version} on {sys.platform}{suffix}.\n" ) sys.stderr.write( - f"Portions {win32ui.copyright} - see 'Help/About PythonWin' for further copyright information.\n" + "Portions {} - see 'Help/About PythonWin' for further copyright information.\n".format( + win32ui.copyright + ) ) else: sys.stderr.write(self.banner) diff --git a/Pythonwin/pywin/framework/intpyapp.py b/Pythonwin/pywin/framework/intpyapp.py index fc4a99e6ac..7d0ef2d289 100644 --- a/Pythonwin/pywin/framework/intpyapp.py +++ b/Pythonwin/pywin/framework/intpyapp.py @@ -317,13 +317,15 @@ def ProcessArgs(self, args, dde=None): # pywin.scintilla.document.CScintillaDocument.OnOpenDocument) # segfaults Pythonwin on recent PY3 builds (b228) win32ui.MessageBox( - f"No such file: {fname}\n\nCommand Line: {win32api.GetCommandLine()}", + "No such file: {}\n\nCommand Line: {}".format( + fname, win32api.GetCommandLine() + ), "Open file for edit", win32con.MB_ICONERROR, ) continue if dde: - dde.Exec("win32ui.GetApp().OpenDocumentFile(%s)" % (repr(fname))) + dde.Exec(f"win32ui.GetApp().OpenDocumentFile({fname!r})") else: win32ui.GetApp().OpenDocumentFile(par) elif argType == "/rundlg": @@ -371,7 +373,7 @@ def LoadSystemModules(self): def LoadUserModules(self, moduleNames=None): # Load the users modules. if moduleNames is None: - default = "pywin.framework.sgrepmdi,pywin.framework.mdi_pychecker" + default = "pywin.framework.sgrepmdi" moduleNames = win32ui.GetProfileVal("Python", "Startup Modules", default) self.DoLoadModules(moduleNames) @@ -465,7 +467,7 @@ def OnFileLocate(self, id, code): else: win32ui.GetApp().OpenDocumentFile(newName) - # Display all the "options" proprety pages we can find + # Display all the "options" property pages we can find def OnViewOptions(self, id, code): win32ui.InitRichEdit() sheet = dialog.PropertySheet("Pythonwin Options") diff --git a/Pythonwin/pywin/framework/scriptutils.py b/Pythonwin/pywin/framework/scriptutils.py index fe57113ddd..abf5a40c13 100644 --- a/Pythonwin/pywin/framework/scriptutils.py +++ b/Pythonwin/pywin/framework/scriptutils.py @@ -27,9 +27,7 @@ debugging_options = """No debugging Step-through in the debugger Run in the debugger -Post-Mortem of unhandled exceptions""".split( - "\n" -) +Post-Mortem of unhandled exceptions""".split("\n") byte_cr = b"\r" byte_lf = b"\n" @@ -614,10 +612,10 @@ def _HandlePythonFailure(what, syntaxErrorPathName=None): _JumpToPosition(fileName, line, col) except (TypeError, ValueError): msg = str(details) - win32ui.SetStatusText("Failed to " + what + " - syntax error - %s" % msg) + win32ui.SetStatusText(f"Failed to {what} - syntax error - {msg}") else: traceback.print_exc() - win32ui.SetStatusText("Failed to " + what + " - " + str(details)) + win32ui.SetStatusText(f"Failed to {what} - {details}") tb = None # Clean up a cycle. diff --git a/Pythonwin/pywin/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index f318f731f8..7635005b82 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -127,8 +127,6 @@ def __radd__(self, other): # Group(1) is the filename, group(2) is the lineno. -# regexGrepResult=regex.compile(r"^\([a-zA-Z]:.*\)(\([0-9]+\))") - regexGrep = re.compile(r"^([a-zA-Z]:[^(]*)\(([0-9]+)\)") # these are the atom numbers defined by Windows for basic dialog controls @@ -264,11 +262,11 @@ def doSearch(self): self.dp = dirpath(self.dirpattern, self.recurse) self.SetTitle(f"Grep for {self.greppattern} in {self.filpattern}") # self.text = [] - self.GetFirstView().Append("#Search " + self.dirpattern + "\n") + self.GetFirstView().Append(f"#Search {self.dirpattern}\n") if self.verbose: - self.GetFirstView().Append("# =" + repr(self.dp.dirs) + "\n") - self.GetFirstView().Append("# Files " + self.filpattern + "\n") - self.GetFirstView().Append("# For " + self.greppattern + "\n") + self.GetFirstView().Append(f"# ={self.dp.dirs!r}\n") + self.GetFirstView().Append(f"# Files {self.filpattern}\n") + self.GetFirstView().Append(f"# For {self.greppattern}\n") self.fplist = self.filpattern.split(";") if self.casesensitive: self.pat = re.compile(self.greppattern) @@ -301,7 +299,7 @@ def SearchFile(self, handler, count): for i in range(len(lines)): line = lines[i] if self.pat.search(line) is not None: - self.GetFirstView().Append(f + "(" + repr(i + 1) + ") " + line) + self.GetFirstView().Append(f"{f} ({i + 1!r}) {line}") else: self.fndx = -1 self.fpndx += 1 @@ -327,18 +325,13 @@ def SearchFile(self, handler, count): return 1 def GetParams(self): - return ( - self.dirpattern - + "\t" - + self.filpattern - + "\t" - + self.greppattern - + "\t" - + repr(self.casesensitive) - + "\t" - + repr(self.recurse) - + "\t" - + repr(self.verbose) + return "{}\t{}\t{}\t{!r}\t{!r}\t{!r}".format( + self.dirpattern, + self.filpattern, + self.greppattern, + self.casesensitive, + self.recurse, + self.verbose, ) def OnSaveDocument(self, filename): diff --git a/Pythonwin/pywin/framework/startup.py b/Pythonwin/pywin/framework/startup.py index 3cc6c01691..ca7a44d874 100644 --- a/Pythonwin/pywin/framework/startup.py +++ b/Pythonwin/pywin/framework/startup.py @@ -50,7 +50,7 @@ pywin.__path__[0] = win32ui.FullPath(pywin.__path__[0]) pywin.framework.__path__[0] = win32ui.FullPath(pywin.framework.__path__[0]) -# make a few wierd sys values. This is so later we can clobber sys.argv to trick +# make a few weird sys values. This is so later we can clobber sys.argv to trick # scripts when running under a GUI environment. moduleName = "pywin.framework.intpyapp" diff --git a/Pythonwin/pywin/framework/stdin.py b/Pythonwin/pywin/framework/stdin.py index 1614fbe917..b7d71dc19e 100644 --- a/Pythonwin/pywin/framework/stdin.py +++ b/Pythonwin/pywin/framework/stdin.py @@ -16,6 +16,7 @@ import sys sys.stdin = sys.stdin.real_file """ + import sys get_input_line = input diff --git a/Pythonwin/pywin/idle/AutoIndent.py b/Pythonwin/pywin/idle/AutoIndent.py index e433097e91..a4e8e2ffa7 100644 --- a/Pythonwin/pywin/idle/AutoIndent.py +++ b/Pythonwin/pywin/idle/AutoIndent.py @@ -101,7 +101,7 @@ def config(self, **options): elif key == "context_use_ps1": self.context_use_ps1 = value else: - raise KeyError("bad option name: %s" % repr(key)) + raise KeyError(f"bad option name: {key!r}") # If ispythonsource and guess are true, guess a good value for # indentwidth based on file content (if possible), and if @@ -230,7 +230,7 @@ def newline_and_indent_event(self, event): y = PyParse.Parser(self.indentwidth, self.tabwidth) for context in self.num_context_lines: startat = max(lno - context, 1) - startatindex = repr(startat) + ".0" + startatindex = f"{startat!r}.0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) bod = y.find_good_parse_start( @@ -500,7 +500,7 @@ def readline(self): val = "" else: i = self.i = self.i + 1 - mark = repr(i) + ".0" + mark = f"{i!r}.0" if self.text.compare(mark, ">=", "end"): val = "" else: diff --git a/Pythonwin/pywin/idle/CallTips.py b/Pythonwin/pywin/idle/CallTips.py index c158479551..03a14c2553 100644 --- a/Pythonwin/pywin/idle/CallTips.py +++ b/Pythonwin/pywin/idle/CallTips.py @@ -207,9 +207,7 @@ def test(tests): expected = t.__doc__ + "\n" + t.__doc__ if get_arg_text(t) != expected: failed.append(t) - print( - f"{t} - expected {repr(expected)}, but got {repr(get_arg_text(t))}" - ) + print(f"{t} - expected {expected!r}, but got {get_arg_text(t)!r}") print("%d of %d tests failed" % (len(failed), len(tests))) tc = TC() diff --git a/Pythonwin/pywin/mfc/activex.py b/Pythonwin/pywin/mfc/activex.py index f3d9939a4b..3d0207aca5 100644 --- a/Pythonwin/pywin/mfc/activex.py +++ b/Pythonwin/pywin/mfc/activex.py @@ -1,5 +1,4 @@ -"""Support for ActiveX control hosting in Pythonwin. -""" +"""Support for ActiveX control hosting in Pythonwin.""" import win32ui import win32uiole diff --git a/Pythonwin/pywin/mfc/dialog.py b/Pythonwin/pywin/mfc/dialog.py index 4edb141236..be4888a4c9 100644 --- a/Pythonwin/pywin/mfc/dialog.py +++ b/Pythonwin/pywin/mfc/dialog.py @@ -8,8 +8,7 @@ import win32con import win32ui -# sob - 2to3 doesn't see this as a relative import :( -from pywin.mfc import window +from . import window def dllFromDll(dllid): @@ -258,13 +257,11 @@ def GetSimpleInput(prompt, defValue="", title=None): # uses a simple dialog to return a string object. if title is None: title = win32ui.GetMainFrame().GetWindowText() - # 2to3 insists on converting 'Dialog.__init__' to 'tkinter.dialog...' - DlgBaseClass = Dialog - class DlgSimpleInput(DlgBaseClass): + class DlgSimpleInput(Dialog): def __init__(self, prompt, defValue, title): self.title = title - DlgBaseClass.__init__(self, win32ui.IDD_SIMPLE_INPUT) + Dialog.__init__(self, win32ui.IDD_SIMPLE_INPUT) self.AddDDX(win32ui.IDC_EDIT1, "result") self.AddDDX(win32ui.IDC_PROMPT1, "prompt") self._obj_.data["result"] = defValue @@ -272,7 +269,7 @@ def __init__(self, prompt, defValue, title): def OnInitDialog(self): self.SetWindowText(self.title) - return DlgBaseClass.OnInitDialog(self) + return Dialog.OnInitDialog(self) dlg = DlgSimpleInput(prompt, defValue, title) if dlg.DoModal() != win32con.IDOK: diff --git a/Pythonwin/pywin/scintilla/IDLEenvironment.py b/Pythonwin/pywin/scintilla/IDLEenvironment.py index e9124d54d2..7ce93331d3 100644 --- a/Pythonwin/pywin/scintilla/IDLEenvironment.py +++ b/Pythonwin/pywin/scintilla/IDLEenvironment.py @@ -516,9 +516,7 @@ def TestCheck(index, edit, expected=None): def TestGet(fr, to, t, expected): got = t.get(fr, to) if got != expected: - print( - f"ERROR: get({repr(fr)}, {repr(to)}) expected {repr(expected)}, but got {repr(got)}" - ) + print(f"ERROR: get({fr!r}, {to!r}) expected {expected!r}, but got {got!r}") def test(): diff --git a/Pythonwin/pywin/scintilla/config.py b/Pythonwin/pywin/scintilla/config.py index e67368dfed..45c2a095c0 100644 --- a/Pythonwin/pywin/scintilla/config.py +++ b/Pythonwin/pywin/scintilla/config.py @@ -42,7 +42,7 @@ def split_line(line, lineno): sep_pos = line.rfind("=") if sep_pos == -1: if line.strip(): - print("Warning: Line %d: %s is an invalid entry" % (lineno, repr(line))) + print(f"Warning: Line {lineno}: {line!r} is an invalid entry") return None, None return "", "" return line[:sep_pos].strip(), line[sep_pos + 1 :].strip() diff --git a/Pythonwin/pywin/scintilla/configui.py b/Pythonwin/pywin/scintilla/configui.py index c8e81257ab..2a2f60cc1e 100644 --- a/Pythonwin/pywin/scintilla/configui.py +++ b/Pythonwin/pywin/scintilla/configui.py @@ -62,7 +62,7 @@ def OnInitDialog(self): # Convert the rect size rect = self.MapDialogRect((5, 5, 120, 75)) self.scintilla.CreateWindow(style, rect, self, 111) - self.HookNotify(self.OnBraceMatch, scintillacon.SCN_CHECKBRACE) + self.HookNotify(self.OnBraceMatch, scintillacon.SCN_UPDATEUI) self.scintilla.HookKeyStroke(self.OnEsc, 27) self.scintilla.SCISetViewWS(1) self.pos_bstart = self.pos_bend = self.pos_bbad = 0 diff --git a/Pythonwin/pywin/scintilla/document.py b/Pythonwin/pywin/scintilla/document.py index fca20f0607..3b2ee8189b 100644 --- a/Pythonwin/pywin/scintilla/document.py +++ b/Pythonwin/pywin/scintilla/document.py @@ -198,7 +198,7 @@ def FinalizeViewCreation(self, view): def HookViewNotifications(self, view): parent = view.GetParentFrame() parent.HookNotify( - ViewNotifyDelegate(self, "OnBraceMatch"), scintillacon.SCN_CHECKBRACE + ViewNotifyDelegate(self, "OnBraceMatch"), scintillacon.SCN_UPDATEUI ) parent.HookNotify( ViewNotifyDelegate(self, "OnMarginClick"), scintillacon.SCN_MARGINCLICK diff --git a/Pythonwin/pywin/scintilla/keycodes.py b/Pythonwin/pywin/scintilla/keycodes.py index d94ccda474..44c8ee6ec6 100644 --- a/Pythonwin/pywin/scintilla/keycodes.py +++ b/Pythonwin/pywin/scintilla/keycodes.py @@ -70,7 +70,7 @@ def get_vk(chardesc): def parse_key_name(name): - name += "-" # Add a sentinal + name += "-" # Add a sentinel start = pos = 0 max = len(name) toks = [] @@ -144,7 +144,7 @@ def make_key_name(vk, flags): def _psc(char): sc, mods = get_vk(char) - print("Char %s -> %d -> %s" % (repr(char), sc, key_code_to_name.get(sc))) + print(f"Char {char!r} -> {sc} -> {key_code_to_name.get(sc)}") def test1(): diff --git a/Pythonwin/pywin/scintilla/scintillacon.py b/Pythonwin/pywin/scintilla/scintillacon.py index 5a79fde17b..bfde2d7c50 100644 --- a/Pythonwin/pywin/scintilla/scintillacon.py +++ b/Pythonwin/pywin/scintilla/scintillacon.py @@ -1,5 +1,4 @@ # Generated by h2py from Include\scintilla.h - INVALID_POSITION = -1 SCI_START = 2000 SCI_OPTIONAL_START = 3000 @@ -7,7 +6,9 @@ SCI_ADDTEXT = 2001 SCI_ADDSTYLEDTEXT = 2002 SCI_INSERTTEXT = 2003 +SCI_CHANGEINSERTION = 2672 SCI_CLEARALL = 2004 +SCI_DELETERANGE = 2645 SCI_CLEARDOCUMENTSTYLE = 2005 SCI_GETLENGTH = 2006 SCI_GETCHARAT = 2007 @@ -22,12 +23,19 @@ SCI_CANREDO = 2016 SCI_MARKERLINEFROMHANDLE = 2017 SCI_MARKERDELETEHANDLE = 2018 +SCI_MARKERHANDLEFROMLINE = 2732 +SCI_MARKERNUMBERFROMLINE = 2733 SCI_GETUNDOCOLLECTION = 2019 SCWS_INVISIBLE = 0 SCWS_VISIBLEALWAYS = 1 SCWS_VISIBLEAFTERINDENT = 2 +SCWS_VISIBLEONLYININDENT = 3 SCI_GETVIEWWS = 2020 SCI_SETVIEWWS = 2021 +SCTD_LONGARROW = 0 +SCTD_STRIKEOUT = 1 +SCI_GETTABDRAWMODE = 2698 +SCI_SETTABDRAWMODE = 2699 SCI_POSITIONFROMPOINT = 2022 SCI_POSITIONFROMPOINTCLOSE = 2023 SCI_GOTOLINE = 2024 @@ -47,10 +55,24 @@ SCI_SETBUFFEREDDRAW = 2035 SCI_SETTABWIDTH = 2036 SCI_GETTABWIDTH = 2121 +SCI_SETTABMINIMUMWIDTH = 2724 +SCI_GETTABMINIMUMWIDTH = 2725 +SCI_CLEARTABSTOPS = 2675 +SCI_ADDTABSTOP = 2676 +SCI_GETNEXTTABSTOP = 2677 SC_CP_UTF8 = 65001 -SC_CP_DBCS = 1 SCI_SETCODEPAGE = 2037 -SCI_SETUSEPALETTE = 2039 +SC_IME_WINDOWED = 0 +SC_IME_INLINE = 1 +SCI_GETIMEINTERACTION = 2678 +SCI_SETIMEINTERACTION = 2679 +SC_ALPHA_TRANSPARENT = 0 +SC_ALPHA_OPAQUE = 255 +SC_ALPHA_NOALPHA = 256 +SC_CURSORNORMAL = -1 +SC_CURSORARROW = 2 +SC_CURSORWAIT = 4 +SC_CURSORREVERSEARROW = 7 MARKER_MAX = 31 SC_MARK_CIRCLE = 0 SC_MARK_ROUNDRECT = 1 @@ -80,6 +102,11 @@ SC_MARK_PIXMAP = 25 SC_MARK_FULLRECT = 26 SC_MARK_LEFTRECT = 27 +SC_MARK_AVAILABLE = 28 +SC_MARK_UNDERLINE = 29 +SC_MARK_RGBAIMAGE = 30 +SC_MARK_BOOKMARK = 31 +SC_MARK_VERTICALBOOKMARK = 32 SC_MARK_CHARACTER = 10000 SC_MARKNUM_FOLDEREND = 25 SC_MARKNUM_FOLDEROPENMID = 26 @@ -88,10 +115,12 @@ SC_MARKNUM_FOLDERSUB = 29 SC_MARKNUM_FOLDER = 30 SC_MARKNUM_FOLDEROPEN = 31 -SC_MASK_FOLDERS = -33554432 +SC_MASK_FOLDERS = 0xFE000000 SCI_MARKERDEFINE = 2040 SCI_MARKERSETFORE = 2041 SCI_MARKERSETBACK = 2042 +SCI_MARKERSETBACKSELECTED = 2292 +SCI_MARKERENABLEHIGHLIGHT = 2293 SCI_MARKERADD = 2043 SCI_MARKERDELETE = 2044 SCI_MARKERDELETEALL = 2045 @@ -101,10 +130,14 @@ SCI_MARKERDEFINEPIXMAP = 2049 SCI_MARKERADDSET = 2466 SCI_MARKERSETALPHA = 2476 +SC_MAX_MARGIN = 4 SC_MARGIN_SYMBOL = 0 SC_MARGIN_NUMBER = 1 SC_MARGIN_BACK = 2 SC_MARGIN_FORE = 3 +SC_MARGIN_TEXT = 4 +SC_MARGIN_RTEXT = 5 +SC_MARGIN_COLOUR = 6 SCI_SETMARGINTYPEN = 2240 SCI_GETMARGINTYPEN = 2241 SCI_SETMARGINWIDTHN = 2242 @@ -113,6 +146,12 @@ SCI_GETMARGINMASKN = 2245 SCI_SETMARGINSENSITIVEN = 2246 SCI_GETMARGINSENSITIVEN = 2247 +SCI_SETMARGINCURSORN = 2248 +SCI_GETMARGINCURSORN = 2249 +SCI_SETMARGINBACKN = 2250 +SCI_GETMARGINBACKN = 2251 +SCI_SETMARGINS = 2252 +SCI_GETMARGINS = 2253 STYLE_DEFAULT = 32 STYLE_LINENUMBER = 33 STYLE_BRACELIGHT = 34 @@ -120,6 +159,7 @@ STYLE_CONTROLCHAR = 36 STYLE_INDENTGUIDE = 37 STYLE_CALLTIP = 38 +STYLE_FOLDDISPLAYTEXT = 39 STYLE_LASTPREDEFINED = 39 STYLE_MAX = 255 SC_CHARSET_ANSI = 0 @@ -133,6 +173,7 @@ SC_CHARSET_MAC = 77 SC_CHARSET_OEM = 255 SC_CHARSET_RUSSIAN = 204 +SC_CHARSET_OEM866 = 866 SC_CHARSET_CYRILLIC = 1251 SC_CHARSET_SHIFTJIS = 128 SC_CHARSET_SYMBOL = 2 @@ -156,6 +197,7 @@ SC_CASE_MIXED = 0 SC_CASE_UPPER = 1 SC_CASE_LOWER = 2 +SC_CASE_CAMEL = 3 SCI_STYLEGETFORE = 2481 SCI_STYLEGETBACK = 2482 SCI_STYLEGETBOLD = 2483 @@ -170,6 +212,14 @@ SCI_STYLEGETCHANGEABLE = 2492 SCI_STYLEGETHOTSPOT = 2493 SCI_STYLESETCASE = 2060 +SC_FONT_SIZE_MULTIPLIER = 100 +SCI_STYLESETSIZEFRACTIONAL = 2061 +SCI_STYLEGETSIZEFRACTIONAL = 2062 +SC_WEIGHT_NORMAL = 400 +SC_WEIGHT_SEMIBOLD = 600 +SC_WEIGHT_BOLD = 700 +SCI_STYLESETWEIGHT = 2063 +SCI_STYLEGETWEIGHT = 2064 SCI_STYLESETCHARACTERSET = 2066 SCI_STYLESETHOTSPOT = 2409 SCI_SETSELFORE = 2067 @@ -187,6 +237,9 @@ SCI_GETCARETPERIOD = 2075 SCI_SETCARETPERIOD = 2076 SCI_SETWORDCHARS = 2077 +SCI_GETWORDCHARS = 2646 +SCI_SETCHARACTERCATEGORYOPTIMIZATION = 2720 +SCI_GETCHARACTERCATEGORYOPTIMIZATION = 2721 SCI_BEGINUNDOACTION = 2078 SCI_ENDUNDOACTION = 2079 INDIC_PLAIN = 0 @@ -197,22 +250,47 @@ INDIC_HIDDEN = 5 INDIC_BOX = 6 INDIC_ROUNDBOX = 7 -INDIC_MAX = 31 +INDIC_STRAIGHTBOX = 8 +INDIC_DASH = 9 +INDIC_DOTS = 10 +INDIC_SQUIGGLELOW = 11 +INDIC_DOTBOX = 12 +INDIC_SQUIGGLEPIXMAP = 13 +INDIC_COMPOSITIONTHICK = 14 +INDIC_COMPOSITIONTHIN = 15 +INDIC_FULLBOX = 16 +INDIC_TEXTFORE = 17 +INDIC_POINT = 18 +INDIC_POINTCHARACTER = 19 +INDIC_GRADIENT = 20 +INDIC_GRADIENTCENTRE = 21 INDIC_CONTAINER = 8 -INDIC0_MASK = 0x20 -INDIC1_MASK = 0x40 -INDIC2_MASK = 0x80 -INDICS_MASK = 0xE0 +INDIC_IME = 32 +INDIC_IME_MAX = 35 +INDIC_MAX = 35 +INDICATOR_CONTAINER = 8 +INDICATOR_IME = 32 +INDICATOR_IME_MAX = 35 +INDICATOR_MAX = 35 SCI_INDICSETSTYLE = 2080 SCI_INDICGETSTYLE = 2081 SCI_INDICSETFORE = 2082 SCI_INDICGETFORE = 2083 SCI_INDICSETUNDER = 2510 SCI_INDICGETUNDER = 2511 +SCI_INDICSETHOVERSTYLE = 2680 +SCI_INDICGETHOVERSTYLE = 2681 +SCI_INDICSETHOVERFORE = 2682 +SCI_INDICGETHOVERFORE = 2683 +SC_INDICVALUEBIT = 0x1000000 +SC_INDICVALUEMASK = 0xFFFFFF +SC_INDICFLAG_VALUEFORE = 1 +SCI_INDICSETFLAGS = 2684 +SCI_INDICGETFLAGS = 2685 SCI_SETWHITESPACEFORE = 2084 SCI_SETWHITESPACEBACK = 2085 -SCI_SETSTYLEBITS = 2090 -SCI_GETSTYLEBITS = 2091 +SCI_SETWHITESPACESIZE = 2086 +SCI_GETWHITESPACESIZE = 2087 SCI_SETLINESTATE = 2092 SCI_GETLINESTATE = 2093 SCI_GETMAXLINESTATE = 2094 @@ -220,6 +298,8 @@ SCI_SETCARETLINEVISIBLE = 2096 SCI_GETCARETLINEBACK = 2097 SCI_SETCARETLINEBACK = 2098 +SCI_GETCARETLINEFRAME = 2704 +SCI_SETCARETLINEFRAME = 2705 SCI_STYLESETCHANGEABLE = 2099 SCI_AUTOCSHOW = 2100 SCI_AUTOCCANCEL = 2101 @@ -258,6 +338,8 @@ SCI_GETLINEINDENTATION = 2127 SCI_GETLINEINDENTPOSITION = 2128 SCI_GETCOLUMN = 2129 +SCI_COUNTCHARACTERS = 2633 +SCI_COUNTCODEUNITS = 2715 SCI_SETHSCROLLBAR = 2130 SCI_GETHSCROLLBAR = 2131 SC_IV_NONE = 0 @@ -271,13 +353,13 @@ SCI_GETLINEENDPOSITION = 2136 SCI_GETCODEPAGE = 2137 SCI_GETCARETFORE = 2138 -SCI_GETUSEPALETTE = 2139 SCI_GETREADONLY = 2140 SCI_SETCURRENTPOS = 2141 SCI_SETSELECTIONSTART = 2142 SCI_GETSELECTIONSTART = 2143 SCI_SETSELECTIONEND = 2144 SCI_GETSELECTIONEND = 2145 +SCI_SETEMPTYSELECTION = 2556 SCI_SETPRINTMAGNIFICATION = 2146 SCI_GETPRINTMAGNIFICATION = 2147 SC_PRINT_NORMAL = 0 @@ -285,13 +367,16 @@ SC_PRINT_BLACKONWHITE = 2 SC_PRINT_COLOURONWHITE = 3 SC_PRINT_COLOURONWHITEDEFAULTBG = 4 +SC_PRINT_SCREENCOLOURS = 5 SCI_SETPRINTCOLOURMODE = 2148 SCI_GETPRINTCOLOURMODE = 2149 -SCFIND_WHOLEWORD = 2 -SCFIND_MATCHCASE = 4 +SCFIND_NONE = 0x0 +SCFIND_WHOLEWORD = 0x2 +SCFIND_MATCHCASE = 0x4 SCFIND_WORDSTART = 0x00100000 SCFIND_REGEXP = 0x00200000 SCFIND_POSIX = 0x00400000 +SCFIND_CXX11REGEX = 0x00800000 SCI_FINDTEXT = 2150 SCI_FORMATRANGE = 2151 SCI_GETFIRSTVISIBLELINE = 2152 @@ -312,6 +397,7 @@ SCI_POSITIONFROMLINE = 2167 SCI_LINESCROLL = 2168 SCI_SCROLLCARET = 2169 +SCI_SCROLLRANGE = 2569 SCI_REPLACESEL = 2170 SCI_SETREADONLY = 2171 SCI_NULL = 2172 @@ -334,8 +420,16 @@ SCI_GETCARETWIDTH = 2189 SCI_SETTARGETSTART = 2190 SCI_GETTARGETSTART = 2191 +SCI_SETTARGETSTARTVIRTUALSPACE = 2728 +SCI_GETTARGETSTARTVIRTUALSPACE = 2729 SCI_SETTARGETEND = 2192 SCI_GETTARGETEND = 2193 +SCI_SETTARGETENDVIRTUALSPACE = 2730 +SCI_GETTARGETENDVIRTUALSPACE = 2731 +SCI_SETTARGETRANGE = 2686 +SCI_GETTARGETTEXT = 2687 +SCI_TARGETFROMSELECTION = 2287 +SCI_TARGETWHOLEDOCUMENT = 2690 SCI_REPLACETARGET = 2194 SCI_REPLACETARGETRE = 2195 SCI_SEARCHINTARGET = 2197 @@ -345,21 +439,19 @@ SCI_CALLTIPCANCEL = 2201 SCI_CALLTIPACTIVE = 2202 SCI_CALLTIPPOSSTART = 2203 +SCI_CALLTIPSETPOSSTART = 2214 SCI_CALLTIPSETHLT = 2204 SCI_CALLTIPSETBACK = 2205 SCI_CALLTIPSETFORE = 2206 SCI_CALLTIPSETFOREHLT = 2207 SCI_CALLTIPUSESTYLE = 2212 +SCI_CALLTIPSETPOSITION = 2213 SCI_VISIBLEFROMDOCLINE = 2220 SCI_DOCLINEFROMVISIBLE = 2221 SCI_WRAPCOUNT = 2235 SC_FOLDLEVELBASE = 0x400 SC_FOLDLEVELWHITEFLAG = 0x1000 SC_FOLDLEVELHEADERFLAG = 0x2000 -SC_FOLDLEVELBOXHEADERFLAG = 0x4000 -SC_FOLDLEVELBOXFOOTERFLAG = 0x8000 -SC_FOLDLEVELCONTRACTED = 0x10000 -SC_FOLDLEVELUNINDENT = 0x20000 SC_FOLDLEVELNUMBERMASK = 0x0FFF SCI_SETFOLDLEVEL = 2222 SCI_GETFOLDLEVEL = 2223 @@ -368,16 +460,37 @@ SCI_SHOWLINES = 2226 SCI_HIDELINES = 2227 SCI_GETLINEVISIBLE = 2228 +SCI_GETALLLINESVISIBLE = 2236 SCI_SETFOLDEXPANDED = 2229 SCI_GETFOLDEXPANDED = 2230 SCI_TOGGLEFOLD = 2231 +SCI_TOGGLEFOLDSHOWTEXT = 2700 +SC_FOLDDISPLAYTEXT_HIDDEN = 0 +SC_FOLDDISPLAYTEXT_STANDARD = 1 +SC_FOLDDISPLAYTEXT_BOXED = 2 +SCI_FOLDDISPLAYTEXTSETSTYLE = 2701 +SCI_FOLDDISPLAYTEXTGETSTYLE = 2707 +SCI_SETDEFAULTFOLDDISPLAYTEXT = 2722 +SCI_GETDEFAULTFOLDDISPLAYTEXT = 2723 +SC_FOLDACTION_CONTRACT = 0 +SC_FOLDACTION_EXPAND = 1 +SC_FOLDACTION_TOGGLE = 2 +SCI_FOLDLINE = 2237 +SCI_FOLDCHILDREN = 2238 +SCI_EXPANDCHILDREN = 2239 +SCI_FOLDALL = 2662 SCI_ENSUREVISIBLE = 2232 +SC_AUTOMATICFOLD_SHOW = 0x0001 +SC_AUTOMATICFOLD_CLICK = 0x0002 +SC_AUTOMATICFOLD_CHANGE = 0x0004 +SCI_SETAUTOMATICFOLD = 2663 +SCI_GETAUTOMATICFOLD = 2664 SC_FOLDFLAG_LINEBEFORE_EXPANDED = 0x0002 SC_FOLDFLAG_LINEBEFORE_CONTRACTED = 0x0004 SC_FOLDFLAG_LINEAFTER_EXPANDED = 0x0008 SC_FOLDFLAG_LINEAFTER_CONTRACTED = 0x0010 SC_FOLDFLAG_LEVELNUMBERS = 0x0040 -SC_FOLDFLAG_BOX = 0x0001 +SC_FOLDFLAG_LINESTATE = 0x0080 SCI_SETFOLDFLAGS = 2233 SCI_ENSUREVISIBLEENFORCEPOLICY = 2234 SCI_SETTABINDENTS = 2260 @@ -389,14 +502,23 @@ SCI_GETMOUSEDWELLTIME = 2265 SCI_WORDSTARTPOSITION = 2266 SCI_WORDENDPOSITION = 2267 +SCI_ISRANGEWORD = 2691 +SC_IDLESTYLING_NONE = 0 +SC_IDLESTYLING_TOVISIBLE = 1 +SC_IDLESTYLING_AFTERVISIBLE = 2 +SC_IDLESTYLING_ALL = 3 +SCI_SETIDLESTYLING = 2692 +SCI_GETIDLESTYLING = 2693 SC_WRAP_NONE = 0 SC_WRAP_WORD = 1 SC_WRAP_CHAR = 2 +SC_WRAP_WHITESPACE = 3 SCI_SETWRAPMODE = 2268 SCI_GETWRAPMODE = 2269 SC_WRAPVISUALFLAG_NONE = 0x0000 SC_WRAPVISUALFLAG_END = 0x0001 SC_WRAPVISUALFLAG_START = 0x0002 +SC_WRAPVISUALFLAG_MARGIN = 0x0004 SCI_SETWRAPVISUALFLAGS = 2460 SCI_GETWRAPVISUALFLAGS = 2461 SC_WRAPVISUALFLAGLOC_DEFAULT = 0x0000 @@ -406,6 +528,12 @@ SCI_GETWRAPVISUALFLAGSLOCATION = 2463 SCI_SETWRAPSTARTINDENT = 2464 SCI_GETWRAPSTARTINDENT = 2465 +SC_WRAPINDENT_FIXED = 0 +SC_WRAPINDENT_SAME = 1 +SC_WRAPINDENT_INDENT = 2 +SC_WRAPINDENT_DEEPINDENT = 3 +SCI_SETWRAPINDENTMODE = 2472 +SCI_GETWRAPINDENTMODE = 2473 SC_CACHE_NONE = 0 SC_CACHE_CARET = 1 SC_CACHE_PAGE = 2 @@ -423,13 +551,32 @@ SCI_SETVSCROLLBAR = 2280 SCI_GETVSCROLLBAR = 2281 SCI_APPENDTEXT = 2282 -SCI_GETTWOPHASEDRAW = 2283 -SCI_SETTWOPHASEDRAW = 2284 -SCI_TARGETFROMSELECTION = 2287 +SC_PHASES_ONE = 0 +SC_PHASES_TWO = 1 +SC_PHASES_MULTIPLE = 2 +SCI_GETPHASESDRAW = 2673 +SCI_SETPHASESDRAW = 2674 +SC_EFF_QUALITY_MASK = 0xF +SC_EFF_QUALITY_DEFAULT = 0 +SC_EFF_QUALITY_NON_ANTIALIASED = 1 +SC_EFF_QUALITY_ANTIALIASED = 2 +SC_EFF_QUALITY_LCD_OPTIMIZED = 3 +SCI_SETFONTQUALITY = 2611 +SCI_GETFONTQUALITY = 2612 +SCI_SETFIRSTVISIBLELINE = 2613 +SC_MULTIPASTE_ONCE = 0 +SC_MULTIPASTE_EACH = 1 +SCI_SETMULTIPASTE = 2614 +SCI_GETMULTIPASTE = 2615 +SCI_GETTAG = 2616 SCI_LINESJOIN = 2288 SCI_LINESSPLIT = 2289 SCI_SETFOLDMARGINCOLOUR = 2290 SCI_SETFOLDMARGINHICOLOUR = 2291 +SC_ACCESSIBILITY_DISABLED = 0 +SC_ACCESSIBILITY_ENABLED = 1 +SCI_SETACCESSIBILITY = 2702 +SCI_GETACCESSIBILITY = 2703 SCI_LINEDOWN = 2300 SCI_LINEDOWNEXTEND = 2301 SCI_LINEUP = 2302 @@ -471,6 +618,7 @@ SCI_LINECUT = 2337 SCI_LINEDELETE = 2338 SCI_LINETRANSPOSE = 2339 +SCI_LINEREVERSE = 2354 SCI_LINEDUPLICATE = 2404 SCI_LOWERCASE = 2340 SCI_UPPERCASE = 2341 @@ -491,8 +639,11 @@ SCI_MOVECARETINSIDEVIEW = 2401 SCI_LINELENGTH = 2350 SCI_BRACEHIGHLIGHT = 2351 +SCI_BRACEHIGHLIGHTINDICATOR = 2498 SCI_BRACEBADLIGHT = 2352 +SCI_BRACEBADLIGHTINDICATOR = 2499 SCI_BRACEMATCH = 2353 +SCI_BRACEMATCHNEXT = 2369 SCI_GETVIEWEOL = 2355 SCI_SETVIEWEOL = 2356 SCI_GETDOCPOINTER = 2357 @@ -501,32 +652,50 @@ EDGE_NONE = 0 EDGE_LINE = 1 EDGE_BACKGROUND = 2 +EDGE_MULTILINE = 3 SCI_GETEDGECOLUMN = 2360 SCI_SETEDGECOLUMN = 2361 SCI_GETEDGEMODE = 2362 SCI_SETEDGEMODE = 2363 SCI_GETEDGECOLOUR = 2364 SCI_SETEDGECOLOUR = 2365 +SCI_MULTIEDGEADDLINE = 2694 +SCI_MULTIEDGECLEARALL = 2695 +SCI_GETMULTIEDGECOLUMN = 2749 SCI_SEARCHANCHOR = 2366 SCI_SEARCHNEXT = 2367 SCI_SEARCHPREV = 2368 SCI_LINESONSCREEN = 2370 +SC_POPUP_NEVER = 0 +SC_POPUP_ALL = 1 +SC_POPUP_TEXT = 2 SCI_USEPOPUP = 2371 SCI_SELECTIONISRECTANGLE = 2372 SCI_SETZOOM = 2373 SCI_GETZOOM = 2374 +SC_DOCUMENTOPTION_DEFAULT = 0 +SC_DOCUMENTOPTION_STYLES_NONE = 0x1 +SC_DOCUMENTOPTION_TEXT_LARGE = 0x100 SCI_CREATEDOCUMENT = 2375 SCI_ADDREFDOCUMENT = 2376 SCI_RELEASEDOCUMENT = 2377 +SCI_GETDOCUMENTOPTIONS = 2379 SCI_GETMODEVENTMASK = 2378 +SCI_SETCOMMANDEVENTS = 2717 +SCI_GETCOMMANDEVENTS = 2718 SCI_SETFOCUS = 2380 SCI_GETFOCUS = 2381 +SC_STATUS_OK = 0 +SC_STATUS_FAILURE = 1 +SC_STATUS_BADALLOC = 2 +SC_STATUS_WARN_START = 1000 +SC_STATUS_WARN_REGEX = 1001 SCI_SETSTATUS = 2382 SCI_GETSTATUS = 2383 SCI_SETMOUSEDOWNCAPTURES = 2384 SCI_GETMOUSEDOWNCAPTURES = 2385 -SC_CURSORNORMAL = -1 -SC_CURSORWAIT = 4 +SCI_SETMOUSEWHEELCAPTURES = 2696 +SCI_GETMOUSEWHEELCAPTURES = 2697 SCI_SETCURSOR = 2386 SCI_GETCURSOR = 2387 SCI_SETCONTROLCHARSYMBOL = 2388 @@ -566,13 +735,17 @@ SCI_PARAUPEXTEND = 2416 SCI_POSITIONBEFORE = 2417 SCI_POSITIONAFTER = 2418 +SCI_POSITIONRELATIVE = 2670 +SCI_POSITIONRELATIVECODEUNITS = 2716 SCI_COPYRANGE = 2419 SCI_COPYTEXT = 2420 SC_SEL_STREAM = 0 SC_SEL_RECTANGLE = 1 SC_SEL_LINES = 2 +SC_SEL_THIN = 3 SCI_SETSELECTIONMODE = 2422 SCI_GETSELECTIONMODE = 2423 +SCI_GETMOVEEXTENDSSELECTION = 2706 SCI_GETLINESELSTARTPOSITION = 2424 SCI_GETLINESELENDPOSITION = 2425 SCI_LINEDOWNRECTEXTEND = 2426 @@ -593,27 +766,48 @@ SCI_WORDRIGHTEND = 2441 SCI_WORDRIGHTENDEXTEND = 2442 SCI_SETWHITESPACECHARS = 2443 +SCI_GETWHITESPACECHARS = 2647 +SCI_SETPUNCTUATIONCHARS = 2648 +SCI_GETPUNCTUATIONCHARS = 2649 SCI_SETCHARSDEFAULT = 2444 SCI_AUTOCGETCURRENT = 2445 +SCI_AUTOCGETCURRENTTEXT = 2610 +SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE = 0 +SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE = 1 +SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR = 2634 +SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR = 2635 +SC_MULTIAUTOC_ONCE = 0 +SC_MULTIAUTOC_EACH = 1 +SCI_AUTOCSETMULTI = 2636 +SCI_AUTOCGETMULTI = 2637 +SC_ORDER_PRESORTED = 0 +SC_ORDER_PERFORMSORT = 1 +SC_ORDER_CUSTOM = 2 +SCI_AUTOCSETORDER = 2660 +SCI_AUTOCGETORDER = 2661 SCI_ALLOCATE = 2446 SCI_TARGETASUTF8 = 2447 SCI_SETLENGTHFORENCODE = 2448 SCI_ENCODEDFROMUTF8 = 2449 SCI_FINDCOLUMN = 2456 +SC_CARETSTICKY_OFF = 0 +SC_CARETSTICKY_ON = 1 +SC_CARETSTICKY_WHITESPACE = 2 SCI_GETCARETSTICKY = 2457 SCI_SETCARETSTICKY = 2458 SCI_TOGGLECARETSTICKY = 2459 SCI_SETPASTECONVERTENDINGS = 2467 SCI_GETPASTECONVERTENDINGS = 2468 SCI_SELECTIONDUPLICATE = 2469 -SC_ALPHA_TRANSPARENT = 0 -SC_ALPHA_OPAQUE = 255 -SC_ALPHA_NOALPHA = 256 SCI_SETCARETLINEBACKALPHA = 2470 SCI_GETCARETLINEBACKALPHA = 2471 CARETSTYLE_INVISIBLE = 0 CARETSTYLE_LINE = 1 CARETSTYLE_BLOCK = 2 +CARETSTYLE_OVERSTRIKE_BAR = 0 +CARETSTYLE_OVERSTRIKE_BLOCK = 0x10 +CARETSTYLE_INS_MASK = 0xF +CARETSTYLE_BLOCK_AFTER = 0x100 SCI_SETCARETSTYLE = 2512 SCI_GETCARETSTYLE = 2513 SCI_SETINDICATORCURRENT = 2500 @@ -630,8 +824,159 @@ SCI_GETPOSITIONCACHE = 2515 SCI_COPYALLOWLINE = 2519 SCI_GETCHARACTERPOINTER = 2520 -SCI_SETKEYSUNICODE = 2521 -SCI_GETKEYSUNICODE = 2522 +SCI_GETRANGEPOINTER = 2643 +SCI_GETGAPPOSITION = 2644 +SCI_INDICSETALPHA = 2523 +SCI_INDICGETALPHA = 2524 +SCI_INDICSETOUTLINEALPHA = 2558 +SCI_INDICGETOUTLINEALPHA = 2559 +SCI_SETEXTRAASCENT = 2525 +SCI_GETEXTRAASCENT = 2526 +SCI_SETEXTRADESCENT = 2527 +SCI_GETEXTRADESCENT = 2528 +SCI_MARKERSYMBOLDEFINED = 2529 +SCI_MARGINSETTEXT = 2530 +SCI_MARGINGETTEXT = 2531 +SCI_MARGINSETSTYLE = 2532 +SCI_MARGINGETSTYLE = 2533 +SCI_MARGINSETSTYLES = 2534 +SCI_MARGINGETSTYLES = 2535 +SCI_MARGINTEXTCLEARALL = 2536 +SCI_MARGINSETSTYLEOFFSET = 2537 +SCI_MARGINGETSTYLEOFFSET = 2538 +SC_MARGINOPTION_NONE = 0 +SC_MARGINOPTION_SUBLINESELECT = 1 +SCI_SETMARGINOPTIONS = 2539 +SCI_GETMARGINOPTIONS = 2557 +SCI_ANNOTATIONSETTEXT = 2540 +SCI_ANNOTATIONGETTEXT = 2541 +SCI_ANNOTATIONSETSTYLE = 2542 +SCI_ANNOTATIONGETSTYLE = 2543 +SCI_ANNOTATIONSETSTYLES = 2544 +SCI_ANNOTATIONGETSTYLES = 2545 +SCI_ANNOTATIONGETLINES = 2546 +SCI_ANNOTATIONCLEARALL = 2547 +ANNOTATION_HIDDEN = 0 +ANNOTATION_STANDARD = 1 +ANNOTATION_BOXED = 2 +ANNOTATION_INDENTED = 3 +SCI_ANNOTATIONSETVISIBLE = 2548 +SCI_ANNOTATIONGETVISIBLE = 2549 +SCI_ANNOTATIONSETSTYLEOFFSET = 2550 +SCI_ANNOTATIONGETSTYLEOFFSET = 2551 +SCI_RELEASEALLEXTENDEDSTYLES = 2552 +SCI_ALLOCATEEXTENDEDSTYLES = 2553 +UNDO_NONE = 0 +UNDO_MAY_COALESCE = 1 +SCI_ADDUNDOACTION = 2560 +SCI_CHARPOSITIONFROMPOINT = 2561 +SCI_CHARPOSITIONFROMPOINTCLOSE = 2562 +SCI_SETMOUSESELECTIONRECTANGULARSWITCH = 2668 +SCI_GETMOUSESELECTIONRECTANGULARSWITCH = 2669 +SCI_SETMULTIPLESELECTION = 2563 +SCI_GETMULTIPLESELECTION = 2564 +SCI_SETADDITIONALSELECTIONTYPING = 2565 +SCI_GETADDITIONALSELECTIONTYPING = 2566 +SCI_SETADDITIONALCARETSBLINK = 2567 +SCI_GETADDITIONALCARETSBLINK = 2568 +SCI_SETADDITIONALCARETSVISIBLE = 2608 +SCI_GETADDITIONALCARETSVISIBLE = 2609 +SCI_GETSELECTIONS = 2570 +SCI_GETSELECTIONEMPTY = 2650 +SCI_CLEARSELECTIONS = 2571 +SCI_SETSELECTION = 2572 +SCI_ADDSELECTION = 2573 +SCI_DROPSELECTIONN = 2671 +SCI_SETMAINSELECTION = 2574 +SCI_GETMAINSELECTION = 2575 +SCI_SETSELECTIONNCARET = 2576 +SCI_GETSELECTIONNCARET = 2577 +SCI_SETSELECTIONNANCHOR = 2578 +SCI_GETSELECTIONNANCHOR = 2579 +SCI_SETSELECTIONNCARETVIRTUALSPACE = 2580 +SCI_GETSELECTIONNCARETVIRTUALSPACE = 2581 +SCI_SETSELECTIONNANCHORVIRTUALSPACE = 2582 +SCI_GETSELECTIONNANCHORVIRTUALSPACE = 2583 +SCI_SETSELECTIONNSTART = 2584 +SCI_GETSELECTIONNSTART = 2585 +SCI_GETSELECTIONNSTARTVIRTUALSPACE = 2726 +SCI_SETSELECTIONNEND = 2586 +SCI_GETSELECTIONNENDVIRTUALSPACE = 2727 +SCI_GETSELECTIONNEND = 2587 +SCI_SETRECTANGULARSELECTIONCARET = 2588 +SCI_GETRECTANGULARSELECTIONCARET = 2589 +SCI_SETRECTANGULARSELECTIONANCHOR = 2590 +SCI_GETRECTANGULARSELECTIONANCHOR = 2591 +SCI_SETRECTANGULARSELECTIONCARETVIRTUALSPACE = 2592 +SCI_GETRECTANGULARSELECTIONCARETVIRTUALSPACE = 2593 +SCI_SETRECTANGULARSELECTIONANCHORVIRTUALSPACE = 2594 +SCI_GETRECTANGULARSELECTIONANCHORVIRTUALSPACE = 2595 +SCVS_NONE = 0 +SCVS_RECTANGULARSELECTION = 1 +SCVS_USERACCESSIBLE = 2 +SCVS_NOWRAPLINESTART = 4 +SCI_SETVIRTUALSPACEOPTIONS = 2596 +SCI_GETVIRTUALSPACEOPTIONS = 2597 +SCI_SETRECTANGULARSELECTIONMODIFIER = 2598 +SCI_GETRECTANGULARSELECTIONMODIFIER = 2599 +SCI_SETADDITIONALSELFORE = 2600 +SCI_SETADDITIONALSELBACK = 2601 +SCI_SETADDITIONALSELALPHA = 2602 +SCI_GETADDITIONALSELALPHA = 2603 +SCI_SETADDITIONALCARETFORE = 2604 +SCI_GETADDITIONALCARETFORE = 2605 +SCI_ROTATESELECTION = 2606 +SCI_SWAPMAINANCHORCARET = 2607 +SCI_MULTIPLESELECTADDNEXT = 2688 +SCI_MULTIPLESELECTADDEACH = 2689 +SCI_CHANGELEXERSTATE = 2617 +SCI_CONTRACTEDFOLDNEXT = 2618 +SCI_VERTICALCENTRECARET = 2619 +SCI_MOVESELECTEDLINESUP = 2620 +SCI_MOVESELECTEDLINESDOWN = 2621 +SCI_SETIDENTIFIER = 2622 +SCI_GETIDENTIFIER = 2623 +SCI_RGBAIMAGESETWIDTH = 2624 +SCI_RGBAIMAGESETHEIGHT = 2625 +SCI_RGBAIMAGESETSCALE = 2651 +SCI_MARKERDEFINERGBAIMAGE = 2626 +SCI_REGISTERRGBAIMAGE = 2627 +SCI_SCROLLTOSTART = 2628 +SCI_SCROLLTOEND = 2629 +SC_TECHNOLOGY_DEFAULT = 0 +SC_TECHNOLOGY_DIRECTWRITE = 1 +SC_TECHNOLOGY_DIRECTWRITERETAIN = 2 +SC_TECHNOLOGY_DIRECTWRITEDC = 3 +SCI_SETTECHNOLOGY = 2630 +SCI_GETTECHNOLOGY = 2631 +SCI_CREATELOADER = 2632 +SCI_FINDINDICATORSHOW = 2640 +SCI_FINDINDICATORFLASH = 2641 +SCI_FINDINDICATORHIDE = 2642 +SCI_VCHOMEDISPLAY = 2652 +SCI_VCHOMEDISPLAYEXTEND = 2653 +SCI_GETCARETLINEVISIBLEALWAYS = 2654 +SCI_SETCARETLINEVISIBLEALWAYS = 2655 +SC_LINE_END_TYPE_DEFAULT = 0 +SC_LINE_END_TYPE_UNICODE = 1 +SCI_SETLINEENDTYPESALLOWED = 2656 +SCI_GETLINEENDTYPESALLOWED = 2657 +SCI_GETLINEENDTYPESACTIVE = 2658 +SCI_SETREPRESENTATION = 2665 +SCI_GETREPRESENTATION = 2666 +SCI_CLEARREPRESENTATION = 2667 +SCI_EOLANNOTATIONSETTEXT = 2740 +SCI_EOLANNOTATIONGETTEXT = 2741 +SCI_EOLANNOTATIONSETSTYLE = 2742 +SCI_EOLANNOTATIONGETSTYLE = 2743 +SCI_EOLANNOTATIONCLEARALL = 2744 +EOLANNOTATION_HIDDEN = 0 +EOLANNOTATION_STANDARD = 1 +EOLANNOTATION_BOXED = 2 +SCI_EOLANNOTATIONSETVISIBLE = 2745 +SCI_EOLANNOTATIONGETVISIBLE = 2746 +SCI_EOLANNOTATIONSETSTYLEOFFSET = 2747 +SCI_EOLANNOTATIONGETSTYLEOFFSET = 2748 SCI_STARTRECORD = 3001 SCI_STOPRECORD = 3002 SCI_SETLEXER = 4001 @@ -645,7 +990,31 @@ SCI_GETPROPERTY = 4008 SCI_GETPROPERTYEXPANDED = 4009 SCI_GETPROPERTYINT = 4010 -SCI_GETSTYLEBITSNEEDED = 4011 +SCI_GETLEXERLANGUAGE = 4012 +SCI_PRIVATELEXERCALL = 4013 +SCI_PROPERTYNAMES = 4014 +SC_TYPE_BOOLEAN = 0 +SC_TYPE_INTEGER = 1 +SC_TYPE_STRING = 2 +SCI_PROPERTYTYPE = 4015 +SCI_DESCRIBEPROPERTY = 4016 +SCI_DESCRIBEKEYWORDSETS = 4017 +SCI_GETLINEENDTYPESSUPPORTED = 4018 +SCI_ALLOCATESUBSTYLES = 4020 +SCI_GETSUBSTYLESSTART = 4021 +SCI_GETSUBSTYLESLENGTH = 4022 +SCI_GETSTYLEFROMSUBSTYLE = 4027 +SCI_GETPRIMARYSTYLEFROMSTYLE = 4028 +SCI_FREESUBSTYLES = 4023 +SCI_SETIDENTIFIERS = 4024 +SCI_DISTANCETOSECONDARYSTYLES = 4025 +SCI_GETSUBSTYLEBASES = 4026 +SCI_GETNAMEDSTYLES = 4029 +SCI_NAMEOFSTYLE = 4030 +SCI_TAGSOFSTYLE = 4031 +SCI_DESCRIPTIONOFSTYLE = 4032 +SCI_SETILEXER = 4033 +SC_MOD_NONE = 0x0 SC_MOD_INSERTTEXT = 0x1 SC_MOD_DELETETEXT = 0x2 SC_MOD_CHANGESTYLE = 0x4 @@ -662,7 +1031,18 @@ SC_STARTACTION = 0x2000 SC_MOD_CHANGEINDICATOR = 0x4000 SC_MOD_CHANGELINESTATE = 0x8000 -SC_MODEVENTMASKALL = 0xFFFF +SC_MOD_CHANGEMARGIN = 0x10000 +SC_MOD_CHANGEANNOTATION = 0x20000 +SC_MOD_CONTAINER = 0x40000 +SC_MOD_LEXERSTATE = 0x80000 +SC_MOD_INSERTCHECK = 0x100000 +SC_MOD_CHANGETABSTOPS = 0x200000 +SC_MOD_CHANGEEOLANNOTATION = 0x400000 +SC_MODEVENTMASKALL = 0x7FFFFF +SC_UPDATE_CONTENT = 0x1 +SC_UPDATE_SELECTION = 0x2 +SC_UPDATE_V_SCROLL = 0x4 +SC_UPDATE_H_SCROLL = 0x8 SCEN_CHANGE = 768 SCEN_SETFOCUS = 512 SCEN_KILLFOCUS = 256 @@ -690,6 +1070,16 @@ SCMOD_SHIFT = 1 SCMOD_CTRL = 2 SCMOD_ALT = 4 +SCMOD_SUPER = 8 +SCMOD_META = 16 +SC_AC_FILLUP = 1 +SC_AC_DOUBLECLICK = 2 +SC_AC_TAB = 3 +SC_AC_NEWLINE = 4 +SC_AC_COMMAND = 5 +SC_CHARACTERSOURCE_DIRECT_INPUT = 0 +SC_CHARACTERSOURCE_TENTATIVE_INPUT = 1 +SC_CHARACTERSOURCE_IME_RESULT = 2 SCN_STYLENEEDED = 2000 SCN_CHARADDED = 2001 SCN_SAVEPOINTREACHED = 2002 @@ -715,12 +1105,37 @@ SCN_INDICATORCLICK = 2023 SCN_INDICATORRELEASE = 2024 SCN_AUTOCCANCELLED = 2025 -SCI_SETCARETPOLICY = 2369 -CARET_CENTER = 0x02 -CARET_XEVEN = 0x08 -CARET_XJUMPS = 0x10 -SCN_POSCHANGED = 2012 -SCN_CHECKBRACE = 2007 +SCN_AUTOCCHARDELETED = 2026 +SCN_HOTSPOTRELEASECLICK = 2027 +SCN_FOCUSIN = 2028 +SCN_FOCUSOUT = 2029 +SCN_AUTOCCOMPLETED = 2030 +SCN_MARGINRIGHTCLICK = 2031 +SCN_AUTOCSELECTIONCHANGE = 2032 +SC_BIDIRECTIONAL_DISABLED = 0 +SC_BIDIRECTIONAL_L2R = 1 +SC_BIDIRECTIONAL_R2L = 2 +SCI_GETBIDIRECTIONAL = 2708 +SCI_SETBIDIRECTIONAL = 2709 +SC_LINECHARACTERINDEX_NONE = 0 +SC_LINECHARACTERINDEX_UTF32 = 1 +SC_LINECHARACTERINDEX_UTF16 = 2 +SCI_GETLINECHARACTERINDEX = 2710 +SCI_ALLOCATELINECHARACTERINDEX = 2711 +SCI_RELEASELINECHARACTERINDEX = 2712 +SCI_LINEFROMINDEXPOSITION = 2713 +SCI_INDEXPOSITIONFROMLINE = 2714 +SCI_SETKEYSUNICODE = 2521 +SCI_GETKEYSUNICODE = 2522 +SCI_GETTWOPHASEDRAW = 2283 +SCI_SETTWOPHASEDRAW = 2284 +SCI_SETSTYLEBITS = 2090 +SCI_GETSTYLEBITS = 2091 +SCI_GETSTYLEBITSNEEDED = 4011 +INDIC0_MASK = 0x20 +INDIC1_MASK = 0x40 +INDIC2_MASK = 0x80 +INDICS_MASK = 0xE0 # Generated by h2py from Include\scilexer.h SCLEX_CONTAINER = 0 SCLEX_NULL = 1 @@ -811,6 +1226,47 @@ SCLEX_POWERSHELL = 88 SCLEX_MYSQL = 89 SCLEX_PO = 90 +SCLEX_TAL = 91 +SCLEX_COBOL = 92 +SCLEX_TACL = 93 +SCLEX_SORCUS = 94 +SCLEX_POWERPRO = 95 +SCLEX_NIMROD = 96 +SCLEX_SML = 97 +SCLEX_MARKDOWN = 98 +SCLEX_TXT2TAGS = 99 +SCLEX_A68K = 100 +SCLEX_MODULA = 101 +SCLEX_COFFEESCRIPT = 102 +SCLEX_TCMD = 103 +SCLEX_AVS = 104 +SCLEX_ECL = 105 +SCLEX_OSCRIPT = 106 +SCLEX_VISUALPROLOG = 107 +SCLEX_LITERATEHASKELL = 108 +SCLEX_STTXT = 109 +SCLEX_KVIRC = 110 +SCLEX_RUST = 111 +SCLEX_DMAP = 112 +SCLEX_AS = 113 +SCLEX_DMIS = 114 +SCLEX_REGISTRY = 115 +SCLEX_BIBTEX = 116 +SCLEX_SREC = 117 +SCLEX_IHEX = 118 +SCLEX_TEHEX = 119 +SCLEX_JSON = 120 +SCLEX_EDIFACT = 121 +SCLEX_INDENT = 122 +SCLEX_MAXIMA = 123 +SCLEX_STATA = 124 +SCLEX_SAS = 125 +SCLEX_NIM = 126 +SCLEX_CIL = 127 +SCLEX_X12 = 128 +SCLEX_DATAFLEX = 129 +SCLEX_HOLLYWOOD = 130 +SCLEX_RAKU = 131 SCLEX_AUTOMATIC = 1000 SCE_P_DEFAULT = 0 SCE_P_COMMENTLINE = 1 @@ -828,6 +1284,10 @@ SCE_P_STRINGEOL = 13 SCE_P_WORD2 = 14 SCE_P_DECORATOR = 15 +SCE_P_FSTRING = 16 +SCE_P_FCHARACTER = 17 +SCE_P_FTRIPLE = 18 +SCE_P_FTRIPLEDOUBLE = 19 SCE_C_DEFAULT = 0 SCE_C_COMMENT = 1 SCE_C_COMMENTLINE = 2 @@ -848,6 +1308,14 @@ SCE_C_COMMENTDOCKEYWORD = 17 SCE_C_COMMENTDOCKEYWORDERROR = 18 SCE_C_GLOBALCLASS = 19 +SCE_C_STRINGRAW = 20 +SCE_C_TRIPLEVERBATIM = 21 +SCE_C_HASHQUOTEDSTRING = 22 +SCE_C_PREPROCESSORCOMMENT = 23 +SCE_C_PREPROCESSORCOMMENTDOC = 24 +SCE_C_USERLITERAL = 25 +SCE_C_TASKMARKER = 26 +SCE_C_ESCAPESEQUENCE = 27 SCE_D_DEFAULT = 0 SCE_D_COMMENT = 1 SCE_D_COMMENTLINE = 2 @@ -866,6 +1334,11 @@ SCE_D_COMMENTLINEDOC = 15 SCE_D_COMMENTDOCKEYWORD = 16 SCE_D_COMMENTDOCKEYWORDERROR = 17 +SCE_D_STRINGB = 18 +SCE_D_STRINGR = 19 +SCE_D_WORD5 = 20 +SCE_D_WORD6 = 21 +SCE_D_WORD7 = 22 SCE_TCL_DEFAULT = 0 SCE_TCL_COMMENT = 1 SCE_TCL_COMMENTLINE = 2 @@ -1034,6 +1507,16 @@ SCE_PL_SUB_PROTOTYPE = 40 SCE_PL_FORMAT_IDENT = 41 SCE_PL_FORMAT = 42 +SCE_PL_STRING_VAR = 43 +SCE_PL_XLAT = 44 +SCE_PL_REGEX_VAR = 54 +SCE_PL_REGSUBST_VAR = 55 +SCE_PL_BACKTICKS_VAR = 57 +SCE_PL_HERE_QQ_VAR = 61 +SCE_PL_HERE_QX_VAR = 62 +SCE_PL_STRING_QQ_VAR = 64 +SCE_PL_STRING_QX_VAR = 65 +SCE_PL_STRING_QR_VAR = 66 SCE_RB_DEFAULT = 0 SCE_RB_ERROR = 1 SCE_RB_COMMENTLINE = 2 @@ -1087,6 +1570,10 @@ SCE_B_ERROR = 16 SCE_B_HEXNUMBER = 17 SCE_B_BINNUMBER = 18 +SCE_B_COMMENTBLOCK = 19 +SCE_B_DOCLINE = 20 +SCE_B_DOCBLOCK = 21 +SCE_B_DOCKEYWORD = 22 SCE_PROPS_DEFAULT = 0 SCE_PROPS_COMMENT = 1 SCE_PROPS_SECTION = 2 @@ -1098,6 +1585,14 @@ SCE_L_TAG = 2 SCE_L_MATH = 3 SCE_L_COMMENT = 4 +SCE_L_TAG2 = 5 +SCE_L_MATH2 = 6 +SCE_L_COMMENT2 = 7 +SCE_L_VERBATIM = 8 +SCE_L_SHORTCMD = 9 +SCE_L_SPECIAL = 10 +SCE_L_CMDOPT = 11 +SCE_L_ERROR = 12 SCE_LUA_DEFAULT = 0 SCE_LUA_COMMENT = 1 SCE_LUA_COMMENTLINE = 2 @@ -1118,6 +1613,7 @@ SCE_LUA_WORD6 = 17 SCE_LUA_WORD7 = 18 SCE_LUA_WORD8 = 19 +SCE_LUA_LABEL = 20 SCE_ERR_DEFAULT = 0 SCE_ERR_PYTHON = 1 SCE_ERR_GCC = 2 @@ -1140,6 +1636,26 @@ SCE_ERR_TIDY = 19 SCE_ERR_JAVA_STACK = 20 SCE_ERR_VALUE = 21 +SCE_ERR_GCC_INCLUDED_FROM = 22 +SCE_ERR_ESCSEQ = 23 +SCE_ERR_ESCSEQ_UNKNOWN = 24 +SCE_ERR_GCC_EXCERPT = 25 +SCE_ERR_ES_BLACK = 40 +SCE_ERR_ES_RED = 41 +SCE_ERR_ES_GREEN = 42 +SCE_ERR_ES_BROWN = 43 +SCE_ERR_ES_BLUE = 44 +SCE_ERR_ES_MAGENTA = 45 +SCE_ERR_ES_CYAN = 46 +SCE_ERR_ES_GRAY = 47 +SCE_ERR_ES_DARK_GRAY = 48 +SCE_ERR_ES_BRIGHT_RED = 49 +SCE_ERR_ES_BRIGHT_GREEN = 50 +SCE_ERR_ES_YELLOW = 51 +SCE_ERR_ES_BRIGHT_BLUE = 52 +SCE_ERR_ES_BRIGHT_MAGENTA = 53 +SCE_ERR_ES_BRIGHT_CYAN = 54 +SCE_ERR_ES_WHITE = 55 SCE_BAT_DEFAULT = 0 SCE_BAT_COMMENT = 1 SCE_BAT_WORD = 2 @@ -1148,6 +1664,17 @@ SCE_BAT_COMMAND = 5 SCE_BAT_IDENTIFIER = 6 SCE_BAT_OPERATOR = 7 +SCE_TCMD_DEFAULT = 0 +SCE_TCMD_COMMENT = 1 +SCE_TCMD_WORD = 2 +SCE_TCMD_LABEL = 3 +SCE_TCMD_HIDE = 4 +SCE_TCMD_COMMAND = 5 +SCE_TCMD_IDENTIFIER = 6 +SCE_TCMD_OPERATOR = 7 +SCE_TCMD_ENVIRONMENT = 8 +SCE_TCMD_EXPANSION = 9 +SCE_TCMD_CLABEL = 10 SCE_MAKE_DEFAULT = 0 SCE_MAKE_COMMENT = 1 SCE_MAKE_PREPROCESSOR = 2 @@ -1163,6 +1690,10 @@ SCE_DIFF_DELETED = 5 SCE_DIFF_ADDED = 6 SCE_DIFF_CHANGED = 7 +SCE_DIFF_PATCH_ADD = 8 +SCE_DIFF_PATCH_DELETE = 9 +SCE_DIFF_REMOVED_PATCH_ADD = 10 +SCE_DIFF_REMOVED_PATCH_DELETE = 11 SCE_CONF_DEFAULT = 0 SCE_CONF_COMMENT = 1 SCE_CONF_NUMBER = 2 @@ -1211,6 +1742,20 @@ SCE_BAAN_IDENTIFIER = 8 SCE_BAAN_STRINGEOL = 9 SCE_BAAN_WORD2 = 10 +SCE_BAAN_WORD3 = 11 +SCE_BAAN_WORD4 = 12 +SCE_BAAN_WORD5 = 13 +SCE_BAAN_WORD6 = 14 +SCE_BAAN_WORD7 = 15 +SCE_BAAN_WORD8 = 16 +SCE_BAAN_WORD9 = 17 +SCE_BAAN_TABLEDEF = 18 +SCE_BAAN_TABLESQL = 19 +SCE_BAAN_FUNCTION = 20 +SCE_BAAN_DOMDEF = 21 +SCE_BAAN_FUNCDEF = 22 +SCE_BAAN_OBJECTDEF = 23 +SCE_BAAN_DEFINEDEF = 24 SCE_LISP_DEFAULT = 0 SCE_LISP_COMMENT = 1 SCE_LISP_NUMBER = 2 @@ -1264,6 +1809,14 @@ SCE_MATLAB_OPERATOR = 6 SCE_MATLAB_IDENTIFIER = 7 SCE_MATLAB_DOUBLEQUOTESTRING = 8 +SCE_MAXIMA_OPERATOR = 0 +SCE_MAXIMA_COMMANDENDING = 1 +SCE_MAXIMA_COMMENT = 2 +SCE_MAXIMA_NUMBER = 3 +SCE_MAXIMA_STRING = 4 +SCE_MAXIMA_COMMAND = 5 +SCE_MAXIMA_VARIABLE = 6 +SCE_MAXIMA_UNKNOWN = 7 SCE_SCRIPTOL_DEFAULT = 0 SCE_SCRIPTOL_WHITE = 1 SCE_SCRIPTOL_COMMENTLINE = 2 @@ -1295,6 +1848,7 @@ SCE_ASM_CHARACTER = 12 SCE_ASM_STRINGEOL = 13 SCE_ASM_EXTINSTRUCTION = 14 +SCE_ASM_COMMENTDIRECTIVE = 15 SCE_F_DEFAULT = 0 SCE_F_COMMENT = 1 SCE_F_NUMBER = 2 @@ -1332,6 +1886,8 @@ SCE_CSS_EXTENDED_IDENTIFIER = 19 SCE_CSS_EXTENDED_PSEUDOCLASS = 20 SCE_CSS_EXTENDED_PSEUDOELEMENT = 21 +SCE_CSS_MEDIA = 22 +SCE_CSS_VARIABLE = 23 SCE_POV_DEFAULT = 0 SCE_POV_COMMENT = 1 SCE_POV_COMMENTLINE = 2 @@ -1484,8 +2040,19 @@ SCE_ERLANG_CHARACTER = 9 SCE_ERLANG_MACRO = 10 SCE_ERLANG_RECORD = 11 -SCE_ERLANG_SEPARATOR = 12 +SCE_ERLANG_PREPROC = 12 SCE_ERLANG_NODE_NAME = 13 +SCE_ERLANG_COMMENT_FUNCTION = 14 +SCE_ERLANG_COMMENT_MODULE = 15 +SCE_ERLANG_COMMENT_DOC = 16 +SCE_ERLANG_COMMENT_DOC_MACRO = 17 +SCE_ERLANG_ATOM_QUOTED = 18 +SCE_ERLANG_MACRO_QUOTED = 19 +SCE_ERLANG_RECORD_QUOTED = 20 +SCE_ERLANG_NODE_NAME_QUOTED = 21 +SCE_ERLANG_BIFS = 22 +SCE_ERLANG_MODULES = 23 +SCE_ERLANG_MODULES_ATT = 24 SCE_ERLANG_UNKNOWN = 31 SCE_MSSQL_DEFAULT = 0 SCE_MSSQL_COMMENT = 1 @@ -1518,6 +2085,11 @@ SCE_V_IDENTIFIER = 11 SCE_V_STRINGEOL = 12 SCE_V_USER = 19 +SCE_V_COMMENT_WORD = 20 +SCE_V_INPUT = 21 +SCE_V_OUTPUT = 22 +SCE_V_INOUT = 23 +SCE_V_PORT_CONNECT = 24 SCE_KIX_DEFAULT = 0 SCE_KIX_COMMENT = 1 SCE_KIX_STRING1 = 2 @@ -1528,6 +2100,7 @@ SCE_KIX_KEYWORD = 7 SCE_KIX_FUNCTIONS = 8 SCE_KIX_OPERATOR = 9 +SCE_KIX_COMMENTSTREAM = 10 SCE_KIX_IDENTIFIER = 31 SCE_GC_DEFAULT = 0 SCE_GC_COMMENTLINE = 1 @@ -1624,6 +2197,7 @@ SCE_VHDL_STDPACKAGE = 12 SCE_VHDL_STDTYPE = 13 SCE_VHDL_USERWORD = 14 +SCE_VHDL_BLOCK_COMMENT = 15 SCE_CAML_DEFAULT = 0 SCE_CAML_IDENTIFIER = 1 SCE_CAML_TAGNAME = 2 @@ -1634,6 +2208,7 @@ SCE_CAML_OPERATOR = 7 SCE_CAML_NUMBER = 8 SCE_CAML_CHAR = 9 +SCE_CAML_WHITE = 10 SCE_CAML_STRING = 11 SCE_CAML_COMMENT = 12 SCE_CAML_COMMENT1 = 13 @@ -1656,6 +2231,12 @@ SCE_HA_COMMENTBLOCK = 14 SCE_HA_COMMENTBLOCK2 = 15 SCE_HA_COMMENTBLOCK3 = 16 +SCE_HA_PRAGMA = 17 +SCE_HA_PREPROCESSOR = 18 +SCE_HA_STRINGEOL = 19 +SCE_HA_RESERVED_OPERATOR = 20 +SCE_HA_LITERATE_COMMENT = 21 +SCE_HA_LITERATE_CODEDELIM = 22 SCE_T3_DEFAULT = 0 SCE_T3_X_DEFAULT = 1 SCE_T3_PREPROCESSOR = 2 @@ -1728,6 +2309,7 @@ SCE_SQL_USER3 = 21 SCE_SQL_USER4 = 22 SCE_SQL_QUOTEDIDENTIFIER = 23 +SCE_SQL_QOPERATOR = 24 SCE_ST_DEFAULT = 0 SCE_ST_STRING = 1 SCE_ST_NUMBER = 2 @@ -1764,11 +2346,19 @@ SCE_FS_DATE = 16 SCE_FS_STRINGEOL = 17 SCE_FS_CONSTANT = 18 -SCE_FS_ASM = 19 -SCE_FS_LABEL = 20 -SCE_FS_ERROR = 21 -SCE_FS_HEXNUMBER = 22 -SCE_FS_BINNUMBER = 23 +SCE_FS_WORDOPERATOR = 19 +SCE_FS_DISABLEDCODE = 20 +SCE_FS_DEFAULT_C = 21 +SCE_FS_COMMENTDOC_C = 22 +SCE_FS_COMMENTLINEDOC_C = 23 +SCE_FS_KEYWORD_C = 24 +SCE_FS_KEYWORD2_C = 25 +SCE_FS_NUMBER_C = 26 +SCE_FS_STRING_C = 27 +SCE_FS_PREPROCESSOR_C = 28 +SCE_FS_OPERATOR_C = 29 +SCE_FS_IDENTIFIER_C = 30 +SCE_FS_STRINGEOL_C = 31 SCE_CSOUND_DEFAULT = 0 SCE_CSOUND_COMMENT = 1 SCE_CSOUND_NUMBER = 2 @@ -1791,7 +2381,7 @@ SCE_INNO_PARAMETER = 3 SCE_INNO_SECTION = 4 SCE_INNO_PREPROC = 5 -SCE_INNO_PREPROC_INLINE = 6 +SCE_INNO_INLINE_EXPANSION = 6 SCE_INNO_COMMENT_PASCAL = 7 SCE_INNO_KEYWORD_PASCAL = 8 SCE_INNO_KEYWORD_USER = 9 @@ -1852,38 +2442,19 @@ SCE_PLM_OPERATOR = 5 SCE_PLM_CONTROL = 6 SCE_PLM_KEYWORD = 7 -SCE_4GL_DEFAULT = 0 -SCE_4GL_NUMBER = 1 -SCE_4GL_WORD = 2 -SCE_4GL_STRING = 3 -SCE_4GL_CHARACTER = 4 -SCE_4GL_PREPROCESSOR = 5 -SCE_4GL_OPERATOR = 6 -SCE_4GL_IDENTIFIER = 7 -SCE_4GL_BLOCK = 8 -SCE_4GL_END = 9 -SCE_4GL_COMMENT1 = 10 -SCE_4GL_COMMENT2 = 11 -SCE_4GL_COMMENT3 = 12 -SCE_4GL_COMMENT4 = 13 -SCE_4GL_COMMENT5 = 14 -SCE_4GL_COMMENT6 = 15 -SCE_4GL_DEFAULT_ = 16 -SCE_4GL_NUMBER_ = 17 -SCE_4GL_WORD_ = 18 -SCE_4GL_STRING_ = 19 -SCE_4GL_CHARACTER_ = 20 -SCE_4GL_PREPROCESSOR_ = 21 -SCE_4GL_OPERATOR_ = 22 -SCE_4GL_IDENTIFIER_ = 23 -SCE_4GL_BLOCK_ = 24 -SCE_4GL_END_ = 25 -SCE_4GL_COMMENT1_ = 26 -SCE_4GL_COMMENT2_ = 27 -SCE_4GL_COMMENT3_ = 28 -SCE_4GL_COMMENT4_ = 29 -SCE_4GL_COMMENT5_ = 30 -SCE_4GL_COMMENT6_ = 31 +SCE_ABL_DEFAULT = 0 +SCE_ABL_NUMBER = 1 +SCE_ABL_WORD = 2 +SCE_ABL_STRING = 3 +SCE_ABL_CHARACTER = 4 +SCE_ABL_PREPROCESSOR = 5 +SCE_ABL_OPERATOR = 6 +SCE_ABL_IDENTIFIER = 7 +SCE_ABL_BLOCK = 8 +SCE_ABL_END = 9 +SCE_ABL_COMMENT = 10 +SCE_ABL_TASKMARKER = 11 +SCE_ABL_LINECOMMENT = 12 SCE_ABAQUS_DEFAULT = 0 SCE_ABAQUS_COMMENT = 1 SCE_ABAQUS_COMMENTBLOCK = 2 @@ -1949,6 +2520,12 @@ SCE_POWERSHELL_KEYWORD = 8 SCE_POWERSHELL_CMDLET = 9 SCE_POWERSHELL_ALIAS = 10 +SCE_POWERSHELL_FUNCTION = 11 +SCE_POWERSHELL_USER1 = 12 +SCE_POWERSHELL_COMMENTSTREAM = 13 +SCE_POWERSHELL_HERE_STRING = 14 +SCE_POWERSHELL_HERE_CHARACTER = 15 +SCE_POWERSHELL_COMMENTDOCKEYWORD = 16 SCE_MYSQL_DEFAULT = 0 SCE_MYSQL_COMMENT = 1 SCE_MYSQL_COMMENTLINE = 2 @@ -1970,6 +2547,8 @@ SCE_MYSQL_USER1 = 18 SCE_MYSQL_USER2 = 19 SCE_MYSQL_USER3 = 20 +SCE_MYSQL_HIDDENCOMMAND = 21 +SCE_MYSQL_PLACEHOLDER = 22 SCE_PO_DEFAULT = 0 SCE_PO_COMMENT = 1 SCE_PO_MSGID = 2 @@ -1979,5 +2558,526 @@ SCE_PO_MSGCTXT = 6 SCE_PO_MSGCTXT_TEXT = 7 SCE_PO_FUZZY = 8 -SCLEX_ASP = 29 -SCLEX_PHP = 30 +SCE_PO_PROGRAMMER_COMMENT = 9 +SCE_PO_REFERENCE = 10 +SCE_PO_FLAGS = 11 +SCE_PO_MSGID_TEXT_EOL = 12 +SCE_PO_MSGSTR_TEXT_EOL = 13 +SCE_PO_MSGCTXT_TEXT_EOL = 14 +SCE_PO_ERROR = 15 +SCE_PAS_DEFAULT = 0 +SCE_PAS_IDENTIFIER = 1 +SCE_PAS_COMMENT = 2 +SCE_PAS_COMMENT2 = 3 +SCE_PAS_COMMENTLINE = 4 +SCE_PAS_PREPROCESSOR = 5 +SCE_PAS_PREPROCESSOR2 = 6 +SCE_PAS_NUMBER = 7 +SCE_PAS_HEXNUMBER = 8 +SCE_PAS_WORD = 9 +SCE_PAS_STRING = 10 +SCE_PAS_STRINGEOL = 11 +SCE_PAS_CHARACTER = 12 +SCE_PAS_OPERATOR = 13 +SCE_PAS_ASM = 14 +SCE_SORCUS_DEFAULT = 0 +SCE_SORCUS_COMMAND = 1 +SCE_SORCUS_PARAMETER = 2 +SCE_SORCUS_COMMENTLINE = 3 +SCE_SORCUS_STRING = 4 +SCE_SORCUS_STRINGEOL = 5 +SCE_SORCUS_IDENTIFIER = 6 +SCE_SORCUS_OPERATOR = 7 +SCE_SORCUS_NUMBER = 8 +SCE_SORCUS_CONSTANT = 9 +SCE_POWERPRO_DEFAULT = 0 +SCE_POWERPRO_COMMENTBLOCK = 1 +SCE_POWERPRO_COMMENTLINE = 2 +SCE_POWERPRO_NUMBER = 3 +SCE_POWERPRO_WORD = 4 +SCE_POWERPRO_WORD2 = 5 +SCE_POWERPRO_WORD3 = 6 +SCE_POWERPRO_WORD4 = 7 +SCE_POWERPRO_DOUBLEQUOTEDSTRING = 8 +SCE_POWERPRO_SINGLEQUOTEDSTRING = 9 +SCE_POWERPRO_LINECONTINUE = 10 +SCE_POWERPRO_OPERATOR = 11 +SCE_POWERPRO_IDENTIFIER = 12 +SCE_POWERPRO_STRINGEOL = 13 +SCE_POWERPRO_VERBATIM = 14 +SCE_POWERPRO_ALTQUOTE = 15 +SCE_POWERPRO_FUNCTION = 16 +SCE_SML_DEFAULT = 0 +SCE_SML_IDENTIFIER = 1 +SCE_SML_TAGNAME = 2 +SCE_SML_KEYWORD = 3 +SCE_SML_KEYWORD2 = 4 +SCE_SML_KEYWORD3 = 5 +SCE_SML_LINENUM = 6 +SCE_SML_OPERATOR = 7 +SCE_SML_NUMBER = 8 +SCE_SML_CHAR = 9 +SCE_SML_STRING = 11 +SCE_SML_COMMENT = 12 +SCE_SML_COMMENT1 = 13 +SCE_SML_COMMENT2 = 14 +SCE_SML_COMMENT3 = 15 +SCE_MARKDOWN_DEFAULT = 0 +SCE_MARKDOWN_LINE_BEGIN = 1 +SCE_MARKDOWN_STRONG1 = 2 +SCE_MARKDOWN_STRONG2 = 3 +SCE_MARKDOWN_EM1 = 4 +SCE_MARKDOWN_EM2 = 5 +SCE_MARKDOWN_HEADER1 = 6 +SCE_MARKDOWN_HEADER2 = 7 +SCE_MARKDOWN_HEADER3 = 8 +SCE_MARKDOWN_HEADER4 = 9 +SCE_MARKDOWN_HEADER5 = 10 +SCE_MARKDOWN_HEADER6 = 11 +SCE_MARKDOWN_PRECHAR = 12 +SCE_MARKDOWN_ULIST_ITEM = 13 +SCE_MARKDOWN_OLIST_ITEM = 14 +SCE_MARKDOWN_BLOCKQUOTE = 15 +SCE_MARKDOWN_STRIKEOUT = 16 +SCE_MARKDOWN_HRULE = 17 +SCE_MARKDOWN_LINK = 18 +SCE_MARKDOWN_CODE = 19 +SCE_MARKDOWN_CODE2 = 20 +SCE_MARKDOWN_CODEBK = 21 +SCE_TXT2TAGS_DEFAULT = 0 +SCE_TXT2TAGS_LINE_BEGIN = 1 +SCE_TXT2TAGS_STRONG1 = 2 +SCE_TXT2TAGS_STRONG2 = 3 +SCE_TXT2TAGS_EM1 = 4 +SCE_TXT2TAGS_EM2 = 5 +SCE_TXT2TAGS_HEADER1 = 6 +SCE_TXT2TAGS_HEADER2 = 7 +SCE_TXT2TAGS_HEADER3 = 8 +SCE_TXT2TAGS_HEADER4 = 9 +SCE_TXT2TAGS_HEADER5 = 10 +SCE_TXT2TAGS_HEADER6 = 11 +SCE_TXT2TAGS_PRECHAR = 12 +SCE_TXT2TAGS_ULIST_ITEM = 13 +SCE_TXT2TAGS_OLIST_ITEM = 14 +SCE_TXT2TAGS_BLOCKQUOTE = 15 +SCE_TXT2TAGS_STRIKEOUT = 16 +SCE_TXT2TAGS_HRULE = 17 +SCE_TXT2TAGS_LINK = 18 +SCE_TXT2TAGS_CODE = 19 +SCE_TXT2TAGS_CODE2 = 20 +SCE_TXT2TAGS_CODEBK = 21 +SCE_TXT2TAGS_COMMENT = 22 +SCE_TXT2TAGS_OPTION = 23 +SCE_TXT2TAGS_PREPROC = 24 +SCE_TXT2TAGS_POSTPROC = 25 +SCE_A68K_DEFAULT = 0 +SCE_A68K_COMMENT = 1 +SCE_A68K_NUMBER_DEC = 2 +SCE_A68K_NUMBER_BIN = 3 +SCE_A68K_NUMBER_HEX = 4 +SCE_A68K_STRING1 = 5 +SCE_A68K_OPERATOR = 6 +SCE_A68K_CPUINSTRUCTION = 7 +SCE_A68K_EXTINSTRUCTION = 8 +SCE_A68K_REGISTER = 9 +SCE_A68K_DIRECTIVE = 10 +SCE_A68K_MACRO_ARG = 11 +SCE_A68K_LABEL = 12 +SCE_A68K_STRING2 = 13 +SCE_A68K_IDENTIFIER = 14 +SCE_A68K_MACRO_DECLARATION = 15 +SCE_A68K_COMMENT_WORD = 16 +SCE_A68K_COMMENT_SPECIAL = 17 +SCE_A68K_COMMENT_DOXYGEN = 18 +SCE_MODULA_DEFAULT = 0 +SCE_MODULA_COMMENT = 1 +SCE_MODULA_DOXYCOMM = 2 +SCE_MODULA_DOXYKEY = 3 +SCE_MODULA_KEYWORD = 4 +SCE_MODULA_RESERVED = 5 +SCE_MODULA_NUMBER = 6 +SCE_MODULA_BASENUM = 7 +SCE_MODULA_FLOAT = 8 +SCE_MODULA_STRING = 9 +SCE_MODULA_STRSPEC = 10 +SCE_MODULA_CHAR = 11 +SCE_MODULA_CHARSPEC = 12 +SCE_MODULA_PROC = 13 +SCE_MODULA_PRAGMA = 14 +SCE_MODULA_PRGKEY = 15 +SCE_MODULA_OPERATOR = 16 +SCE_MODULA_BADSTR = 17 +SCE_COFFEESCRIPT_DEFAULT = 0 +SCE_COFFEESCRIPT_COMMENT = 1 +SCE_COFFEESCRIPT_COMMENTLINE = 2 +SCE_COFFEESCRIPT_COMMENTDOC = 3 +SCE_COFFEESCRIPT_NUMBER = 4 +SCE_COFFEESCRIPT_WORD = 5 +SCE_COFFEESCRIPT_STRING = 6 +SCE_COFFEESCRIPT_CHARACTER = 7 +SCE_COFFEESCRIPT_UUID = 8 +SCE_COFFEESCRIPT_PREPROCESSOR = 9 +SCE_COFFEESCRIPT_OPERATOR = 10 +SCE_COFFEESCRIPT_IDENTIFIER = 11 +SCE_COFFEESCRIPT_STRINGEOL = 12 +SCE_COFFEESCRIPT_VERBATIM = 13 +SCE_COFFEESCRIPT_REGEX = 14 +SCE_COFFEESCRIPT_COMMENTLINEDOC = 15 +SCE_COFFEESCRIPT_WORD2 = 16 +SCE_COFFEESCRIPT_COMMENTDOCKEYWORD = 17 +SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR = 18 +SCE_COFFEESCRIPT_GLOBALCLASS = 19 +SCE_COFFEESCRIPT_STRINGRAW = 20 +SCE_COFFEESCRIPT_TRIPLEVERBATIM = 21 +SCE_COFFEESCRIPT_COMMENTBLOCK = 22 +SCE_COFFEESCRIPT_VERBOSE_REGEX = 23 +SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT = 24 +SCE_COFFEESCRIPT_INSTANCEPROPERTY = 25 +SCE_AVS_DEFAULT = 0 +SCE_AVS_COMMENTBLOCK = 1 +SCE_AVS_COMMENTBLOCKN = 2 +SCE_AVS_COMMENTLINE = 3 +SCE_AVS_NUMBER = 4 +SCE_AVS_OPERATOR = 5 +SCE_AVS_IDENTIFIER = 6 +SCE_AVS_STRING = 7 +SCE_AVS_TRIPLESTRING = 8 +SCE_AVS_KEYWORD = 9 +SCE_AVS_FILTER = 10 +SCE_AVS_PLUGIN = 11 +SCE_AVS_FUNCTION = 12 +SCE_AVS_CLIPPROP = 13 +SCE_AVS_USERDFN = 14 +SCE_ECL_DEFAULT = 0 +SCE_ECL_COMMENT = 1 +SCE_ECL_COMMENTLINE = 2 +SCE_ECL_NUMBER = 3 +SCE_ECL_STRING = 4 +SCE_ECL_WORD0 = 5 +SCE_ECL_OPERATOR = 6 +SCE_ECL_CHARACTER = 7 +SCE_ECL_UUID = 8 +SCE_ECL_PREPROCESSOR = 9 +SCE_ECL_UNKNOWN = 10 +SCE_ECL_IDENTIFIER = 11 +SCE_ECL_STRINGEOL = 12 +SCE_ECL_VERBATIM = 13 +SCE_ECL_REGEX = 14 +SCE_ECL_COMMENTLINEDOC = 15 +SCE_ECL_WORD1 = 16 +SCE_ECL_COMMENTDOCKEYWORD = 17 +SCE_ECL_COMMENTDOCKEYWORDERROR = 18 +SCE_ECL_WORD2 = 19 +SCE_ECL_WORD3 = 20 +SCE_ECL_WORD4 = 21 +SCE_ECL_WORD5 = 22 +SCE_ECL_COMMENTDOC = 23 +SCE_ECL_ADDED = 24 +SCE_ECL_DELETED = 25 +SCE_ECL_CHANGED = 26 +SCE_ECL_MOVED = 27 +SCE_OSCRIPT_DEFAULT = 0 +SCE_OSCRIPT_LINE_COMMENT = 1 +SCE_OSCRIPT_BLOCK_COMMENT = 2 +SCE_OSCRIPT_DOC_COMMENT = 3 +SCE_OSCRIPT_PREPROCESSOR = 4 +SCE_OSCRIPT_NUMBER = 5 +SCE_OSCRIPT_SINGLEQUOTE_STRING = 6 +SCE_OSCRIPT_DOUBLEQUOTE_STRING = 7 +SCE_OSCRIPT_CONSTANT = 8 +SCE_OSCRIPT_IDENTIFIER = 9 +SCE_OSCRIPT_GLOBAL = 10 +SCE_OSCRIPT_KEYWORD = 11 +SCE_OSCRIPT_OPERATOR = 12 +SCE_OSCRIPT_LABEL = 13 +SCE_OSCRIPT_TYPE = 14 +SCE_OSCRIPT_FUNCTION = 15 +SCE_OSCRIPT_OBJECT = 16 +SCE_OSCRIPT_PROPERTY = 17 +SCE_OSCRIPT_METHOD = 18 +SCE_VISUALPROLOG_DEFAULT = 0 +SCE_VISUALPROLOG_KEY_MAJOR = 1 +SCE_VISUALPROLOG_KEY_MINOR = 2 +SCE_VISUALPROLOG_KEY_DIRECTIVE = 3 +SCE_VISUALPROLOG_COMMENT_BLOCK = 4 +SCE_VISUALPROLOG_COMMENT_LINE = 5 +SCE_VISUALPROLOG_COMMENT_KEY = 6 +SCE_VISUALPROLOG_COMMENT_KEY_ERROR = 7 +SCE_VISUALPROLOG_IDENTIFIER = 8 +SCE_VISUALPROLOG_VARIABLE = 9 +SCE_VISUALPROLOG_ANONYMOUS = 10 +SCE_VISUALPROLOG_NUMBER = 11 +SCE_VISUALPROLOG_OPERATOR = 12 +SCE_VISUALPROLOG_CHARACTER = 13 +SCE_VISUALPROLOG_CHARACTER_TOO_MANY = 14 +SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR = 15 +SCE_VISUALPROLOG_STRING = 16 +SCE_VISUALPROLOG_STRING_ESCAPE = 17 +SCE_VISUALPROLOG_STRING_ESCAPE_ERROR = 18 +SCE_VISUALPROLOG_STRING_EOL_OPEN = 19 +SCE_VISUALPROLOG_STRING_VERBATIM = 20 +SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL = 21 +SCE_VISUALPROLOG_STRING_VERBATIM_EOL = 22 +SCE_STTXT_DEFAULT = 0 +SCE_STTXT_COMMENT = 1 +SCE_STTXT_COMMENTLINE = 2 +SCE_STTXT_KEYWORD = 3 +SCE_STTXT_TYPE = 4 +SCE_STTXT_FUNCTION = 5 +SCE_STTXT_FB = 6 +SCE_STTXT_NUMBER = 7 +SCE_STTXT_HEXNUMBER = 8 +SCE_STTXT_PRAGMA = 9 +SCE_STTXT_OPERATOR = 10 +SCE_STTXT_CHARACTER = 11 +SCE_STTXT_STRING1 = 12 +SCE_STTXT_STRING2 = 13 +SCE_STTXT_STRINGEOL = 14 +SCE_STTXT_IDENTIFIER = 15 +SCE_STTXT_DATETIME = 16 +SCE_STTXT_VARS = 17 +SCE_STTXT_PRAGMAS = 18 +SCE_KVIRC_DEFAULT = 0 +SCE_KVIRC_COMMENT = 1 +SCE_KVIRC_COMMENTBLOCK = 2 +SCE_KVIRC_STRING = 3 +SCE_KVIRC_WORD = 4 +SCE_KVIRC_KEYWORD = 5 +SCE_KVIRC_FUNCTION_KEYWORD = 6 +SCE_KVIRC_FUNCTION = 7 +SCE_KVIRC_VARIABLE = 8 +SCE_KVIRC_NUMBER = 9 +SCE_KVIRC_OPERATOR = 10 +SCE_KVIRC_STRING_FUNCTION = 11 +SCE_KVIRC_STRING_VARIABLE = 12 +SCE_RUST_DEFAULT = 0 +SCE_RUST_COMMENTBLOCK = 1 +SCE_RUST_COMMENTLINE = 2 +SCE_RUST_COMMENTBLOCKDOC = 3 +SCE_RUST_COMMENTLINEDOC = 4 +SCE_RUST_NUMBER = 5 +SCE_RUST_WORD = 6 +SCE_RUST_WORD2 = 7 +SCE_RUST_WORD3 = 8 +SCE_RUST_WORD4 = 9 +SCE_RUST_WORD5 = 10 +SCE_RUST_WORD6 = 11 +SCE_RUST_WORD7 = 12 +SCE_RUST_STRING = 13 +SCE_RUST_STRINGR = 14 +SCE_RUST_CHARACTER = 15 +SCE_RUST_OPERATOR = 16 +SCE_RUST_IDENTIFIER = 17 +SCE_RUST_LIFETIME = 18 +SCE_RUST_MACRO = 19 +SCE_RUST_LEXERROR = 20 +SCE_RUST_BYTESTRING = 21 +SCE_RUST_BYTESTRINGR = 22 +SCE_RUST_BYTECHARACTER = 23 +SCE_DMAP_DEFAULT = 0 +SCE_DMAP_COMMENT = 1 +SCE_DMAP_NUMBER = 2 +SCE_DMAP_STRING1 = 3 +SCE_DMAP_STRING2 = 4 +SCE_DMAP_STRINGEOL = 5 +SCE_DMAP_OPERATOR = 6 +SCE_DMAP_IDENTIFIER = 7 +SCE_DMAP_WORD = 8 +SCE_DMAP_WORD2 = 9 +SCE_DMAP_WORD3 = 10 +SCE_DMIS_DEFAULT = 0 +SCE_DMIS_COMMENT = 1 +SCE_DMIS_STRING = 2 +SCE_DMIS_NUMBER = 3 +SCE_DMIS_KEYWORD = 4 +SCE_DMIS_MAJORWORD = 5 +SCE_DMIS_MINORWORD = 6 +SCE_DMIS_UNSUPPORTED_MAJOR = 7 +SCE_DMIS_UNSUPPORTED_MINOR = 8 +SCE_DMIS_LABEL = 9 +SCE_REG_DEFAULT = 0 +SCE_REG_COMMENT = 1 +SCE_REG_VALUENAME = 2 +SCE_REG_STRING = 3 +SCE_REG_HEXDIGIT = 4 +SCE_REG_VALUETYPE = 5 +SCE_REG_ADDEDKEY = 6 +SCE_REG_DELETEDKEY = 7 +SCE_REG_ESCAPED = 8 +SCE_REG_KEYPATH_GUID = 9 +SCE_REG_STRING_GUID = 10 +SCE_REG_PARAMETER = 11 +SCE_REG_OPERATOR = 12 +SCE_BIBTEX_DEFAULT = 0 +SCE_BIBTEX_ENTRY = 1 +SCE_BIBTEX_UNKNOWN_ENTRY = 2 +SCE_BIBTEX_KEY = 3 +SCE_BIBTEX_PARAMETER = 4 +SCE_BIBTEX_VALUE = 5 +SCE_BIBTEX_COMMENT = 6 +SCE_HEX_DEFAULT = 0 +SCE_HEX_RECSTART = 1 +SCE_HEX_RECTYPE = 2 +SCE_HEX_RECTYPE_UNKNOWN = 3 +SCE_HEX_BYTECOUNT = 4 +SCE_HEX_BYTECOUNT_WRONG = 5 +SCE_HEX_NOADDRESS = 6 +SCE_HEX_DATAADDRESS = 7 +SCE_HEX_RECCOUNT = 8 +SCE_HEX_STARTADDRESS = 9 +SCE_HEX_ADDRESSFIELD_UNKNOWN = 10 +SCE_HEX_EXTENDEDADDRESS = 11 +SCE_HEX_DATA_ODD = 12 +SCE_HEX_DATA_EVEN = 13 +SCE_HEX_DATA_UNKNOWN = 14 +SCE_HEX_DATA_EMPTY = 15 +SCE_HEX_CHECKSUM = 16 +SCE_HEX_CHECKSUM_WRONG = 17 +SCE_HEX_GARBAGE = 18 +SCE_JSON_DEFAULT = 0 +SCE_JSON_NUMBER = 1 +SCE_JSON_STRING = 2 +SCE_JSON_STRINGEOL = 3 +SCE_JSON_PROPERTYNAME = 4 +SCE_JSON_ESCAPESEQUENCE = 5 +SCE_JSON_LINECOMMENT = 6 +SCE_JSON_BLOCKCOMMENT = 7 +SCE_JSON_OPERATOR = 8 +SCE_JSON_URI = 9 +SCE_JSON_COMPACTIRI = 10 +SCE_JSON_KEYWORD = 11 +SCE_JSON_LDKEYWORD = 12 +SCE_JSON_ERROR = 13 +SCE_EDI_DEFAULT = 0 +SCE_EDI_SEGMENTSTART = 1 +SCE_EDI_SEGMENTEND = 2 +SCE_EDI_SEP_ELEMENT = 3 +SCE_EDI_SEP_COMPOSITE = 4 +SCE_EDI_SEP_RELEASE = 5 +SCE_EDI_UNA = 6 +SCE_EDI_UNH = 7 +SCE_EDI_BADSEGMENT = 8 +SCE_STATA_DEFAULT = 0 +SCE_STATA_COMMENT = 1 +SCE_STATA_COMMENTLINE = 2 +SCE_STATA_COMMENTBLOCK = 3 +SCE_STATA_NUMBER = 4 +SCE_STATA_OPERATOR = 5 +SCE_STATA_IDENTIFIER = 6 +SCE_STATA_STRING = 7 +SCE_STATA_TYPE = 8 +SCE_STATA_WORD = 9 +SCE_STATA_GLOBAL_MACRO = 10 +SCE_STATA_MACRO = 11 +SCE_SAS_DEFAULT = 0 +SCE_SAS_COMMENT = 1 +SCE_SAS_COMMENTLINE = 2 +SCE_SAS_COMMENTBLOCK = 3 +SCE_SAS_NUMBER = 4 +SCE_SAS_OPERATOR = 5 +SCE_SAS_IDENTIFIER = 6 +SCE_SAS_STRING = 7 +SCE_SAS_TYPE = 8 +SCE_SAS_WORD = 9 +SCE_SAS_GLOBAL_MACRO = 10 +SCE_SAS_MACRO = 11 +SCE_SAS_MACRO_KEYWORD = 12 +SCE_SAS_BLOCK_KEYWORD = 13 +SCE_SAS_MACRO_FUNCTION = 14 +SCE_SAS_STATEMENT = 15 +SCE_NIM_DEFAULT = 0 +SCE_NIM_COMMENT = 1 +SCE_NIM_COMMENTDOC = 2 +SCE_NIM_COMMENTLINE = 3 +SCE_NIM_COMMENTLINEDOC = 4 +SCE_NIM_NUMBER = 5 +SCE_NIM_STRING = 6 +SCE_NIM_CHARACTER = 7 +SCE_NIM_WORD = 8 +SCE_NIM_TRIPLE = 9 +SCE_NIM_TRIPLEDOUBLE = 10 +SCE_NIM_BACKTICKS = 11 +SCE_NIM_FUNCNAME = 12 +SCE_NIM_STRINGEOL = 13 +SCE_NIM_NUMERROR = 14 +SCE_NIM_OPERATOR = 15 +SCE_NIM_IDENTIFIER = 16 +SCE_CIL_DEFAULT = 0 +SCE_CIL_COMMENT = 1 +SCE_CIL_COMMENTLINE = 2 +SCE_CIL_WORD = 3 +SCE_CIL_WORD2 = 4 +SCE_CIL_WORD3 = 5 +SCE_CIL_STRING = 6 +SCE_CIL_LABEL = 7 +SCE_CIL_OPERATOR = 8 +SCE_CIL_IDENTIFIER = 9 +SCE_CIL_STRINGEOL = 10 +SCE_X12_DEFAULT = 0 +SCE_X12_BAD = 1 +SCE_X12_ENVELOPE = 2 +SCE_X12_FUNCTIONGROUP = 3 +SCE_X12_TRANSACTIONSET = 4 +SCE_X12_SEGMENTHEADER = 5 +SCE_X12_SEGMENTEND = 6 +SCE_X12_SEP_ELEMENT = 7 +SCE_X12_SEP_SUBELEMENT = 8 +SCE_DF_DEFAULT = 0 +SCE_DF_IDENTIFIER = 1 +SCE_DF_METATAG = 2 +SCE_DF_IMAGE = 3 +SCE_DF_COMMENTLINE = 4 +SCE_DF_PREPROCESSOR = 5 +SCE_DF_PREPROCESSOR2 = 6 +SCE_DF_NUMBER = 7 +SCE_DF_HEXNUMBER = 8 +SCE_DF_WORD = 9 +SCE_DF_STRING = 10 +SCE_DF_STRINGEOL = 11 +SCE_DF_SCOPEWORD = 12 +SCE_DF_OPERATOR = 13 +SCE_DF_ICODE = 14 +SCE_HOLLYWOOD_DEFAULT = 0 +SCE_HOLLYWOOD_COMMENT = 1 +SCE_HOLLYWOOD_COMMENTBLOCK = 2 +SCE_HOLLYWOOD_NUMBER = 3 +SCE_HOLLYWOOD_KEYWORD = 4 +SCE_HOLLYWOOD_STDAPI = 5 +SCE_HOLLYWOOD_PLUGINAPI = 6 +SCE_HOLLYWOOD_PLUGINMETHOD = 7 +SCE_HOLLYWOOD_STRING = 8 +SCE_HOLLYWOOD_STRINGBLOCK = 9 +SCE_HOLLYWOOD_PREPROCESSOR = 10 +SCE_HOLLYWOOD_OPERATOR = 11 +SCE_HOLLYWOOD_IDENTIFIER = 12 +SCE_HOLLYWOOD_CONSTANT = 13 +SCE_HOLLYWOOD_HEXNUMBER = 14 +SCE_RAKU_DEFAULT = 0 +SCE_RAKU_ERROR = 1 +SCE_RAKU_COMMENTLINE = 2 +SCE_RAKU_COMMENTEMBED = 3 +SCE_RAKU_POD = 4 +SCE_RAKU_CHARACTER = 5 +SCE_RAKU_HEREDOC_Q = 6 +SCE_RAKU_HEREDOC_QQ = 7 +SCE_RAKU_STRING = 8 +SCE_RAKU_STRING_Q = 9 +SCE_RAKU_STRING_QQ = 10 +SCE_RAKU_STRING_Q_LANG = 11 +SCE_RAKU_STRING_VAR = 12 +SCE_RAKU_REGEX = 13 +SCE_RAKU_REGEX_VAR = 14 +SCE_RAKU_ADVERB = 15 +SCE_RAKU_NUMBER = 16 +SCE_RAKU_PREPROCESSOR = 17 +SCE_RAKU_OPERATOR = 18 +SCE_RAKU_WORD = 19 +SCE_RAKU_FUNCTION = 20 +SCE_RAKU_IDENTIFIER = 21 +SCE_RAKU_TYPEDEF = 22 +SCE_RAKU_MU = 23 +SCE_RAKU_POSITIONAL = 24 +SCE_RAKU_ASSOCIATIVE = 25 +SCE_RAKU_CALLABLE = 26 +SCE_RAKU_GRAMMAR = 27 +SCE_RAKU_CLASS = 28 diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index 4ae7eab49c..b1beb6f156 100644 --- a/Pythonwin/pywin/scintilla/view.py +++ b/Pythonwin/pywin/scintilla/view.py @@ -334,7 +334,9 @@ 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( - f'View.AppendMenu(): Unknown event "{event}" specified for menu text "{text}" - ignored' + 'View.AppendMenu(): Unknown event "{}" specified for menu text "{}" - ignored'.format( + event, text + ) ) return keyname = configManager.get_key_binding(event, self._GetSubConfigNames()) @@ -510,7 +512,7 @@ def list2dict(l): pass except: win32ui.SetStatusText( - f"Error attempting to get object attributes - {repr(sys.exc_info()[0])}" + f"Error attempting to get object attributes - {sys.exc_info()[0]!r}" ) items = [ @@ -745,7 +747,7 @@ def CalculatePageRanges(self, dc, pInfo): pageStart = self.FormatRange(dc, pageStart, textLen, rc, 0) maxPage += 1 self.starts[maxPage] = pageStart - # And a sentinal for one page past the end + # And a sentinel for one page past the end self.starts[maxPage + 1] = textLen # When actually printing, maxPage doesn't have any effect at this late state. # but is needed to make the Print Preview work correctly. @@ -822,8 +824,9 @@ def LoadConfiguration(): configManager = ConfigManager(configName) if configManager.last_error: bTryDefault = 0 - msg = ( - f"Error loading configuration '{configName}'\n\n{configManager.last_error}" + msg = "Error loading configuration '{}'\n\n{}".format( + configName, + configManager.last_error, ) if configName != "default": msg += "\n\nThe default configuration will be loaded." diff --git a/Pythonwin/pywin/tools/browser.py b/Pythonwin/pywin/tools/browser.py index 6a301c3de0..8346d7d019 100644 --- a/Pythonwin/pywin/tools/browser.py +++ b/Pythonwin/pywin/tools/browser.py @@ -49,20 +49,13 @@ def __repr__(self): type = self.GetHLIType() except: type = "Generic" - return ( - "HLIPythonObject(" - + type - + ") - name: " - + self.name - + " object: " - + repr(self.myobject) - ) + return f"HLIPythonObject({type}) - name: {self.name} object: {self.myobject!r}" def GetText(self): try: - return str(self.name) + " (" + self.GetHLIType() + ")" + return f"{self.name} ({self.GetHLIType()})" except AttributeError: - return str(self.name) + " = " + repr(self.myobject) + return f"{self.name} = {self.myobject!r}" def InsertDocString(self, lst): ob = None @@ -260,7 +253,7 @@ def GetSubList(self): ret = [] pos = 0 for item in self.myobject: - ret.append(MakeHLI(item, "[" + str(pos) + "]")) + ret.append(MakeHLI(item, f"[{pos}]")) pos += 1 self.InsertDocString(ret) return ret diff --git a/Pythonwin/pywin/tools/hierlist.py b/Pythonwin/pywin/tools/hierlist.py index 0f06b8c0e5..1e4f8d7682 100644 --- a/Pythonwin/pywin/tools/hierlist.py +++ b/Pythonwin/pywin/tools/hierlist.py @@ -99,7 +99,9 @@ def HierInit(self, parent, listControl=None): # Used when window first exists. lbid = listControl.GetDlgCtrlID() assert ( self.listBoxId is None or self.listBoxId == lbid - ), f"An invalid listbox control ID has been specified (specified as {self.listBoxId}, but exists as {lbid})" + ), "An invalid listbox control ID has been specified (specified as {}, but exists as {})".format( + self.listBoxId, 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 70a6aaac79..d8f854ff45 100644 --- a/Pythonwin/pywin/tools/regedit.py +++ b/Pythonwin/pywin/tools/regedit.py @@ -332,8 +332,10 @@ def __eq__(self, other): ) def __repr__(self): - return ( - f"<{self.__class__.__name__} with root={self.keyRoot}, key={self.keyName}>" + return "<{} with root={}, key={}>".format( + self.__class__.__name__, + self.keyRoot, + self.keyName, ) def GetText(self): diff --git a/adodbapi/adodbapi.py b/adodbapi/adodbapi.py index 4e85bc525b..19adbfb30c 100644 --- a/adodbapi/adodbapi.py +++ b/adodbapi/adodbapi.py @@ -66,7 +66,7 @@ def getIndexedValue(obj, index): def make_COM_connecter(): try: pythoncom.CoInitialize() # v2.1 Paj - c = Dispatch("ADODB.Connection") # connect _after_ CoIninialize v2.1.1 adamvan + c = Dispatch("ADODB.Connection") # connect _after_ CoInitialize v2.1.1 adamvan except: raise api.InterfaceError( "Windows COM Error: Dispatch('ADODB.Connection') failed." @@ -395,9 +395,7 @@ def _rollback(self): # If attributes has adXactAbortRetaining it performs retaining aborts that is, # calling RollbackTrans automatically starts a new transaction. Not all providers support this. # If not, we will have to start a new transaction by this command: - if ( - not self.transaction_level - ): # if self.transaction_level == 0 or self.transaction_level is None: + if not self.transaction_level: self.transaction_level = self.connector.BeginTrans() except Exception as e: self._raiseConnectionError(api.ProgrammingError, e) @@ -595,7 +593,7 @@ def _raiseCursorError(self, errorclass, errorvalue): eh(self.connection, self, errorclass, errorvalue) def build_column_info(self, recordset): - self.converters = [] # convertion function for each column + self.converters = [] # conversion function for each column self.columnNames = {} # names of columns {lowercase name : number,...} self._description = None @@ -634,9 +632,8 @@ def _makeDescriptionFromRS(self): if self.rs.EOF or self.rs.BOF: display_size = None else: - display_size = ( - f.ActualSize - ) # TODO: Is this the correct defintion according to the DB API 2 Spec ? + # TODO: Is this the correct defintion according to the DB API 2 Spec ? + display_size = f.ActualSize null_ok = bool(f.Attributes & adc.adFldMayBeNull) # v2.1 Cole desc.append( ( @@ -774,9 +771,8 @@ def get_returned_parameters(self): after the last recordset has been read. In that case, you must coll nextset() until it returns None, then call this method to get your returned information.""" - retLst = ( - [] - ) # store procedures may return altered parameters, including an added "return value" item + # store procedures may return altered parameters, including an added "return value" item + retLst = [] for p in tuple(self.cmd.Parameters): if verbose > 2: print( @@ -907,9 +903,8 @@ def _buildADOparameterList(self, parameters, sproc=False): ) i += 1 else: # -- build own parameter list - if ( - self._parameter_names - ): # we expect a dictionary of parameters, this is the list of expected names + # we expect a dictionary of parameters, this is the list of expected names + if self._parameter_names: for parm_name in self._parameter_names: elem = parameters[parm_name] adotype = api.pyTypeToADOType(elem) diff --git a/adodbapi/examples/db_print.py b/adodbapi/examples/db_print.py index c0eb83ee4d..fc86a8b3c8 100644 --- a/adodbapi/examples/db_print.py +++ b/adodbapi/examples/db_print.py @@ -1,4 +1,4 @@ -""" db_print.py -- a simple demo for ADO database reads.""" +"""db_print.py -- a simple demo for ADO database reads.""" import sys diff --git a/adodbapi/examples/db_table_names.py b/adodbapi/examples/db_table_names.py index 907bdb85ea..17ff583491 100644 --- a/adodbapi/examples/db_table_names.py +++ b/adodbapi/examples/db_table_names.py @@ -1,4 +1,4 @@ -""" db_table_names.py -- a simple demo for ADO database table listing.""" +"""db_table_names.py -- a simple demo for ADO database table listing.""" import sys diff --git a/adodbapi/process_connect_string.py b/adodbapi/process_connect_string.py index d8b29f280c..320d1bb35e 100644 --- a/adodbapi/process_connect_string.py +++ b/adodbapi/process_connect_string.py @@ -1,4 +1,4 @@ -""" a clumsy attempt at a macro language to let the programmer execute code on the server (ex: determine 64bit)""" +"""a clumsy attempt at a macro language to let the programmer execute code on the server (ex: determine 64bit)""" from . import is64bit @@ -45,6 +45,8 @@ def macro_call(macro_name, args, kwargs): return new_key, platform.node() elif macro_name == "getenv": # expand the server's environment variable args[1] + import os + try: dflt = args[2] # if not found, default from args[2] except IndexError: # or blank @@ -86,13 +88,11 @@ def process( dsn = args[0] except IndexError: dsn = None - if isinstance( - dsn, dict - ): # as a convenience the first argument may be django settings + # as a convenience the first argument may be django settings + if isinstance(dsn, dict): kwargs.update(dsn) - elif ( - dsn - ): # the connection string is passed to the connection as part of the keyword dictionary + # the connection string is passed to the connection as part of the keyword dictionary + elif dsn: kwargs["connection_string"] = dsn try: a1 = args[1] diff --git a/adodbapi/test/adodbapitest.py b/adodbapi/test/adodbapitest.py index 1b50e595f8..88dab12671 100644 --- a/adodbapi/test/adodbapitest.py +++ b/adodbapi/test/adodbapitest.py @@ -1,4 +1,4 @@ -""" Unit tests version 2.6.1.0 for adodbapi""" +"""Unit tests version 2.6.1.0 for adodbapi""" """ adodbapi - A python DB API 2.0 interface to Microsoft ADO @@ -213,7 +213,7 @@ def testUserDefinedConversionForExactNumericTypes(self): # now return strings adodbapi.variantConversions[ado_consts.adNumeric] = adodbapi.cvtString self.helpTestDataType("numeric(18,2)", "NUMBER", "3.45") - # now a completly weird user defined convertion + # now a completely weird user defined conversion adodbapi.variantConversions[ado_consts.adNumeric] = ( lambda x: "!!This function returns a funny unicode string %s!!" % x ) @@ -228,7 +228,7 @@ def testUserDefinedConversionForExactNumericTypes(self): finally: # now reset the converter to its original function adodbapi.variantConversions[ado_consts.adNumeric] = ( - oldconverter # Restore the original convertion function + oldconverter # Restore the original conversion function ) def helpTestDataType( @@ -325,15 +325,16 @@ def helpTestDataType( rs = crsr.fetchone() if allowedReturnValues: allowedTypes = tuple([type(aRV) for aRV in allowedReturnValues]) - assert isinstance( - rs[0], allowedTypes - ), 'result type "%s" must be one of %s' % (type(rs[0]), allowedTypes) + assert isinstance(rs[0], allowedTypes), ( + 'result type "%s" must be one of %s' % (type(rs[0]), allowedTypes) + ) else: - assert isinstance( - rs[0], type(pyData) - ), 'result type "%s" must be instance of %s' % ( - type(rs[0]), - type(pyData), + assert isinstance(rs[0], type(pyData)), ( + 'result type "%s" must be instance of %s' + % ( + type(rs[0]), + type(pyData), + ) ) if compareAlmostEqual and DBAPIDataTypeString == "DATETIME": @@ -343,9 +344,9 @@ def helpTestDataType( elif compareAlmostEqual: s = float(pyData) v = float(rs[0]) - assert ( - abs(v - s) / s < 0.00001 - ), "Values not almost equal recvd=%s, expected=%f" % (rs[0], s) + assert abs(v - s) / s < 0.00001, ( + "Values not almost equal recvd=%s, expected=%f" % (rs[0], s) + ) else: if allowedReturnValues: ok = False @@ -487,7 +488,7 @@ def testDataTypeDate(self): ) def testDataTypeBinary(self): - binfld = b"\x07\x00\xE2\x40*" + binfld = b"\x07\x00\xe2\x40*" arv = [binfld, adodbapi.Binary(binfld), bytes(binfld)] if self.getEngine() == "PostgreSQL": self.helpTestDataType( @@ -692,9 +693,9 @@ def testRowIterator(self): rec = crsr.fetchone() # check that stepping through an emulated row works for j in range(len(inParam)): - assert ( - rec[j] == inParam[j] - ), 'returned value:"%s" != test value:"%s"' % (rec[j], inParam[j]) + assert rec[j] == inParam[j], ( + 'returned value:"%s" != test value:"%s"' % (rec[j], inParam[j]) + ) # check that we can get a complete tuple from a row assert ( tuple(rec) == inParam diff --git a/adodbapi/test/dbapi20.py b/adodbapi/test/dbapi20.py index 5639e4c3c7..ea920d42b2 100644 --- a/adodbapi/test/dbapi20.py +++ b/adodbapi/test/dbapi20.py @@ -1,14 +1,14 @@ #!/usr/bin/env python -""" Python DB API 2.0 driver compliance unit test suite. +"""Python DB API 2.0 driver compliance unit test suite. - This software is Public Domain and may be used without restrictions. + This software is Public Domain and may be used without restrictions. - "Now we have booze and barflies entering the discussion, plus rumours of - DBAs on drugs... and I won't tell you what flashes through my mind each - time I read the subject line with 'Anal Compliance' in it. All around - this is turning out to be a thoroughly unwholesome unit test." +"Now we have booze and barflies entering the discussion, plus rumours of + DBAs on drugs... and I won't tell you what flashes through my mind each + time I read the subject line with 'Anal Compliance' in it. All around + this is turning out to be a thoroughly unwholesome unit test." - -- Ian Bicking + -- Ian Bicking """ __version__ = "$Revision: 1.15.0 $"[11:-2] @@ -71,7 +71,7 @@ # - Now a subclass of TestCase, to avoid requiring the driver stub # to use multiple inheritance # - Reversed the polarity of buggy test in test_description -# - Test exception heirarchy correctly +# - Test exception hierarchy correctly # - self.populate is now self._populate(), so if a driver stub # overrides self.ddl1 this change propogates # - VARCHAR columns now have a width, which will hopefully make the @@ -198,7 +198,7 @@ def test_paramstyle(self): def test_Exceptions(self): # Make sure required exceptions exist, and are in the - # defined heirarchy. + # defined hierarchy. if sys.version[0] == "3": # under Python 3 StardardError no longer exists self.assertTrue(issubclass(self.driver.Warning, Exception)) self.assertTrue(issubclass(self.driver.Error, Exception)) diff --git a/adodbapi/test/setuptestframework.py b/adodbapi/test/setuptestframework.py index 65b99e990f..4b9de6a7d4 100644 --- a/adodbapi/test/setuptestframework.py +++ b/adodbapi/test/setuptestframework.py @@ -1,6 +1,7 @@ #!/usr/bin/python2 # Configure this in order to run the testcases. "setuptestframework.py v 2.6.0.8" + import os import shutil import tempfile @@ -55,7 +56,7 @@ def makeadopackage(testfolder): shutil.copy(os.path.join(adoPath, f), newpackage) return testfolder else: - raise OSError("Connot find source of adodbapi to test.") + raise OSError("Cannot find source of adodbapi to test.") def makemdb(testfolder, mdb_name): diff --git a/com/win32com/client/__init__.py b/com/win32com/client/__init__.py index 055b7c9cf5..0cc25a431d 100644 --- a/com/win32com/client/__init__.py +++ b/com/win32com/client/__init__.py @@ -556,7 +556,7 @@ def _ApplyTypes_(self, dispid, wFlags, retType, argTypes, user, resultCLSID, *ar def __getattr__(self, attr): args = self._prop_map_get_.get(attr) if args is None: - raise AttributeError(f"'{repr(self)}' object has no attribute '{attr}'") + raise AttributeError(f"'{self!r}' object has no attribute '{attr}'") return self._ApplyTypes_(*args) def __setattr__(self, attr, value): @@ -566,7 +566,7 @@ def __setattr__(self, attr, value): try: args, defArgs = self._prop_map_put_[attr] except KeyError: - raise AttributeError(f"'{repr(self)}' object has no attribute '{attr}'") + raise AttributeError(f"'{self!r}' object has no attribute '{attr}'") self._oleobj_.Invoke(*(args + (value,) + defArgs)) def _get_good_single_object_(self, obj, obUserName=None, resultCLSID=None): diff --git a/com/win32com/client/build.py b/com/win32com/client/build.py index f8991683d2..4b7628438e 100644 --- a/com/win32com/client/build.py +++ b/com/win32com/client/build.py @@ -16,6 +16,7 @@ # # OleItem, DispatchItem, MapEntry, BuildCallList() is used by makepy +import builtins import datetime import string from itertools import chain @@ -98,10 +99,10 @@ def __init__( def __repr__(self): return ( - 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}" - ) + "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) def GetResultCLSID(self): rc = self.resultCLSID @@ -114,9 +115,8 @@ def GetResultCLSIDStr(self): rc = self.GetResultCLSID() if rc is None: return "None" - return repr( - str(rc) - ) # Convert the IID object to a string, then to a string in a string. + # Convert the IID object to a string in a string. + return f"'{rc}'" def GetResultName(self): if self.resultDocumentation is None: @@ -404,7 +404,7 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): if len(bad_params) == 0 and len(retDesc) == 2 and retDesc[1] == 0: rd = retDesc[0] if rd in NoTranslateMap: - s = "%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)" % ( + s = "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {}{})".format( linePrefix, id, fdesc[4], @@ -413,42 +413,46 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): _BuildArgList(fdesc, names), ) elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]: - s = "%s\tret = self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)\n" % ( + s = "{}\tret = self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})\n".format( linePrefix, id, fdesc[4], retDesc, - repr(argsDesc), + argsDesc, _BuildArgList(fdesc, names), ) s += f"{linePrefix}\tif ret is not None:\n" if rd == pythoncom.VT_UNKNOWN: - s += f"{linePrefix}\t\t# See if this IUnknown is really an IDispatch\n" + s += "{}\t\t# See if this IUnknown is really an IDispatch\n".format( + linePrefix + ) s += f"{linePrefix}\t\ttry:\n" - s += f"{linePrefix}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n" + s += "{}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n".format( + linePrefix + ) s += f"{linePrefix}\t\texcept pythoncom.error:\n" s += f"{linePrefix}\t\t\treturn ret\n" - s += f"{linePrefix}\t\tret = Dispatch(ret, {repr(name)}, {resclsid})\n" - s += "%s\treturn ret" % linePrefix + s += f"{linePrefix}\t\tret = Dispatch(ret, {name!r}, {resclsid})\n" + s += f"{linePrefix}\treturn ret" elif rd == pythoncom.VT_BSTR: s = f"{linePrefix}\t# Result is a Unicode object\n" - s += "%s\treturn self._oleobj_.InvokeTypes(%d, LCID, %s, %s, %s%s)" % ( + s += "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})".format( linePrefix, id, fdesc[4], retDesc, - repr(argsDesc), + argsDesc, _BuildArgList(fdesc, names), ) # else s remains None if s is None: - s = "%s\treturn self._ApplyTypes_(%d, %s, %s, %s, %s, %s%s)" % ( + s = "{}\treturn self._ApplyTypes_({}, {}, {}, {}, {!r}, {}{})".format( linePrefix, id, fdesc[4], retDesc, argsDesc, - repr(name), + name, resclsid, _BuildArgList(fdesc, names), ) @@ -650,7 +654,7 @@ def MakePublicAttributeName(className, is_global=False): if ret == className: ret = ret.upper() return ret - elif is_global and hasattr(__builtins__, className): + elif is_global and hasattr(builtins, className): # builtins may be mixed case. If capitalizing it doesn't change it, # force to all uppercase (eg, "None", "True" become "NONE", "TRUE" ret = className.capitalize() diff --git a/com/win32com/client/combrowse.py b/com/win32com/client/combrowse.py index f83aa9c9b0..4587a9aab8 100644 --- a/com/win32com/client/combrowse.py +++ b/com/win32com/client/combrowse.py @@ -1,25 +1,25 @@ """A utility for browsing COM objects. - Usage: +Usage: - Command Prompt + Command Prompt - Use the command *"python.exe combrowse.py"*. This will display - display a fairly small, modal dialog. + Use the command *"python.exe combrowse.py"*. This will display + display a fairly small, modal dialog. - Pythonwin + Pythonwin - Use the "Run Script" menu item, and this will create the browser in an - MDI window. This window can be fully resized. + Use the "Run Script" menu item, and this will create the browser in an + MDI window. This window can be fully resized. - Details +Details - This module allows browsing of registered Type Libraries, COM categories, - and running COM objects. The display is similar to the Pythonwin object - browser, and displays the objects in a hierarchical window. + This module allows browsing of registered Type Libraries, COM categories, + and running COM objects. The display is similar to the Pythonwin object + browser, and displays the objects in a hierarchical window. - Note that this module requires the win32ui (ie, Pythonwin) distribution to - work. + Note that this module requires the win32ui (ie, Pythonwin) distribution to + work. """ @@ -581,7 +581,6 @@ def GetSubList(self): def main(modal=True, mdi=False): - root = HLIRoot("COM Browser") if mdi and "pywin.framework.app" in sys.modules: # do it in a MDI window diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index 9e5e7ce007..3738da9031 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -389,9 +389,10 @@ def _get_good_object_(self, ob, userName=None, ReturnCLSID=None): elif isinstance(ob, tuple): return tuple( map( - lambda o, s=self, oun=userName, rc=ReturnCLSID: s._get_good_single_object_( - o, oun, rc - ), + lambda o, + s=self, + oun=userName, + rc=ReturnCLSID: s._get_good_single_object_(o, oun, rc), ob, ) ) @@ -460,13 +461,13 @@ def _print_details_(self): print("\t", method) print("Props:") for prop, entry in self._olerepr_.propMap.items(): - print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") + print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") print("Get Props:") for prop, entry in self._olerepr_.propMapGet.items(): - print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") + print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") print("Put Props:") for prop, entry in self._olerepr_.propMapPut.items(): - print(f"\t{prop} = 0x{entry.dispid:x} - {repr(entry)}") + print(f"\t{prop} = 0x{entry.dispid:x} - {entry!r}") except: traceback.print_exc() @@ -534,7 +535,9 @@ def _FlagAsMethod(self, *methodNames): def __AttrToID__(self, attr): debug_attr_print( - f"Calling GetIDsOfNames for property {attr} in Dispatch container {self._username_}" + "Calling GetIDsOfNames for property {} in Dispatch container {}".format( + attr, self._username_ + ) ) return self._oleobj_.GetIDsOfNames(0, attr) @@ -637,7 +640,7 @@ def __setattr__(self, attr, value): return # Allow property assignment. debug_attr_print( - f"SetAttr called for {self._username_}.{attr}={repr(value)} on DispatchContainer" + f"SetAttr called for {self._username_}.{attr}={value!r} on DispatchContainer" ) if self._olerepr_: @@ -686,7 +689,9 @@ def __setattr__(self, attr, value): self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value) self._olerepr_.propMap[attr] = entry debug_attr_print( - f"__setattr__ property {attr} (id=0x{entry.dispid:x}) in Dispatch container {self._username_}" + "__setattr__ property {} (id=0x{:x}) in Dispatch container {}".format( + attr, entry.dispid, self._username_ + ) ) return except pythoncom.com_error: diff --git a/com/win32com/client/gencache.py b/com/win32com/client/gencache.py index 4a6428803a..717f2a9c72 100644 --- a/com/win32com/client/gencache.py +++ b/com/win32com/client/gencache.py @@ -415,7 +415,9 @@ def ForgetAboutTypelibInterface(typelib_ob): except KeyError: # Not worth raising an exception - maybe they don't know we only remember for demand generated, etc. print( - f"ForgetAboutTypelibInterface:: Warning - type library with info {info} is not being remembered!" + "ForgetAboutTypelibInterface:: Warning - type library with info {} is not being remembered!".format( + info + ) ) # and drop any version redirects to it for key, val in versionRedirectMap.items(): @@ -511,7 +513,10 @@ def EnsureModule( bValidateFile = 0 if module is not None and bValidateFile: assert not is_readonly, "Can't validate in a read-only gencache" - filePathPrefix = f"{GetGeneratePath()}\\{GetGeneratedFileName(typelibCLSID, lcid, major, minor)}" + filePathPrefix = "{}\\{}".format( + GetGeneratePath(), + GetGeneratedFileName(typelibCLSID, lcid, major, minor), + ) filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".py" if __debug__: @@ -545,7 +550,10 @@ def EnsureModule( bReloadNeeded = 1 else: minor = module.MinorVersion - filePathPrefix = f"{GetGeneratePath()}\\{GetGeneratedFileName(typelibCLSID, lcid, major, minor)}" + filePathPrefix = "{}\\{}".format( + GetGeneratePath(), + GetGeneratedFileName(typelibCLSID, lcid, major, minor), + ) filePath = filePathPrefix + ".py" filePathPyc = filePathPrefix + ".pyc" # print("Trying py stat: ", filePath) @@ -740,7 +748,9 @@ def Rebuild(verbose=1): AddModuleToCache(iid, lcid, major, minor, verbose, 0) except: print( - f"Could not add module {info} - {sys.exc_info()[0]}: {sys.exc_info()[1]}" + "Could not add module {} - {}: {}".format( + 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 0708c58d38..aad03afa17 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -113,7 +113,7 @@ def __lt__(self, other): return self.order < other.order def __repr__(self): - return "OleItem: doc=%s, order=%d" % (repr(self.doc), self.order) + return f"OleItem: doc={self.doc!r}, order={self.order}" class RecordItem(build.OleItem, WritableItem): @@ -233,10 +233,7 @@ def WriteEnumerationItems(self, stream): # Sanitize it, in case the repr contains its own quotes. (??? line breaks too ???) use = use.replace('"', "'") use = ( - '"' - + use - + '"' - + " # This VARIANT type cannot be converted automatically" + f'"{use}" # This VARIANT type cannot be converted automatically' ) print( "\t%-30s=%-10s # from enum %s" @@ -342,11 +339,11 @@ def WriteClassHeader(self, generator): ) except pythoncom.com_error: pass - print("\tCLSID = " + repr(self.clsid), file=stream) + print(f"\tCLSID = {self.clsid!r}", file=stream) if self.coclass_clsid is None: print("\tcoclass_clsid = None", file=stream) else: - print("\tcoclass_clsid = " + repr(self.coclass_clsid), file=stream) + print(f"\tcoclass_clsid = {self.coclass_clsid!r}", file=stream) print(file=stream) self.bWritten = 1 @@ -364,11 +361,11 @@ def WriteEventSinkClassHeader(self, generator): ) except pythoncom.com_error: pass - print("\tCLSID = CLSID_Sink = " + repr(self.clsid), file=stream) + print(f"\tCLSID = CLSID_Sink = {self.clsid!r}", file=stream) if self.coclass_clsid is None: print("\tcoclass_clsid = None", file=stream) else: - print("\tcoclass_clsid = " + repr(self.coclass_clsid), file=stream) + print(f"\tcoclass_clsid = {self.coclass_clsid!r}", file=stream) print("\t_public_methods_ = [] # For COM Server support", file=stream) WriteSinkEventMap(self, stream) print(file=stream) @@ -542,7 +539,9 @@ def WriteClassBody(self, generator): if generator.bBuildHidden or not entry.hidden: if entry.GetResultName(): print( - f"\t\t# Method '{key}' returns object of type '{entry.GetResultName()}'", + "\t\t# Method '{}' returns object of type '{}'".format( + key, entry.GetResultName() + ), file=stream, ) details = entry.desc @@ -759,7 +758,12 @@ def WriteClass(self, generator): file=stream, ) print( - f"{ref.python_name} = sys.modules['{generator.base_mod_name}.{ref.python_name}'].{ref.python_name}", + "{} = sys.modules['{}.{}'].{}".format( + ref.python_name, + 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! @@ -785,14 +789,14 @@ def WriteClass(self, generator): if item.bWritten: key = item.python_name else: - key = repr(str(item.clsid)) # really the iid. - print("\t\t%s," % (key), file=stream) + key = f"'{item.clsid}'" # really the iid. + print(f"\t\t{key},", file=stream) print("\t]", file=stream) if defItem: if defItem.bWritten: defName = defItem.python_name else: - defName = repr(str(defItem.clsid)) # really the iid. + defName = f"'{defItem.clsid}'" # really the iid. print(f"\tdefault_source = {defName}", file=stream) print("\tcoclass_interfaces = [", file=stream) defItem = None @@ -803,14 +807,14 @@ def WriteClass(self, generator): if item.bWritten: key = item.python_name else: - key = repr(str(item.clsid)) # really the iid. + key = f"'{item.clsid}'" # really the iid. print(f"\t\t{key},", file=stream) print("\t]", file=stream) if defItem: if defItem.bWritten: defName = defItem.python_name else: - defName = repr(str(defItem.clsid)) # really the iid. + defName = f"'{defItem.clsid}'" # really the iid. print(f"\tdefault_interface = {defName}", file=stream) self.bWritten = 1 print(file=stream) @@ -962,9 +966,7 @@ def _Build_Interface(self, type_info_tuple): return oleItem, vtableItem def BuildOleItemsFromType(self): - assert ( - self.bBuildHidden - ), "This code doesn't look at the hidden flag - I thought everyone set it true!?!?!" + assert self.bBuildHidden, "This code doesn't look at the hidden flag - I thought everyone set it true!?!?!" oleItems = {} enumItems = {} recordItems = {} @@ -1090,7 +1092,7 @@ def do_gen_file_header(self): print(build._makeDocString(docDesc), file=self.file) - print("makepy_version =", repr(makepy_version), file=self.file) + print(f"makepy_version = {makepy_version!r}", file=self.file) print(f"python_version = 0x{sys.hexversion:x}", file=self.file) print(file=self.file) print( @@ -1112,10 +1114,10 @@ def do_gen_file_header(self): print("defaultNamedNotOptArg=pythoncom.Empty", file=self.file) print("defaultUnnamedArg=pythoncom.Empty", file=self.file) print(file=self.file) - print("CLSID = " + repr(la[0]), file=self.file) - print("MajorVersion = " + str(la[3]), file=self.file) - print("MinorVersion = " + str(la[4]), file=self.file) - print("LibraryFlags = " + str(la[5]), file=self.file) + print(f"CLSID = {la[0]!r}", file=self.file) + print(f"MajorVersion = {la[3]}", file=self.file) + print(f"MinorVersion = {la[4]}", file=self.file) + print(f"LibraryFlags = {la[5]}", file=self.file) print("LCID = " + hex(la[1]), file=self.file) print(file=self.file) @@ -1161,15 +1163,14 @@ def do_generate(self): print("RecordMap = {", file=stream) for record in recordItems.values(): if record.clsid == pythoncom.IID_NULL: + record_str = f"{record.doc[0]!r}: '{record.clsid}'," print( - f"\t###{repr(record.doc[0])}: {repr(str(record.clsid))}, # Record disabled because it doesn't have a non-null GUID", + f"\t###{record_str}", + "# Record disabled because it doesn't have a non-null GUID", file=stream, ) else: - print( - f"\t{repr(record.doc[0])}: {repr(str(record.clsid))},", - file=stream, - ) + print(f"\t{record_str}", file=stream) print("}", file=stream) print(file=stream) @@ -1179,7 +1180,7 @@ def do_generate(self): for item in oleItems.values(): if item is not None and item.bWritten: print( - f"\t'{str(item.clsid)}' : {item.python_name},", + f"\t'{item.clsid}' : {item.python_name},", file=stream, ) print("}", file=stream) @@ -1201,7 +1202,7 @@ def do_generate(self): for item in oleItems.values(): if item is not None: print( - f"\t'{str(item.clsid)}' : {repr(item.python_name)},", + f"\t'{item.clsid}' : {item.python_name!r},", file=stream, ) print("}", file=stream) @@ -1342,7 +1343,9 @@ def do_gen_child_item(self, oleitem): oleitem.WriteClass(self) if oleitem.bWritten: print( - f'win32com.client.CLSIDToClass.RegisterCLSID( "{oleitem.clsid}", {oleitem.python_name} )', + 'win32com.client.CLSIDToClass.RegisterCLSID( "{}", {} )'.format( + oleitem.clsid, oleitem.python_name + ), file=self.file, ) diff --git a/com/win32com/client/makepy.py b/com/win32com/client/makepy.py index 79e66fb674..4d60856ed7 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -15,11 +15,12 @@ """Generate a .py file from an OLE TypeLibrary file. - This module is concerned only with the actual writing of - a .py file. It draws on the @build@ module, which builds - the knowledge of a COM interface. +This module is concerned only with the actual writing of +a .py file. It draws on the @build@ module, which builds +the knowledge of a COM interface. """ + usageHelp = """ \ Usage: @@ -105,12 +106,16 @@ def ShowInfo(spec): desc = tlb.GetDocumentation(-1)[0] print(desc) print( - f" {tlbSpec.clsid}, lcid={tlbSpec.lcid}, major={tlbSpec.major}, minor={tlbSpec.minor}" + " {}, lcid={}, major={}, minor={}".format( + tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor + ) ) print(" >>> # Use these commands in Python code to auto generate .py support") print(" >>> from win32com.client import gencache") print( - f" >>> gencache.EnsureModule('{tlbSpec.clsid}', {tlbSpec.lcid}, {tlbSpec.major}, {tlbSpec.minor})" + " >>> gencache.EnsureModule('{}', {}, {}, {})".format( + tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor + ) ) diff --git a/com/win32com/client/selecttlb.py b/com/win32com/client/selecttlb.py index bf8627f5ff..1d10c9ad82 100644 --- a/com/win32com/client/selecttlb.py +++ b/com/win32com/client/selecttlb.py @@ -1,5 +1,4 @@ -"""Utilities for selecting and enumerating the Type Libraries installed on the system -""" +"""Utilities for selecting and enumerating the Type Libraries installed on the system""" import pythoncom import win32api diff --git a/com/win32com/client/tlbrowse.py b/com/win32com/client/tlbrowse.py index 59ef804197..ceeabe8ec4 100644 --- a/com/win32com/client/tlbrowse.py +++ b/com/win32com/client/tlbrowse.py @@ -155,7 +155,9 @@ def _GetMainInfoTypes(self): typeFlags = attr[11] desc = doc[0] - desc += f", Flags=0x{flags:x}, typeKind=0x{typeKind:x}, typeFlags=0x{typeFlags:x}" + desc += ", Flags=0x{:x}, typeKind=0x{:x}, typeFlags=0x{:x}".format( + flags, typeKind, typeFlags + ) if flags & pythoncom.IMPLTYPEFLAG_FSOURCE: desc += "(Source)" infos.append(("Implements", desc)) diff --git a/com/win32com/demos/outlookAddin.py b/com/win32com/demos/outlookAddin.py index 244d5b325e..a67dedafc1 100644 --- a/com/win32com/demos/outlookAddin.py +++ b/com/win32com/demos/outlookAddin.py @@ -58,9 +58,7 @@ def OnItemAdd(self, item): try: print("An item was added to the inbox with subject:", item.Subject) except AttributeError: - print( - "An item was added to the inbox, but it has no subject! - ", repr(item) - ) + print(f"An item was added to the inbox, but it has no subject! - {item!r}") class OutlookAddin: diff --git a/com/win32com/makegw/makegw.py b/com/win32com/makegw/makegw.py index 8ffdb9306f..e3c85d61a5 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -1,48 +1,48 @@ """Utility functions for writing out gateway C++ files - This module will generate a C++/Python binding for a specific COM - interface. - - Can be run from command line (passing required arguments) or the old way - (start Python, import this module, change to the directory where the generated code - should be written, and run the public function). - - This module is capable of generating both 'Interfaces' (ie, Python - client side support for the interface) and 'Gateways' (ie, Python - server side support for the interface). Many COM interfaces are useful - both as Client and Server. Other interfaces, however, really only make - sense to implement one side or the other. For example, it would be pointless - for Python to implement Server side for 'IRunningObjectTable', unless we were - implementing core COM for an operating system in Python (hey - now there's an idea!) - - Most COM interface code is totally boiler-plate - it consists of - converting arguments, dispatching the call to Python, and processing - any result values. - - This module automates the generation of such code. It has the ability to - parse a .H file generated by the MIDL tool (ie, almost all COM .h files) - and build almost totally complete C++ code. - - The module understands some of the well known data types, and how to - convert them. There are only a couple of places where hand-editing is - necessary, as detailed below: - - unsupported types -- If a type is not known, the generator will - pretty much ignore it, but write a comment to the generated code. You - may want to add custom support for this type. In some cases, C++ compile errors - will result. These are intentional - generating code to remove these errors would - imply a false sense of security that the generator has done the right thing. - - other return policies -- By default, Python never sees the return SCODE from - a COM function. The interface usually returns None if OK, else a COM exception - if "FAILED(scode)" is TRUE. You may need to change this if: - * EXCEPINFO is passed to the COM function. This is not detected and handled - * For some reason Python should always see the result SCODE, even if it - did fail or succeed. For example, some functions return a BOOLEAN result - in the SCODE, meaning Python should always see it. - * FAILED(scode) for the interface still has valid data to return (by default, - the code generated does not process the return values, and raise an exception - to Python/COM +This module will generate a C++/Python binding for a specific COM +interface. + +Can be run from command line (passing required arguments) or the old way +(start Python, import this module, change to the directory where the generated code +should be written, and run the public function). + +This module is capable of generating both 'Interfaces' (ie, Python +client side support for the interface) and 'Gateways' (ie, Python +server side support for the interface). Many COM interfaces are useful +both as Client and Server. Other interfaces, however, really only make +sense to implement one side or the other. For example, it would be pointless +for Python to implement Server side for 'IRunningObjectTable', unless we were +implementing core COM for an operating system in Python (hey - now there's an idea!) + +Most COM interface code is totally boiler-plate - it consists of +converting arguments, dispatching the call to Python, and processing +any result values. + +This module automates the generation of such code. It has the ability to +parse a .h file generated by the MIDL tool (ie, almost all COM .h files) +and build almost totally complete C++ code. + +The module understands some of the well known data types, and how to +convert them. There are only a couple of places where hand-editing is +necessary, as detailed below: + +unsupported types -- If a type is not known, the generator will +pretty much ignore it, but write a comment to the generated code. You +may want to add custom support for this type. In some cases, C++ compile errors +will result. These are intentional - generating code to remove these errors would +imply a false sense of security that the generator has done the right thing. + +other return policies -- By default, Python never sees the return SCODE from +a COM function. The interface usually returns None if OK, else a COM exception +if "FAILED(scode)" is TRUE. You may need to change this if: +* EXCEPINFO is passed to the COM function. This is not detected and handled +* For some reason Python should always see the result SCODE, even if it + did fail or succeed. For example, some functions return a BOOLEAN result + in the SCODE, meaning Python should always see it. +* FAILED(scode) for the interface still has valid data to return (by default, + the code generated does not process the return values, and raise an exception + to Python/COM """ import argparse @@ -61,7 +61,7 @@ def make_framework_support( ): """Generate C++ code for a Python Interface and Gateway - header_file_name -- The full path to the .H file which defines the interface. + header_file_name -- The full path to the .h file which defines the interface. interface_name -- The name of the interface to search for, and to generate. bMakeInterface = 1 -- Should interface (ie, client) support be generated. bMakeGatewayInterface = 1 -- Should gateway (ie, server) support be generated. @@ -202,9 +202,7 @@ def _write_ifc_cpp(f, interface): return ({name} *)Py{base}::GetI(self); }} -""".format( - **interface.__dict__ - ) +""".format(**interface.__dict__) ) ptr = re.sub(r"[a-z]", "", interface.name) @@ -219,9 +217,7 @@ def _write_ifc_cpp(f, interface): {interfacename} *p{ptr} = GetI(self); if ( p{ptr} == NULL ) return NULL; -""".format( - **strdict - ) +""".format(**strdict) ) argsParseTuple = argsCOM = formatChars = codePost = codePobjects = ( codeCobjects @@ -248,14 +244,20 @@ def _write_ifc_cpp(f, interface): argsCOM += ", " + comArgName except makegwparse.error_not_supported as why: f.write( - 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' + '// *** 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.write(f"\t{arg.type} {arg.name};\n\tPyObject *ob{arg.name};\n") f.write( - f"\t// @pyparm |{arg.name}||Description for {arg.name}\n" + "\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 ) - codePost += f"\tif (bPythonIsHappy && !PyObject_As{arg.type}( ob{arg.name}, &{arg.name} )) bPythonIsHappy = FALSE;\n" formatChars += "O" argsParseTuple += ", &ob%s" % arg.name @@ -268,7 +270,9 @@ def _write_ifc_cpp(f, interface): f.write(codePobjects) f.write(codeCobjects) f.write( - f'\tif ( !PyArg_ParseTuple(args, "{formatChars}:{method.name}"{argsParseTuple}) )\n\t\treturn NULL;\n' + '\tif ( !PyArg_ParseTuple(args, "{}:{}"{}) )\n\t\treturn NULL;\n'.format( + formatChars, method.name, argsParseTuple + ) ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") @@ -286,9 +290,7 @@ def _write_ifc_cpp(f, interface): {cleanup_gil} if ( FAILED(hr) ) return PyCom_BuildPyException(hr, p{ptr}, IID_{interfacename} ); -""".format( - **strdict - ) +""".format(**strdict) ) codePre = codePost = formatChars = codeVarsPass = codeDecl = "" for arg in method.args: @@ -305,12 +307,16 @@ def _write_ifc_cpp(f, interface): codeDecl += argCvt.DeclareParseArgTupleInputConverter() except makegwparse.error_not_supported as why: f.write( - f'// *** The output argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// {why}\n' + '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( + arg.name, arg.raw_type, why + ) ) continue if formatChars: f.write( - f'{codeDecl}\n{codePre}\tPyObject *pyretval = Py_BuildValue("{formatChars}"{codeVarsPass});\n{codePost}\treturn pyretval;' + '{}\n{}\tPyObject *pyretval = Py_BuildValue("{}"{});\n{}\treturn pyretval;'.format( + codeDecl, codePre, formatChars, codeVarsPass, codePost + ) ) else: f.write("\tPy_RETURN_NONE;\n") @@ -320,7 +326,9 @@ def _write_ifc_cpp(f, interface): f.write("static struct PyMethodDef Py%s_methods[] =\n{\n" % name) for method in interface.methods: f.write( - f'\t{{ "{method.name}", Py{interface.name}::{method.name}, 1 }}, // @pymeth {method.name}|Description of {method.name}\n' + '\t{{ "{}", Py{}::{}, 1 }}, // @pymeth {}|Description of {}\n'.format( + method.name, interface.name, method.name, method.name, method.name + ) ) interfacebase = interface.base @@ -334,9 +342,7 @@ def _write_ifc_cpp(f, interface): sizeof(Py{name}), Py{name}_methods, GET_PYCOM_CTOR(Py{name})); -""".format( - **locals() - ) +""".format(**locals()) ) @@ -369,7 +375,9 @@ class {gname} : public {base_name}, public {name} ) if interface.base != "IUnknown": f.write( - f"\t// {interface.base}\n\t// *** Manually add {interface.base} method decls here\n\n" + "\t// {}\n\t// *** Manually add {} method decls here\n\n".format( + interface.base, interface.base + ) ) else: f.write("\n\n") @@ -456,13 +464,19 @@ def _write_gw_cpp(f, interface): codePost += argCvt.GetBuildForGatewayPostCode() except makegwparse.error_not_supported as why: f.write( - 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' + '// *** 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.write( - f"\tPyObject *ob{arg.name} = PyObject_From{arg.type}({arg.name});\n" + "\tPyObject *ob{} = PyObject_From{}({});\n".format( + arg.name, arg.type, arg.name + ) ) f.write( - f'\tif (ob{arg.name}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{method.name}");\n' + '\tif (ob{}==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( + arg.name, method.name + ) ) codePost += "\tPy_DECREF(ob%s);\n" % arg.name formatChars += "O" @@ -508,7 +522,9 @@ def _write_gw_cpp(f, interface): needConversion = needConversion or argCvt.NeedUSES_CONVERSION() except makegwparse.error_not_supported as why: f.write( - f'// *** The output argument {arg.name} of type "{arg.raw_type}" was not processed ***\n// {why}\n' + '// *** The output argument {} of type "{}" was not processed ***\n// {}\n'.format( + arg.name, arg.raw_type, why + ) ) if formatChars: # If I have any to actually process. @@ -519,7 +535,9 @@ def _write_gw_cpp(f, interface): if codePobjects: f.write(codePobjects) f.write( - f'\tif (!{parseFn}(result, "{formatChars}" {argsParseTuple}))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("{method.name}");\n' + '\tif (!{}(result, "{}" {}))\n\t\treturn MAKE_PYCOM_GATEWAY_FAILURE_CODE("{}");\n'.format( + parseFn, formatChars, argsParseTuple, method.name + ) ) if codePost: f.write("\tBOOL bPythonIsHappy = TRUE;\n") diff --git a/com/win32com/makegw/makegwenum.py b/com/win32com/makegw/makegwenum.py index 3ba274a4e6..d3698af75c 100644 --- a/com/win32com/makegw/makegwenum.py +++ b/com/win32com/makegw/makegwenum.py @@ -191,9 +191,7 @@ def _write_enumifc_cpp(f, interface): sizeof(PyIEnum{enumtype}), PyIEnum{enumtype}_methods, GET_PYCOM_CTOR(PyIEnum{enumtype})); -""".format( - **locals() - ) +""".format(**locals()) ) @@ -329,7 +327,5 @@ def _write_enumgw_cpp(f, interface): return PyCom_CheckIEnumNextResult(hr, IID_IEnum{enumtype}); }} -""".format( - **locals() - ) +""".format(**locals()) ) diff --git a/com/win32com/makegw/makegwparse.py b/com/win32com/makegw/makegwparse.py index e33a3d67e9..14e800db60 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -1,15 +1,15 @@ """Utilities for makegw - Parse a header file to build an interface - This module contains the core code for parsing a header file describing a - COM interface, and building it into an "Interface" structure. +This module contains the core code for parsing a header file describing a +COM interface, and building it into an "Interface" structure. - Each Interface has methods, and each method has arguments. +Each Interface has methods, and each method has arguments. - Each argument knows how to use Py_BuildValue or Py_ParseTuple to - exchange itself with Python. +Each argument knows how to use Py_BuildValue or Py_ParseTuple to +exchange itself with Python. - See the @win32com.makegw@ module for information in building a COM - interface +See the @win32com.makegw@ module for information in building a COM +interface """ from __future__ import annotations @@ -209,7 +209,11 @@ def GetBuildForGatewayPostCode(self): return s def GetAutoduckString(self): - return f"// @pyparm {self._GetPythonTypeDesc()}|{self.arg.name}||Description for {self.arg.name}" + return "// @pyparm {}|{}||Description for {}".format( + self._GetPythonTypeDesc(), + self.arg.name, + self.arg.name, + ) def _GetPythonTypeDesc(self): "Returns a string with the description of the type. Used for doco purposes" @@ -319,7 +323,9 @@ def GetBuildForInterfacePostCode(self): return "\tPy_XDECREF(ob%s);\n" % self.arg.name def GetParsePostCode(self): - return f"\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob{self.arg.name}, (ULONG_PTR *){self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyWinLong_AsULONG_PTR(ob{}, (ULONG_PTR *){})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) + ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) @@ -360,7 +366,9 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return f"\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) + ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) @@ -387,7 +395,9 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return f"\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyWinObject_AsBstr(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) + ) def GetInterfaceArgCleanup(self): return "\tSysFreeString(%s);\n" % self.GetIndirectedArgName(None, 1) @@ -419,7 +429,9 @@ def GetUnconstType(self): return self.arg.unc_type def GetParsePostCode(self): - return f"\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob{self.arg.name}, {self.GetIndirectedArgName(None, 2)})) bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyWinObject_AsTCHAR(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 2) + ) def GetInterfaceArgCleanup(self): return "\tPyWinObject_FreeTCHAR(%s);\n" % self.GetIndirectedArgName(None, 1) @@ -441,7 +453,10 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return f"\tif (!PyWinObject_AsIID(ob{self.arg.name}, &{self.arg.name})) bPythonIsHappy = FALSE;\n" + return "\tif (!PyWinObject_AsIID(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, + self.arg.name, + ) def GetBuildForInterfacePreCode(self): # notdirected = self.GetIndirectedArgName(self.arg.indirectionLevel, 0) @@ -470,7 +485,11 @@ def _GetPythonTypeDesc(self): def GetParsePostCode(self): # variable was declared with only the builtinIndirection ### NOTE: this is an [in] ... so use only builtin - 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' + 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), + ) def GetBuildForInterfacePreCode(self): ### use just the builtinIndirection again... @@ -491,11 +510,18 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return f"\tif (!PyCom_PyObjectAsSTATSTG(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)}, 0/*flags*/)) bPythonIsHappy = FALSE;\n" + return "\tif (!PyCom_PyObjectAsSTATSTG(ob{}, {}, 0/*flags*/)) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) + ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - 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" + 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, + ) class ArgFormatterGeneric(ArgFormatterPythonCOM): @@ -503,14 +529,22 @@ def _GetPythonTypeDesc(self): return "" % self.arg.type def GetParsePostCode(self): - return f"\tif (!PyObject_As{self.arg.type}(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)}) bPythonIsHappy = FALSE;\n" + return "\tif (!PyObject_As{}(ob{}, &{}) bPythonIsHappy = FALSE;\n".format( + self.arg.type, + self.arg.name, + self.GetIndirectedArgName(None, 1), + ) def GetInterfaceArgCleanup(self): return f"\tPyObject_Free{self.arg.type}({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return f"\tob{self.arg.name} = PyObject_From{self.arg.type}({self.GetIndirectedArgName(None, 1)});\n" + return "\tob{} = PyObject_From{}({});\n".format( + self.arg.name, + self.arg.type, + self.GetIndirectedArgName(None, 1), + ) class ArgFormatterIDLIST(ArgFormatterPythonCOM): @@ -518,14 +552,19 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return f"\tif (bPythonIsHappy && !PyObject_AsPIDL(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)})) bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyObject_AsPIDL(ob{}, &{})) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) + ) def GetInterfaceArgCleanup(self): return f"\tPyObject_FreePIDL({self.arg.name});\n" def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return f"\tob{self.arg.name} = PyObject_FromPIDL({self.GetIndirectedArgName(None, 1)});\n" + return "\tob{} = PyObject_FromPIDL({});\n".format( + self.arg.name, + self.GetIndirectedArgName(None, 1), + ) class ArgFormatterHANDLE(ArgFormatterPythonCOM): @@ -533,11 +572,16 @@ def _GetPythonTypeDesc(self): return "" def GetParsePostCode(self): - return f"\tif (!PyWinObject_AsHANDLE(ob{self.arg.name}, &{self.GetIndirectedArgName(None, 1)}, FALSE) bPythonIsHappy = FALSE;\n" + return "\tif (!PyWinObject_AsHANDLE(ob{}, &{}, FALSE) bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) + ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 1) - return f"\tob{self.arg.name} = PyWinObject_FromHANDLE({self.GetIndirectedArgName(None, 0)});\n" + return "\tob{} = PyWinObject_FromHANDLE({});\n".format( + self.arg.name, + self.GetIndirectedArgName(None, 0), + ) class ArgFormatterLARGE_INTEGER(ArgFormatterPythonCOM): @@ -548,11 +592,19 @@ def _GetPythonTypeDesc(self): return "" % self.GetKeyName() def GetParsePostCode(self): - return f"\tif (!PyWinObject_As{self.GetKeyName()}(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)})) bPythonIsHappy = FALSE;\n" + return "\tif (!PyWinObject_As{}(ob{}, {})) bPythonIsHappy = FALSE;\n".format( + self.GetKeyName(), + self.arg.name, + self.GetIndirectedArgName(None, 1), + ) def GetBuildForInterfacePreCode(self): notdirected = self.GetIndirectedArgName(None, 0) - return f"\tob{self.arg.name} = PyWinObject_From{self.GetKeyName()}({notdirected});\n" + return "\tob{} = PyWinObject_From{}({});\n".format( + self.arg.name, + self.GetKeyName(), + notdirected, + ) class ArgFormatterULARGE_INTEGER(ArgFormatterLARGE_INTEGER): @@ -562,9 +614,11 @@ def GetKeyName(self): class ArgFormatterInterface(ArgFormatterPythonCOM): def GetInterfaceCppObjectInfo(self): - return ( - self.GetIndirectedArgName(1, self.arg.indirectionLevel), - f"{self.GetUnconstType()} * {self.arg.name}", + return self.GetIndirectedArgName( + 1, self.arg.indirectionLevel + ), "{} * {}".format( + self.GetUnconstType(), + self.arg.name, ) def GetParsePostCode(self): @@ -574,14 +628,25 @@ def GetParsePostCode(self): else: # vs. in params for interface mode. sArg = self.GetIndirectedArgName(1, 2) - return f"\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob{self.arg.name}, IID_{self.arg.type}, (void **){sArg}, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n" + return "\tif (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(ob{}, IID_{}, (void **){}, TRUE /* bNoneOK */))\n\t\t bPythonIsHappy = FALSE;\n".format( + self.arg.name, self.arg.type, sArg + ) def GetBuildForInterfacePreCode(self): - return f"\tob{self.arg.name} = PyCom_PyObjectFromIUnknown({self.arg.name}, IID_{self.arg.type}, FALSE);\n" + return "\tob{} = PyCom_PyObjectFromIUnknown({}, IID_{}, FALSE);\n".format( + self.arg.name, + self.arg.name, + self.arg.type, + ) def GetBuildForGatewayPreCode(self): sPrefix = self._IndirectPrefix(self._GetDeclaredIndirection(), 1) - return f"\tob{self.arg.name} = PyCom_PyObjectFromIUnknown({sPrefix}{self.arg.name}, IID_{self.arg.type}, TRUE);\n" + return "\tob{} = PyCom_PyObjectFromIUnknown({}{}, IID_{}, TRUE);\n".format( + self.arg.name, + sPrefix, + self.arg.name, + self.arg.type, + ) def GetInterfaceArgCleanup(self): return f"\tif ({self.arg.name}) {self.arg.name}->Release();\n" @@ -589,7 +654,9 @@ def GetInterfaceArgCleanup(self): class ArgFormatterVARIANT(ArgFormatterPythonCOM): def GetParsePostCode(self): - return f"\tif ( !PyCom_VariantFromPyObject(ob{self.arg.name}, {self.GetIndirectedArgName(None, 1)}) )\n\t\tbPythonIsHappy = FALSE;\n" + return "\tif ( !PyCom_VariantFromPyObject(ob{}, {}) )\n\t\tbPythonIsHappy = FALSE;\n".format( + self.arg.name, self.GetIndirectedArgName(None, 1) + ) def GetBuildForGatewayPreCode(self): notdirected = self.GetIndirectedArgName(None, 1) diff --git a/com/win32com/olectl.py b/com/win32com/olectl.py index f6be98bda2..e2e16b42de 100644 --- a/com/win32com/olectl.py +++ b/com/win32com/olectl.py @@ -1,6 +1,6 @@ """Constants used by COM Controls - Hand created version of OLECTL.H constants. +Hand created version of olectl.h constants. """ import winerror diff --git a/com/win32com/server/connect.py b/com/win32com/server/connect.py index e99555a046..5d3cddf981 100644 --- a/com/win32com/server/connect.py +++ b/com/win32com/server/connect.py @@ -1,6 +1,6 @@ """Utilities for Server Side connections. - A collection of helpers for server side connection points. +A collection of helpers for server side connection points. """ import pythoncom @@ -82,4 +82,4 @@ def _BroadcastNotify(self, broadcaster, extraArgs): self._OnNotifyFail(interface, details) def _OnNotifyFail(self, interface, details): - print("Ignoring COM error to connection - %s" % (repr(details))) + print(f"Ignoring COM error to connection - {details!r}") diff --git a/com/win32com/server/dispatcher.py b/com/win32com/server/dispatcher.py index 820fd47143..7aba2cb22c 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -6,6 +6,7 @@ from __future__ import annotations import traceback +from typing import NoReturn import pythoncom import win32api @@ -31,51 +32,48 @@ def __init__(self, policyClass, object): # default location (typically 'print') self.logger = getattr(win32com, "logger", None) - # Note the "return self._HandleException_()" is purely to stop pychecker - # complaining - _HandleException_ will itself raise an exception for the - # pythoncom framework, so the result will never be seen. def _CreateInstance_(self, clsid, reqIID): try: self.policy._CreateInstance_(clsid, reqIID) return pythoncom.WrapObject(self, reqIID) except: - return self._HandleException_() + self._HandleException_() def _QueryInterface_(self, iid): try: return self.policy._QueryInterface_(iid) except: - return self._HandleException_() + self._HandleException_() def _Invoke_(self, dispid, lcid, wFlags, args): try: return self.policy._Invoke_(dispid, lcid, wFlags, args) except: - return self._HandleException_() + self._HandleException_() def _GetIDsOfNames_(self, names, lcid): try: return self.policy._GetIDsOfNames_(names, lcid) except: - return self._HandleException_() + self._HandleException_() def _GetTypeInfo_(self, index, lcid): try: return self.policy._GetTypeInfo_(index, lcid) except: - return self._HandleException_() + self._HandleException_() def _GetTypeInfoCount_(self): try: return self.policy._GetTypeInfoCount_() except: - return self._HandleException_() + self._HandleException_() def _GetDispID_(self, name, fdex): try: return self.policy._GetDispID_(name, fdex) except: - return self._HandleException_() + self._HandleException_() def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): try: @@ -83,45 +81,45 @@ def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): dispid, lcid, wFlags, args, kwargs, serviceProvider ) except: - return self._HandleException_() + self._HandleException_() def _DeleteMemberByName_(self, name, fdex): try: return self.policy._DeleteMemberByName_(name, fdex) except: - return self._HandleException_() + self._HandleException_() def _DeleteMemberByDispID_(self, id): try: return self.policy._DeleteMemberByDispID_(id) except: - return self._HandleException_() + self._HandleException_() def _GetMemberProperties_(self, id, fdex): try: return self.policy._GetMemberProperties_(id, fdex) except: - return self._HandleException_() + self._HandleException_() def _GetMemberName_(self, dispid): try: return self.policy._GetMemberName_(dispid) except: - return self._HandleException_() + self._HandleException_() def _GetNextDispID_(self, fdex, flags): try: return self.policy._GetNextDispID_(fdex, flags) except: - return self._HandleException_() + self._HandleException_() def _GetNameSpaceParent_(self): try: return self.policy._GetNameSpaceParent_() except: - return self._HandleException_() + self._HandleException_() - def _HandleException_(self): + def _HandleException_(self) -> NoReturn: """Called whenever an exception is raised. Default behaviour is to print the exception. @@ -152,7 +150,9 @@ def _QueryInterface_(self, iid): rc = DispatcherBase._QueryInterface_(self, iid) if not rc: self._trace_( - f"in {repr(self.policy._obj_)}._QueryInterface_ with unsupported IID {IIDToInterfaceName(iid)} ({iid})" + "in {!r}._QueryInterface_ with unsupported IID {} ({})".format( + self.policy._obj_, IIDToInterfaceName(iid), iid + ) ) return rc @@ -178,7 +178,9 @@ def _GetDispID_(self, name, fdex): def _InvokeEx_(self, dispid, lcid, wFlags, args, kwargs, serviceProvider): self._trace_( - f"in {self.policy._obj_!r}._InvokeEx_-{dispid}{args!r} [{wFlags:x},{lcid},{serviceProvider!r}]" + "in {!r}._InvokeEx_-{}{!r} [{:x},{},{!r}]".format( + self.policy._obj_, dispid, args, wFlags, lcid, serviceProvider + ) ) return DispatcherBase._InvokeEx_( self, dispid, lcid, wFlags, args, kwargs, serviceProvider @@ -217,9 +219,7 @@ def __init__(self, policyClass, object): if self.logger is None: # If we have no logger, setup our output. import win32traceutil # Sets up everything. - self._trace_( - "Object with win32trace dispatcher created (object=%s)" % repr(object) - ) + self._trace_(f"Object with win32trace dispatcher created (object={object!r})") class DispatcherOutputDebugString(DispatcherTrace): diff --git a/com/win32com/server/exception.py b/com/win32com/server/exception.py index a6b3111fec..c31073e1cd 100644 --- a/com/win32com/server/exception.py +++ b/com/win32com/server/exception.py @@ -1,15 +1,15 @@ """Exception Handling - Exceptions +Exceptions - To better support COM exceptions, the framework allows for an instance to be - raised. This instance may have a certain number of known attributes, which are - translated into COM exception details. + To better support COM exceptions, the framework allows for an instance to be + raised. This instance may have a certain number of known attributes, which are + translated into COM exception details. - This means, for example, that Python could raise a COM exception that includes details - on a Help file and location, and a description for the user. + This means, for example, that Python could raise a COM exception that includes details + on a Help file and location, and a description for the user. - This module provides a class which provides the necessary attributes. + This module provides a class which provides the necessary attributes. """ import sys diff --git a/com/win32com/server/policy.py b/com/win32com/server/policy.py index 0c1f924271..f4593b4b97 100644 --- a/com/win32com/server/policy.py +++ b/com/win32com/server/policy.py @@ -321,7 +321,7 @@ def _getidsofnames_(self, names, lcid): # IDispatchEx support for policies. Most of the IDispathEx functionality # by default will raise E_NOTIMPL. Thus it is not necessary for derived - # policies to explicitely implement all this functionality just to not implement it! + # policies to explicitly implement all this functionality just to not implement it! def _GetDispID_(self, name, fdex): return self._getdispid_(name, fdex) diff --git a/com/win32com/server/register.py b/com/win32com/server/register.py index 3c3a5dcfa9..8a05ea117f 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -272,7 +272,7 @@ def RegisterServer( exeName = _find_localserver_exe(1) exeName = win32api.GetShortPathName(exeName) pyfile = _find_localserver_module() - command = f'{exeName} "{pyfile}" {str(clsid)}' + command = f'{exeName} "{pyfile}" {clsid}' _set_string(keyNameRoot + "\\LocalServer32", command) else: # Remove any old LocalServer32 registrations _remove_key(keyNameRoot + "\\LocalServer32") @@ -383,7 +383,7 @@ def UnregisterServer(clsid, progID=None, verProgID=None, customKeys=None): def GetRegisteredServerOption(clsid, optionName): """Given a CLSID for a server and option name, return the option value""" - keyNameRoot = f"CLSID\\{str(clsid)}\\{str(optionName)}" + keyNameRoot = f"CLSID\\{clsid}\\{optionName}" return _get_string(keyNameRoot) @@ -448,7 +448,7 @@ def RegisterClasses(*classes, **flags): win32api.FindFiles(sys.argv[0])[0][8] )[0] except (IndexError, win32api.error): - # Can't find the script file - the user must explicitely set the _reg_... attribute. + # Can't find the script file - the user must explicitly set the _reg_... attribute. raise TypeError( "Can't locate the script hosting the COM object - please set _reg_class_spec_ in your object" ) @@ -523,11 +523,10 @@ def UnregisterClasses(*classes, **flags): extra() -# # Unregister info is for installers or external uninstallers. # The WISE installer, for example firstly registers the COM server, # then queries for the Unregister info, appending it to its -# install log. Uninstalling the package will the uninstall the server +# install log. Uninstalling the package will uninstall the server. def UnregisterInfoClasses(*classes, **flags): ret = [] for cls in classes: @@ -594,7 +593,9 @@ def ReExecuteElevated(flags): print(os.path.splitdrive(cwd)[0], file=batf) print('cd "%s"' % os.getcwd(), file=batf) print( - f'{win32api.GetShortPathName(exe_to_run)} {new_params} > "{outfile}" 2>&1', + '{} {} > "{}" 2>&1'.format( + win32api.GetShortPathName(exe_to_run), new_params, outfile + ), file=batf, ) finally: diff --git a/com/win32com/servers/interp.py b/com/win32com/servers/interp.py index 37d83bd497..0676e21276 100644 --- a/com/win32com/servers/interp.py +++ b/com/win32com/servers/interp.py @@ -1,14 +1,14 @@ """Python.Interpreter COM Server - This module implements a very very simple COM server which - exposes the Python interpreter. +This module implements a very very simple COM server which +exposes the Python interpreter. - This is designed more as a demonstration than a full blown COM server. - General functionality and Error handling are both limited. +This is designed more as a demonstration than a full blown COM server. +General functionality and Error handling are both limited. - To use this object, ensure it is registered by running this module - from Python.exe. Then, from Visual Basic, use "CreateObject('Python.Interpreter')", - and call its methods! +To use this object, ensure it is registered by running this module +from Python.exe. Then, from Visual Basic, use "CreateObject('Python.Interpreter')", +and call its methods! """ import winerror diff --git a/com/win32com/test/GenTestScripts.py b/com/win32com/test/GenTestScripts.py index 079f6a9842..8b09df0771 100644 --- a/com/win32com/test/GenTestScripts.py +++ b/com/win32com/test/GenTestScripts.py @@ -3,6 +3,7 @@ # import os import sys +import traceback import pythoncom import win32com @@ -60,10 +61,7 @@ def GenerateAll(): def CleanAll(): print("Cleaning generated test scripts...") - try: # Clear exceptions! - 1 / 0 - except: - pass + traceback.clear_frames(sys.exc_info()[2]) # Clear exceptions! genPath = GetGenPath() for args in genList: try: diff --git a/com/win32com/test/errorSemantics.py b/com/win32com/test/errorSemantics.py index 843395c41d..fe5045cc88 100644 --- a/com/win32com/test/errorSemantics.py +++ b/com/win32com/test/errorSemantics.py @@ -158,7 +158,7 @@ def test(): "The source in the exception tuple did not yield the correct string", str(com_exc), ) - assert exc[2] == "\U0001F600", ( + assert exc[2] == "\U0001f600", ( "The description in the exception tuple did not yield the correct string", str(com_exc), ) @@ -213,7 +213,7 @@ def testLogger(): except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] - assert message.endswith("Exception: \U0001F600\n") + assert message.endswith("Exception: \U0001f600\n") assert handler.num_emits == 1, handler.num_emits assert handler.last_record.startswith( "pythoncom error: Unexpected exception in gateway method 'Commit'" @@ -228,7 +228,7 @@ def testLogger(): except pythoncom.error as exc: # `excepinfo` is a tuple with elt 2 being the traceback we captured. message = exc.excepinfo[2] - assert message.endswith("Exception: \U0001F600\n") + assert message.endswith("Exception: \U0001f600\n") assert handler.num_emits == 1, handler.num_emits handler.reset() diff --git a/com/win32com/test/testDCOM.py b/com/win32com/test/testDCOM.py index 1160f9b5eb..fea4d20404 100644 --- a/com/win32com/test/testDCOM.py +++ b/com/win32com/test/testDCOM.py @@ -35,7 +35,9 @@ def test(serverName): actualName = ob.Eval("win32api.GetComputerName()") if serverName.lower() != actualName.lower(): print( - f"Error: The object created on server '{serverName}' reported its name as '{actualName}'" + "Error: The object created on server '{}' reported its name as '{}'".format( + serverName, 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 4e336253e9..58a93e2a1d 100644 --- a/com/win32com/test/testDynamic.py +++ b/com/win32com/test/testDynamic.py @@ -37,8 +37,8 @@ def write(self, *args): ) # Probably call as PROPGET. for arg in args[:-1]: - print(str(arg), end=" ") - print(str(args[-1])) + print(arg, end=" ") + print(args[-1]) def Test(): @@ -65,7 +65,7 @@ def Test(): client.TestSequence = v assert v == list( client.TestSequence - ), f"Dynamic sequences not working! {repr(v)!r}/{repr(client.testSequence)!r}" + ), f"Dynamic sequences not working! {v!r}/{client.testSequence!r}" client.write("This", "output", "has", "come", "via", "testDynamic.py") # Check our new "_FlagAsMethod" works (kinda!) diff --git a/com/win32com/test/testExchange.py b/com/win32com/test/testExchange.py index 119c16a17b..f54422bb6a 100644 --- a/com/win32com/test/testExchange.py +++ b/com/win32com/test/testExchange.py @@ -91,7 +91,6 @@ def TestUser(session): def test(): - oldcwd = os.getcwd() try: session = gencache.EnsureDispatch("MAPI.Session") diff --git a/com/win32com/test/testGatewayAddresses.py b/com/win32com/test/testGatewayAddresses.py index aeafbec759..3904d5e908 100644 --- a/com/win32com/test/testGatewayAddresses.py +++ b/com/win32com/test/testGatewayAddresses.py @@ -60,7 +60,7 @@ def FailObjectIdentity(ob1, ob2, when): if not CheckObjectIdentity(ob1, ob2): global numErrors numErrors += 1 - print(when, f"are not identical ({repr(ob1)}, {repr(ob2)})") + print(f"{when} are not identical ({ob1!r}, {ob2!r})") class Dummy: diff --git a/com/win32com/test/testMSOffice.py b/com/win32com/test/testMSOffice.py index 514b9b55f5..d3f93da7fc 100644 --- a/com/win32com/test/testMSOffice.py +++ b/com/win32com/test/testMSOffice.py @@ -107,10 +107,7 @@ def TextExcel(xl): xl.Visible = 1 assert xl.Visible, "Visible property not true." - if int(xl.Version.split(".")[0]) >= 8: - xl.Workbooks.Add() - else: - xl.Workbooks().Add() + xl.Workbooks.Add() xl.Range("A1:C1").Value = (1, 2, 3) xl.Range("A2:C2").Value = ("x", "y", "z") @@ -181,19 +178,6 @@ def TestAll(): print("Generated Excel tests failed", e) traceback.print_exc() - try: - import xl5en32 # nopycln: import # Test import. TODO: Is testing Excel 95 still relevant ? - - mod = gencache.EnsureModule("{00020813-0000-0000-C000-000000000046}", 9, 1, 0) - xl = win32com.client.Dispatch("Excel.Application.5") - print("Starting Excel 95 for makepy test...") - TextExcel(xl) - except ImportError: - print("Could not import the generated Excel 95 wrapper") - except Exception as e: - print("Excel 95 tests failed", e) - traceback.print_exc() - if __name__ == "__main__": TestAll() diff --git a/com/win32com/test/testMSOfficeEvents.py b/com/win32com/test/testMSOfficeEvents.py index 7874edafca..e742c82f9b 100644 --- a/com/win32com/test/testMSOfficeEvents.py +++ b/com/win32com/test/testMSOfficeEvents.py @@ -57,8 +57,8 @@ def OnBeforeRightClick(self, Target, Cancel): book = e.Workbooks.Add() book = DispatchWithEvents(book, WorkbookEvents) print("Have book", book) - # sheet = e.Worksheets(1) - # sheet = DispatchWithEvents(sheet, WorksheetEvents) + # sheet = e.Worksheets(1) + # sheet = DispatchWithEvents(sheet, WorksheetEvents) print("Double-click in a few of the Excel cells...") print("Press any key when finished with Excel, or wait 10 seconds...") diff --git a/com/win32com/test/testPersist.py b/com/win32com/test/testPersist.py index aecdd27fbf..e47c973057 100644 --- a/com/win32com/test/testPersist.py +++ b/com/win32com/test/testPersist.py @@ -42,8 +42,8 @@ def ReadAt(self, offset, cb): return result def WriteAt(self, offset, data): - print("WriteAt " + str(offset)) - print("len " + str(len(data))) + print("WriteAt", offset) + print("len", len(data)) print("data:") # print(data) if len(self.data) >= offset: @@ -56,13 +56,13 @@ def WriteAt(self, offset, data): return len(data) def Flush(self, whatsthis=0): - print("Flush" + str(whatsthis)) + print("Flush", whatsthis) fname = os.path.join(win32api.GetTempPath(), "persist.doc") open(fname, "wb").write(self.data) return S_OK def SetSize(self, size): - print("Set Size" + str(size)) + print("Set Size", size) if size > len(self.data): self.data += b"\000" * (size - len(self.data)) else: @@ -76,7 +76,7 @@ def UnlockRegion(self, offset, size, locktype): print("UnlockRegion") def Stat(self, statflag): - print("returning Stat " + str(statflag)) + print("returning Stat", statflag) return ( "PyMemBytes", storagecon.STGTY_LOCKBYTES, @@ -121,7 +121,7 @@ def SaveObject(self): return S_OK def GetMoniker(self, dwAssign, dwWhichMoniker): - print("GetMoniker " + str(dwAssign) + " " + str(dwWhichMoniker)) + print("GetMoniker", dwAssign, dwWhichMoniker) def GetContainer(self): print("GetContainer") @@ -130,7 +130,7 @@ def ShowObject(self): print("ShowObject") def OnShowWindow(self, fShow): - print("ShowObject" + str(fShow)) + print("ShowObject", fShow) def RequestNewObjectLayout(self): print("RequestNewObjectLayout") diff --git a/com/win32com/test/testPippo.py b/com/win32com/test/testPippo.py index 414483b53e..765acf97f4 100644 --- a/com/win32com/test/testPippo.py +++ b/com/win32com/test/testPippo.py @@ -51,9 +51,8 @@ def testNumpyArrays(self): self._testArray(numpy.array([-3.14, -2, -0.1, 0.0, 1.1, 2.5, 3])) def testByteArrays(self): - if "bytes" in dir(__builtins__): - self._testArray(b"abcdef") - self._testArray(bytearray(b"abcdef")) + self._testArray(b"abcdef") + self._testArray(bytearray(b"abcdef")) def _testArray(self, inArray): outArray = self.object.Method3(inArray) diff --git a/com/win32com/test/testPyComTest.py b/com/win32com/test/testPyComTest.py index 50330e3564..269d9ebb9f 100644 --- a/com/win32com/test/testPyComTest.py +++ b/com/win32com/test/testPyComTest.py @@ -609,7 +609,7 @@ def check_dispatch(got): def TestCounter(counter, bIsGenerated): # Test random access into container - progress("Testing counter", repr(counter)) + progress(f"Testing counter {counter!r}") import random for i in range(50): diff --git a/com/win32com/test/testvb.py b/com/win32com/test/testvb.py index 480c1c742b..91f06d3da2 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -95,10 +95,13 @@ def TestVB(vbtest, bUseGenerated): vbtest.VariantProperty == "Hello from Python" ), "Could not set the variant string property correctly." vbtest.VariantProperty = (1.0, 2.0, 3.0) - assert vbtest.VariantProperty == ( - 1.0, - 2.0, - 3.0, + assert ( + vbtest.VariantProperty + == ( + 1.0, + 2.0, + 3.0, + ) ), f"Could not set the variant property to an array of floats correctly - '{vbtest.VariantProperty}'." TestArrays(vbtest, bUseGenerated) @@ -195,8 +198,8 @@ def _getcount(ob): check = [] for item in i: check.append(item) - assert check == list( - expected + assert ( + check == list(expected) ), f"Collection iterator {col_name} didn't have {expected!r} 2nd time around (had {check!r})" # but an iterator is not restartable check = [] @@ -336,12 +339,14 @@ def TestArrays(vbtest, bUseGenerated): assert testData == list(resultData) testData = ["hi", "from", "Python"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) - assert testData == list( - byRefParam - ), f"Expected '{testData}', got '{list(byRefParam)}'" - assert testData == list( - resultData - ), f"Expected '{testData}', got '{list(resultData)}'" + assert testData == list(byRefParam), "Expected '{}', got '{}'".format( + testData, + list(byRefParam), + ) + assert testData == list(resultData), "Expected '{}', got '{}'".format( + testData, + list(resultData), + ) # This time, we just pass Unicode, so the result should compare equal testData = [1, 2.0, "3"] resultData, byRefParam = vbtest.PassSAFEARRAYVariant(testData) @@ -474,10 +479,18 @@ def TestStructs(vbtest): assert "foo" in str(exc), exc # test repr - it uses repr() of the sub-objects, so check it matches. - 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: + 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, + ) + ) + repr_s = repr(s) + if repr_s != expected: print("Expected repr:", expected) - print("Actual repr :", repr(s)) + print("Actual repr :", repr_s) raise AssertionError("repr() of record object failed") print("Struct/Record tests passed") diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index d303724173..877d99bf12 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -52,7 +52,12 @@ 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 = f"{progid!r} is registered against a different Python version ({dll})" + why_not = ( + "{!r} is registered against a different Python version ({})".format( + progid, + dll, + ) + ) break else: # print(f"Skipping registration of '{filename}' - already registered") diff --git a/com/win32com/universal.py b/com/win32com/universal.py index ec42039c2c..c79d7d80a1 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -212,7 +212,9 @@ def dispatch( retVal = retVal[1:] else: raise TypeError( - f"Expected {len(meth._gw_out_args) + 1} return values, got: {len(retVal)}" + "Expected {} return values, got: {}".format( + len(meth._gw_out_args) + 1, len(retVal) + ) ) else: retVal = [retVal] diff --git a/com/win32com/util.py b/com/win32com/util.py index 0a5748f1e1..2fa8931af0 100644 --- a/com/win32com/util.py +++ b/com/win32com/util.py @@ -1,6 +1,6 @@ """General utility functions common to client and server. - This module contains a collection of general purpose utility functions. +This module contains a collection of general purpose utility functions. """ import pythoncom diff --git a/com/win32comext/adsi/demos/scp.py b/com/win32comext/adsi/demos/scp.py index b2ff016ec9..dc5f831e8f 100644 --- a/com/win32comext/adsi/demos/scp.py +++ b/com/win32comext/adsi/demos/scp.py @@ -419,7 +419,7 @@ def main(): "--test", action="store_true", help="Execute a mini-test suite, providing defaults for most options and args", - ), + ) parser.add_option( "", diff --git a/com/win32comext/adsi/demos/test.py b/com/win32comext/adsi/demos/test.py index 43c85d6b83..5e7467c223 100644 --- a/com/win32comext/adsi/demos/test.py +++ b/com/win32comext/adsi/demos/test.py @@ -158,7 +158,9 @@ def DumpSchema2(): iid_name = win32com.util.IIDToInterfaceName(item.PrimaryInterface) if verbose_level >= 2: print( - f"Class: Name={item.Name}, Flags={desc}, Primary Interface={iid_name}" + "Class: Name={}, Flags={}, Primary Interface={}".format( + item.Name, desc, iid_name + ) ) nclass += 1 elif item_class == "property": diff --git a/com/win32comext/axdebug/adb.py b/com/win32comext/axdebug/adb.py index 1910418090..ee6b620c58 100644 --- a/com/win32comext/axdebug/adb.py +++ b/com/win32comext/axdebug/adb.py @@ -1,5 +1,4 @@ -"""The glue between the Python debugger interface and the Active Debugger interface -""" +"""The glue between the Python debugger interface and the Active Debugger interface""" import _thread import bdb diff --git a/com/win32comext/axdebug/codecontainer.py b/com/win32comext/axdebug/codecontainer.py index e7502845d9..8546d0c03e 100644 --- a/com/win32comext/axdebug/codecontainer.py +++ b/com/win32comext/axdebug/codecontainer.py @@ -229,7 +229,7 @@ def GetText(self): try: self.text = open(fname, "r").read() except OSError as details: - self.text = f"# COMException opening file\n# {repr(details)}" + self.text = f"# COMException opening file\n# {details!r}" else: self.text = f"# No file available for module '{self.module}'" self._buildlines() diff --git a/com/win32comext/axdebug/contexts.py b/com/win32comext/axdebug/contexts.py index df6e97760f..d732fbae1e 100644 --- a/com/win32comext/axdebug/contexts.py +++ b/com/win32comext/axdebug/contexts.py @@ -1,6 +1,4 @@ -""" A module for managing the AXDebug I*Contexts - -""" +"""A module for managing the AXDebug I*Contexts""" from . import adb, axdebug, gateways diff --git a/com/win32comext/axdebug/documents.py b/com/win32comext/axdebug/documents.py index 560901fb42..723d2bf13e 100644 --- a/com/win32comext/axdebug/documents.py +++ b/com/win32comext/axdebug/documents.py @@ -1,5 +1,4 @@ -""" Management of documents for AXDebugging. -""" +"""Management of documents for AXDebugging.""" import pythoncom import win32api @@ -106,7 +105,7 @@ class CodeContainerProvider: Given a Python file name (as the debugger knows it by) this will return a CodeContainer interface suitable for use. - This provides a simple base imlpementation that simply supports + This provides a simple base implementation that simply supports a dictionary of nodes and providers. """ diff --git a/com/win32comext/axdebug/dump.py b/com/win32comext/axdebug/dump.py index 61a1cfc7ab..6c149daa01 100644 --- a/com/win32comext/axdebug/dump.py +++ b/com/win32comext/axdebug/dump.py @@ -28,7 +28,7 @@ def DumpDebugApplicationNode(node, level=0): numLines, numChars = doctext.GetSize() # text, attr = doctext.GetText(0, 20, 1) text, attr = doctext.GetText(0, numChars, 1) - print(f"{spacer}Text is {repr(text[:40] + '...')}, {len(text)} bytes long") + print(f"{spacer}Text is '{text[:40] + '...'}', {len(text)} bytes long") else: print(f"{spacer*2}") @@ -46,9 +46,7 @@ def dumpall(): e = Enumerator(dm.EnumApplications()) for app in e: print(f"Application: {app.GetName()}") - node = ( - app.GetRootNode() - ) # of type PyIDebugApplicationNode->PyIDebugDocumentProvider->PyIDebugDocumentInfo + node = app.GetRootNode() # of type PyIDebugApplicationNode->PyIDebugDocumentProvider->PyIDebugDocumentInfo DumpDebugApplicationNode(node) diff --git a/com/win32comext/axdebug/util.py b/com/win32comext/axdebug/util.py index 424c529df1..b1b560e40e 100644 --- a/com/win32comext/axdebug/util.py +++ b/com/win32comext/axdebug/util.py @@ -3,6 +3,7 @@ import os import sys +import traceback import win32api import win32com.server.dispatcher @@ -43,13 +44,8 @@ def RaiseNotImpl(who=None): print(f"********* Function {who} Raising E_NOTIMPL ************") # Print a sort-of "traceback", dumping all the frames leading to here. - try: - 1 / 0 - except: - frame = sys.exc_info()[2].tb_frame - while frame: + for frame, i in traceback.walk_stack(sys._getframe()): print(f"File: {frame.f_code.co_filename}, Line: {frame.f_lineno}") - frame = frame.f_back # and raise the exception for COM raise COMException(scode=winerror.E_NOTIMPL) @@ -89,7 +85,7 @@ def _Invoke_(self, dispid, lcid, wFlags, args): tb = None # A cycle scode = v.scode try: - desc = " (" + str(v.description) + ")" + desc = f" ({v.description})" except AttributeError: desc = "" print(f"*** Invoke of {dispid} raised COM exception 0x{scode:x}{desc}") diff --git a/com/win32comext/axscript/client/debug.py b/com/win32comext/axscript/client/debug.py index 352b86453e..bf7ef960ad 100644 --- a/com/win32comext/axscript/client/debug.py +++ b/com/win32comext/axscript/client/debug.py @@ -125,12 +125,7 @@ def _query_interface_for_debugger_(self, iid): def OnEnterScript(self): trace("OnEnterScript") - try: - 1 / 0 - except: - # Bit of a hack - reach into engine. - baseFrame = sys.exc_info()[2].tb_frame.f_back - self.adb.SetupAXDebugging(baseFrame) + self.adb.SetupAXDebugging(sys._getframe().f_back) def OnLeaveScript(self): trace("OnLeaveScript") diff --git a/com/win32comext/axscript/client/error.py b/com/win32comext/axscript/client/error.py index 5aadbf9bc0..41711abdd8 100644 --- a/com/win32comext/axscript/client/error.py +++ b/com/win32comext/axscript/client/error.py @@ -1,7 +1,7 @@ """Exception and error handling. - This contains the core exceptions that the implementations should raise - as well as the IActiveScriptError interface code. +This contains the core exceptions that the implementations should raise +as well as the IActiveScriptError interface code. """ from __future__ import annotations @@ -247,8 +247,8 @@ def ProcessAXScriptException( result = scriptingSite.OnScriptError(gateway) except pythoncom.com_error as details: print("**OnScriptError failed:", details) - print("Exception description:'%s'" % (repr(exceptionInstance.description))) - print("Exception text:'%s'" % (repr(exceptionInstance.linetext))) + print(f"Exception description: '{exceptionInstance.description!r}'") + print(f"Exception text: '{exceptionInstance.linetext!r}'") result = winerror.S_FALSE if result == winerror.S_OK: diff --git a/com/win32comext/axscript/client/framework.py b/com/win32comext/axscript/client/framework.py index 85a312b09d..c4a04329f8 100644 --- a/com/win32comext/axscript/client/framework.py +++ b/com/win32comext/axscript/client/framework.py @@ -1,10 +1,10 @@ """AXScript Client Framework - This module provides a core framework for an ActiveX Scripting client. - Derived classes actually implement the AX Client itself, including the - scoping rules, etc. +This module provides a core framework for an ActiveX Scripting client. +Derived classes actually implement the AX Client itself, including the +scoping rules, etc. - There are classes defined for the engine itself, and for ScriptItems +There are classes defined for the engine itself, and for ScriptItems """ from __future__ import annotations @@ -766,7 +766,9 @@ def SetScriptSite(self, site): except: traceback.print_exc() trace( - f"*** Debugger Manager could not initialize - {sys.exc_info()[0]}: {sys.exc_info()[1]}" + "*** Debugger Manager could not initialize - {}: {}".format( + sys.exc_info()[0], sys.exc_info()[1] + ) ) self.debugManager = None diff --git a/com/win32comext/axscript/client/pyscript.py b/com/win32comext/axscript/client/pyscript.py index fd7806073d..1327451884 100644 --- a/com/win32comext/axscript/client/pyscript.py +++ b/com/win32comext/axscript/client/pyscript.py @@ -100,7 +100,7 @@ def _FindAttribute_(self, attr): class NamedScriptAttribute: - "An explicitely named object in an objects namespace" + "An explicitly named object in an objects namespace" # Each named object holds a reference to one of these. # Whenever a sub-item appears in a namespace, it is really one of these @@ -110,7 +110,7 @@ def __init__(self, scriptItem): self.__dict__["_scriptItem_"] = scriptItem def __repr__(self): - return "" + return f"" def __getattr__(self, attr): # If a known subitem, return it. diff --git a/com/win32comext/axscript/client/scriptdispatch.py b/com/win32comext/axscript/client/scriptdispatch.py index ca696fe849..6bd29adcb0 100644 --- a/com/win32comext/axscript/client/scriptdispatch.py +++ b/com/win32comext/axscript/client/scriptdispatch.py @@ -1,8 +1,8 @@ """dynamic dispatch objects for AX Script. - This is an IDispatch object that a scripting host may use to - query and invoke methods on the main script. Not may hosts use - this yet, so it is not well tested! +This is an IDispatch object that a scripting host may use to +query and invoke methods on the main script. Not may hosts use +this yet, so it is not well tested! """ from __future__ import annotations diff --git a/com/win32comext/axscript/test/leakTest.py b/com/win32comext/axscript/test/leakTest.py index 9612553721..8ac3954e7d 100644 --- a/com/win32comext/axscript/test/leakTest.py +++ b/com/win32comext/axscript/test/leakTest.py @@ -144,10 +144,10 @@ def doTestEngine(engine, echoer): print("***** Calling 'hello' failed", exc) return if echoer.last != "Goober": - print("***** Function call didn't set value correctly", repr(echoer.last)) + print(f"***** Function call didnt set value correctly {echoer.last!r}") if str(ob.prop) != "Property Value": - print("***** Property Value not correct - ", repr(ob.prop)) + print(f"***** Property Value not correct - {ob.prop!r}") ob.testcollection() diff --git a/com/win32comext/mapi/mapitags.py b/com/win32comext/mapi/mapitags.py index e6e9667e02..e3238b6624 100644 --- a/com/win32comext/mapi/mapitags.py +++ b/com/win32comext/mapi/mapitags.py @@ -824,7 +824,7 @@ def PROP_TAG(ulPropType, ulPropID): PROP_ID_SECURE_MIN = 26608 PROP_ID_SECURE_MAX = 26623 -# From EDKMDB.H +# From EdkMdb.h pidExchangeXmitReservedMin = 16352 pidExchangeNonXmitReservedMin = 26080 pidProfileMin = 26112 diff --git a/com/win32comext/mapi/mapiutil.py b/com/win32comext/mapi/mapiutil.py index 5ae387f2ac..c677317186 100644 --- a/com/win32comext/mapi/mapiutil.py +++ b/com/win32comext/mapi/mapiutil.py @@ -203,7 +203,7 @@ def SetProperties(msg, propDict): tagType = mapitags.PT_SYSTIME else: raise ValueError( - f"The type of object {repr(val)}({type(val)}) can not be written" + f"The type of object {val!r}({type(val)}) can not be written" ) key = mapitags.PROP_TAG(tagType, mapitags.PROP_ID(newIds[newIdNo])) newIdNo += 1 diff --git a/com/win32comext/shell/demos/servers/empty_volume_cache.py b/com/win32comext/shell/demos/servers/empty_volume_cache.py index 084e97c4f6..b5fb32e15e 100644 --- a/com/win32comext/shell/demos/servers/empty_volume_cache.py +++ b/com/win32comext/shell/demos/servers/empty_volume_cache.py @@ -155,7 +155,9 @@ def DllRegisterServer(): # See link at top of file. import winreg - kn = rf"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{EmptyVolumeCache._reg_desc_}" + kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( + EmptyVolumeCache._reg_desc_, + ) key = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, kn) winreg.SetValueEx(key, None, 0, winreg.REG_SZ, EmptyVolumeCache._reg_clsid_) @@ -163,7 +165,9 @@ def DllRegisterServer(): def DllUnregisterServer(): import winreg - kn = rf"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{EmptyVolumeCache._reg_desc_}" + kn = r"Software\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\{}".format( + 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 31287117f2..f00e383cc3 100644 --- a/com/win32comext/shell/demos/servers/folder_view.py +++ b/com/win32comext/shell/demos/servers/folder_view.py @@ -529,7 +529,7 @@ def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags): def InvokeCommand(self, ci): mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci - # this seems very convuluted, but it's what the sample does :) + # this seems very convoluted, but it's what the sample does :) for verb_name, verb_id, flag in folderViewImplContextMenuIDs: if isinstance(verb, int): matches = verb == verb_id @@ -821,7 +821,10 @@ 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 = f"{ContextMenu._context_menu_type_}\\shellex\\ContextMenuHandlers\\{ContextMenu._reg_desc_}" + keypath = "{}\\shellex\\ContextMenuHandlers\\{}".format( + ContextMenu._context_menu_type_, + 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()) @@ -834,7 +837,9 @@ def DllUnregisterServer(): paths = [ "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Desktop\\Namespace\\" + ShellFolder._reg_clsid_, - f"{ContextMenu._context_menu_type_}\\shellex\\ContextMenuHandlers\\{ContextMenu._reg_desc_}", + "{}\\shellex\\ContextMenuHandlers\\{}".format( + ContextMenu._context_menu_type_, ContextMenu._reg_desc_ + ), ] for path in paths: try: diff --git a/com/win32comext/shell/demos/servers/shell_view.py b/com/win32comext/shell/demos/servers/shell_view.py index 01d1294898..1b62c4faef 100644 --- a/com/win32comext/shell/demos/servers/shell_view.py +++ b/com/win32comext/shell/demos/servers/shell_view.py @@ -150,7 +150,7 @@ def BindToObject(self, pidl, bc, iid): elif typ == "object": klass = ShellFolderObject else: - raise RuntimeError("What is " + repr(typ)) + raise RuntimeError(f"What is {typ!r}") ret = wrap(klass(extra), iid, useDispatcher=(debug > 0)) return ret @@ -369,7 +369,7 @@ def Initialize(self, pidl): # This is the PIDL of us, as created by the shell. This is our # top-level ID. All other items under us have PIDLs defined # by us - see the notes at the top of the file. - # print("Initialize called with pidl", repr(pidl)) + # print("Initialize called with pidl={pidl!r}") self.pidl = pidl def CreateViewObject(self, hwnd, iid): diff --git a/isapi/samples/redirector_with_filter.py b/isapi/samples/redirector_with_filter.py index 6d9914c040..393e89d059 100644 --- a/isapi/samples/redirector_with_filter.py +++ b/isapi/samples/redirector_with_filter.py @@ -84,6 +84,7 @@ def Dispatch(self, ecb): # The ISAPI filter. class Filter(SimpleFilter): "Sample Python Redirector" + filter_flags = isapicon.SF_NOTIFY_PREPROC_HEADERS | isapicon.SF_NOTIFY_ORDER_DEFAULT def HttpFilterProc(self, fc): diff --git a/isapi/simple.py b/isapi/simple.py index d5fcb04d7c..177e8935cd 100644 --- a/isapi/simple.py +++ b/isapi/simple.py @@ -40,6 +40,7 @@ def TerminateExtension(self, status): class SimpleFilter: "Base class for a a simple ISAPI filter" + filter_flags: int | None = None def __init__(self): diff --git a/isapi/threaded_extension.py b/isapi/threaded_extension.py index 044b909877..b6a161a23a 100644 --- a/isapi/threaded_extension.py +++ b/isapi/threaded_extension.py @@ -60,6 +60,7 @@ def call_handler(self, cblock): # fully asynch extension. class ThreadPoolExtension(isapi.simple.SimpleExtension): "Base class for an ISAPI extension based around a thread-pool" + max_workers = 20 worker_shutdown_wait = 15000 # 15 seconds for workers to quit... diff --git a/pywin32_postinstall.py b/pywin32_postinstall.py index a9dd85645d..e90e354d9f 100644 --- a/pywin32_postinstall.py +++ b/pywin32_postinstall.py @@ -8,10 +8,16 @@ import shutil import sys import sysconfig -import tempfile # Send output somewhere so it can be found if necessary... +import tempfile import winreg -tee_f = open(os.path.join(tempfile.gettempdir(), "pywin32_postinstall.log"), "w") +tee_f = open( + os.path.join( + tempfile.gettempdir(), # Send output somewhere so it can be found if necessary... + "pywin32_postinstall.log", + ), + "w", +) class Tee: @@ -35,13 +41,6 @@ def flush(self): tee_f.flush() -# For some unknown reason, when running under bdist_wininst we will start up -# with sys.stdout as None but stderr is hooked up. This work-around allows -# bdist_wininst to see the output we write and display it at the end of -# the install. -if sys.stdout is None: # pyright: ignore[reportUnnecessaryComparison] - sys.stdout = sys.stderr - sys.stderr = Tee(sys.stderr) sys.stdout = Tee(sys.stdout) @@ -61,80 +60,60 @@ def flush(self): root_key_name = "Software\\Python\\PythonCore\\" + sys.winver -try: - # When this script is run from inside the bdist_wininst installer, - # file_created() and directory_created() are additional builtin - # functions which write lines to PythonXX\pywin32-install.log. This is - # a list of actions for the uninstaller, the format is inspired by what - # the Wise installer also creates. - file_created # type: ignore[used-before-def] - # 3.10 stopped supporting bdist_wininst, but we can still build them with 3.9. - # This can be kept until Python 3.9 or exe installers support is dropped. - is_bdist_wininst = True -except NameError: - is_bdist_wininst = False # we know what it is not - but not what it is :) - - def file_created(file): - pass - - def directory_created(directory): - pass - - def get_root_hkey(): - try: - winreg.OpenKey( - winreg.HKEY_LOCAL_MACHINE, root_key_name, 0, winreg.KEY_CREATE_SUB_KEY - ) - return winreg.HKEY_LOCAL_MACHINE - except OSError: - # Either not exist, or no permissions to create subkey means - # must be HKCU - return winreg.HKEY_CURRENT_USER - - -try: - create_shortcut # type: ignore[used-before-def] -except NameError: - # Create a function with the same signature as create_shortcut provided - # by bdist_wininst - def create_shortcut( - path, description, filename, arguments="", workdir="", iconpath="", iconindex=0 - ): - import pythoncom - from win32com.shell import shell - ilink = pythoncom.CoCreateInstance( - shell.CLSID_ShellLink, - None, - pythoncom.CLSCTX_INPROC_SERVER, - shell.IID_IShellLink, +def get_root_hkey(): + try: + winreg.OpenKey( + winreg.HKEY_LOCAL_MACHINE, root_key_name, 0, winreg.KEY_CREATE_SUB_KEY ) - ilink.SetPath(path) - ilink.SetDescription(description) - if arguments: - ilink.SetArguments(arguments) - if workdir: - ilink.SetWorkingDirectory(workdir) - if iconpath or iconindex: - ilink.SetIconLocation(iconpath, iconindex) - # now save it. - ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile) - ipf.Save(filename, 0) - - # Support the same list of "path names" as bdist_wininst. - def get_special_folder_path(path_name): - from win32com.shell import shell, shellcon - - for maybe in """ - CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA - CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY - CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP - CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON - CSIDL_PROGRAM_FILES CSIDL_FONTS""".split(): - if maybe == path_name: - csidl = getattr(shellcon, maybe) - return shell.SHGetSpecialFolderPath(0, csidl, False) - raise ValueError(f"{path_name} is an unknown path ID") + return winreg.HKEY_LOCAL_MACHINE + except OSError: + # Either not exist, or no permissions to create subkey means + # must be HKCU + return winreg.HKEY_CURRENT_USER + + +# Create a function with the same signature as create_shortcut +# previously provided by bdist_wininst +def create_shortcut( + path, description, filename, arguments="", workdir="", iconpath="", iconindex=0 +): + import pythoncom + from win32com.shell import shell + + ilink = pythoncom.CoCreateInstance( + shell.CLSID_ShellLink, + None, + pythoncom.CLSCTX_INPROC_SERVER, + shell.IID_IShellLink, + ) + ilink.SetPath(path) + ilink.SetDescription(description) + if arguments: + ilink.SetArguments(arguments) + if workdir: + ilink.SetWorkingDirectory(workdir) + if iconpath or iconindex: + ilink.SetIconLocation(iconpath, iconindex) + # now save it. + ipf = ilink.QueryInterface(pythoncom.IID_IPersistFile) + ipf.Save(filename, 0) + + +# Support the same list of "path names" as bdist_wininst used to +def get_special_folder_path(path_name): + from win32com.shell import shell, shellcon + + for maybe in """ + CSIDL_COMMON_STARTMENU CSIDL_STARTMENU CSIDL_COMMON_APPDATA + CSIDL_LOCAL_APPDATA CSIDL_APPDATA CSIDL_COMMON_DESKTOPDIRECTORY + CSIDL_DESKTOPDIRECTORY CSIDL_COMMON_STARTUP CSIDL_STARTUP + CSIDL_COMMON_PROGRAMS CSIDL_PROGRAMS CSIDL_PROGRAM_FILES_COMMON + CSIDL_PROGRAM_FILES CSIDL_FONTS""".split(): + if maybe == path_name: + csidl = getattr(shellcon, maybe) + return shell.SHGetSpecialFolderPath(0, csidl, False) + raise ValueError(f"{path_name} is an unknown path ID") def CopyTo(desc, src, dest): @@ -270,14 +249,14 @@ def RegisterPythonwin(register=True, lib_dir=None): """Add (or remove) Pythonwin to context menu for python scripts. ??? Should probably also add Edit command for pys files also. Also need to remove these keys on uninstall, but there's no function - like file_created to add registry entries to uninstall log ??? + to add registry entries to uninstall log ??? """ import os if lib_dir is None: lib_dir = sysconfig.get_paths()["platlib"] classes_root = get_root_hkey() - ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build, + ## Installer executable doesn't seem to pass anything to postinstall script indicating if it's a debug build pythonwin_exe = os.path.join(lib_dir, "Pythonwin", "Pythonwin.exe") pythonwin_edit_command = pythonwin_exe + ' -edit "%1"' @@ -395,7 +374,6 @@ def fixup_dbi(): else: os.rename(this_pyd, this_dest) print(f"renamed '{this_pyd}'->'{this_pyd}.old'") - file_created(this_pyd + ".old") except OSError as exc: print(f"FAILED to rename '{this_pyd}': {exc}") @@ -446,8 +424,6 @@ def install(lib_dir): CopyTo("installing %s" % base, fname, dst) if verbose: print(f"Copied {base} to {dst}") - # Register the files with the uninstaller - file_created(dst) worked = 1 # Nuke any other versions that may exist - having # duplicates causes major headaches. @@ -484,11 +460,6 @@ def install(lib_dir): "You don't have enough permissions to install the system files" ) - # Pythonwin 'compiles' config files - record them for uninstall. - pywin_dir = os.path.join(lib_dir, "Pythonwin", "pywin") - for fname in glob.glob(os.path.join(pywin_dir, "*.cfg")): - file_created(fname[:-1] + "c") # .cfg->.cfc - # Register our demo COM objects. try: try: @@ -534,7 +505,6 @@ def install(lib_dir): if not os.path.isdir(make_dir): if verbose: print(f"Creating directory {make_dir}") - directory_created(make_dir) os.mkdir(make_dir) try: @@ -553,7 +523,6 @@ def install(lib_dir): "", sys.prefix, ) - file_created(dst) if verbose: print("Shortcut for Pythonwin created") # And the docs. @@ -561,7 +530,6 @@ def install(lib_dir): dst = os.path.join(fldr, "Python for Windows Documentation.lnk") doc = "Documentation for the PyWin32 extensions" create_shortcut(chm_file, doc, dst) - file_created(dst) if verbose: print("Shortcut to documentation created") else: @@ -579,15 +547,6 @@ def install(lib_dir): pass print("The pywin32 extensions were successfully installed.") - if is_bdist_wininst: - # Open a web page with info about the .exe installers being deprecated. - import webbrowser - - try: - webbrowser.open("https://mhammond.github.io/pywin32_installers.html") - except webbrowser.Error: - print("Please visit https://mhammond.github.io/pywin32_installers.html") - def uninstall(lib_dir): # First ensure our system modules are loaded from pywin32_system, so @@ -677,14 +636,10 @@ def uninstall(lib_dir): print(f"FAILED to remove system files: {why}") -# NOTE: If this script is run from inside the bdist_wininst created -# binary installer or uninstaller, the command line args are either -# '-install' or '-remove'. - -# Important: From inside the binary installer this script MUST NOT -# call sys.exit() or raise SystemExit, otherwise not only this script -# but also the installer will terminate! (Is there a way to prevent -# this from the bdist_wininst C code?) +# NOTE: This used to be run from inside the bdist_wininst created binary un/installer. +# From inside the binary installer this script HAD to NOT +# call sys.exit() or raise SystemExit, otherwise the installer would also terminate! +# Out of principle, we're still not using system exits. def verify_destination(location): @@ -702,13 +657,15 @@ def main(): > python pywin32_postinstall.py -install - If you installed pywin32 via a .exe installer, this should be run - automatically after installation, but if it fails you can run it again. + This should be run automatically after installation, + but if it fails you can run it again. - If you installed pywin32 via PIP, you almost certainly need to run this to + Given EXE installers are no longer provided, + and wheel installs can't run postinstall scripts, + you almost certainly need to run this to setup the environment correctly. - Execute with script with a '-install' parameter, to ensure the environment + Execute this script with a '-install' parameter, to ensure the environment is setup correctly. """, ) @@ -770,8 +727,7 @@ def main(): install(args.destination) if args.remove: - if not is_bdist_wininst: - uninstall(args.destination) + uninstall(args.destination) if __name__ == "__main__": diff --git a/setup.py b/setup.py index d5c6148e7b..b463cc1193 100644 --- a/setup.py +++ b/setup.py @@ -9,14 +9,14 @@ To build and install locally for testing etc, you need a build environment which is capable of building the version of Python you are targeting, then: - python setup.py -q install + pip install . -v For a debug (_d) version, you need a local debug build of Python, but must use the release version executable for the build. eg: - python setup.py -q build --debug install + pip install . -v --config-setting=--build-option=build --config-setting=--build-option=--debug Cross-compilation from x86 to ARM is well supported (assuming installed vs tools etc) - eg: - python setup.py -q build_ext --plat-name win-arm64 build --plat-name win-arm64 bdist_wheel --plat-name win-arm64 + python -m build --wheel --config-setting=--build-option=build_ext --config-setting=--build-option=--plat-name=win-arm64 --config-setting=--build-option=build --config-setting=--build-option=--plat-name=win-arm64 --config-setting=--build-option=bdist_wheel --config-setting=--build-option=--plat-name=win-arm64 Some modules require special SDKs or toolkits to build (eg, mapi/exchange), which often aren't available in CI. The build process treats them as optional - @@ -39,7 +39,6 @@ from setuptools.command.build import build from setuptools.command.build_ext import build_ext from setuptools.command.install import install -from setuptools.command.install_lib import install_lib from setuptools.modified import newer_group from tempfile import gettempdir from typing import Iterable @@ -95,7 +94,6 @@ def __init__( export_symbols=None, export_symbol_file=None, pch_header=None, - windows_h_version=None, # min version of windows.h needed. extra_swig_commands=None, is_regular_dll=False, # regular Windows DLL? # list of headers which may not be installed forcing us to @@ -126,7 +124,6 @@ def __init__( define_macros.append(("CRYPT_DECRYPT_MESSAGE_PARA_HAS_EXTRA_FIELDS", None)) self.pch_header = pch_header self.extra_swig_commands = extra_swig_commands or [] - self.windows_h_version = windows_h_version self.optional_headers = optional_headers self.is_regular_dll = is_regular_dll self.base_address = base_address @@ -255,10 +252,6 @@ def get_pywin32_dir(self): class WinExt_win32com(WinExt): def __init__(self, name, **kw): kw["libraries"] = kw.get("libraries", "") + " oleaut32 ole32" - - # COM extensions require later windows headers. - if not kw.get("windows_h_version"): - kw["windows_h_version"] = 0x500 WinExt.__init__(self, name, **kw) def get_pywin32_dir(self): @@ -364,8 +357,6 @@ def finalize_options(self): "win-arm64": "arm64", }.get(self.plat_name, "x86") - self.windows_h_version = None - # The pywintypes library is created in the build_temp # directory, so we need to add this to library_dirs self.library_dirs.append(self.build_temp) @@ -381,19 +372,12 @@ def _why_cant_build_extension(self, ext): # axdebug fails to build on 3.11 due to Python "frame" objects changing. # This could be fixed, but is almost certainly not in use any more, so # just skip it. - if ext.name == "axdebug" and sys.version_info > (3, 10): + if ext.name == "axdebug" and sys.version_info >= (3, 11): return "AXDebug no longer builds on 3.11 and up" include_dirs = self.compiler.include_dirs + os.environ.get("INCLUDE", "").split( os.pathsep ) - if self.windows_h_version is None: - # Note that we used to try and find WINVER or _WIN32_WINNT macros - # here defining the version of the Windows SDK we use and check - # it was late enough for the extension being built. But since we - # moved to the Windows 8.1 SDK (or later), this isn't necessary - # as all modules require less than this. - pass look_dirs = include_dirs for h in ext.optional_headers: @@ -453,7 +437,6 @@ def _build_scintilla(self): assert os.path.isdir(build_temp), build_temp makeargs.append("SUB_DIR_O=%s" % build_temp) makeargs.append("SUB_DIR_BIN=%s" % build_temp) - makeargs.append("DIR_PYTHON=%s" % sys.prefix) nmake = "nmake.exe" # Attempt to resolve nmake to the same one that our compiler object @@ -617,7 +600,8 @@ 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()] + rf"\VC\Redist\MSVC\{vcverdir}{self.plat_dir}" + vcbase[: m.start()] + + r"\VC\Redist\MSVC\{}{}".format(vcverdir, self.plat_dir) ) redist_globs.append( vcbase[: m.start()] @@ -860,52 +844,40 @@ def swig_sources(self, sources, ext=None): class my_install(install): def run(self): + """Custom script we run at the end of installing + This is only run for local installs. Wheel-based installs won't run this code. + """ install.run(self) - # Custom script we run at the end of installing - this is the same script - # run by bdist_wininst - # If self.root has a value, it means we are being "installed" into - # some other directory than Python itself (eg, into a temp directory - # for bdist_wininst to use) - in which case we must *not* run our - # installer - if not self.dry_run and not self.root: - # We must run the script we just installed into Scripts, as it - # may have had 2to3 run over it. - filename = os.path.join(self.install_scripts, "pywin32_postinstall.py") - if not os.path.isfile(filename): - raise RuntimeError(f"Can't find '{filename}'") - print("Executing post install script...") - # As of setuptools>=74.0.0, we no longer need to - # be concerned about distutils calling win32api - subprocess.Popen( - [ - sys.executable, - filename, - "-install", - "-destination", - self.install_lib, - "-quiet", - "-wait", - str(os.getpid()), - ] + # If self.root has a value, it means we are being "installed" into some other + # directory than Python itself - in which case we must *not* run our installer. + # bdist_wininst used to trigger this by using a temp directory. + # Is this still a concern ? + if self.root: + print( + "Not executing post install script when " + + f"not installing in Python itself (self.root={self.root})" ) - - -class my_install_lib(install_lib): - def install(self): - # This is crazy - in setuptools 61.1.0 (and probably some earlier versions), the - # install_lib and build comments don't agree on where the .py files to install can - # be found, so we end up with a warning logged: - # `warning: my_install_lib: 'build\lib.win-amd64-3.8' does not exist -- no Python modules to install` - # (because they are actually in `build\lib.win-amd64-cpython-38`!) - # It's not an error though, so we end up with .exe installers lacking our lib files! - builder = self.get_finalized_command("build") - if os.path.isdir(builder.build_platlib) and not os.path.isdir(self.build_dir): - self.build_dir = builder.build_platlib - # We want a failure to find .py files be an error rather than a warning. - outfiles = super().install() - if not outfiles: - raise RuntimeError("No Python files were found to install") - return outfiles + return + self.execute(self._postinstall, (), msg="Executing post install script...") + + def _postinstall(self): + filename = os.path.join(self.install_scripts, "pywin32_postinstall.py") + if not os.path.isfile(filename): + raise RuntimeError(f"Can't find '{filename}'") + # As of setuptools>=74.0.0, we no longer need to + # be concerned about distutils calling win32api + subprocess.Popen( + [ + sys.executable, + filename, + "-install", + "-destination", + self.install_lib, + "-quiet", + "-wait", + str(os.getpid()), + ] + ) def my_new_compiler(**kw): @@ -920,13 +892,6 @@ def my_new_compiler(**kw): class my_compiler(MSVCCompiler): - # Just one GUIDS.CPP and it gives trouble on mainwin too. Maybe I - # should just rename the file, but a case-only rename is likely to be - # worse! This can probably go away once we kill the VS project files - # though, as we can just specify the lowercase name in the module def. - _cpp_extensions = MSVCCompiler._cpp_extensions + [".CPP"] - src_extensions = MSVCCompiler.src_extensions + [".CPP"] - def link( self, target_desc, @@ -1088,135 +1053,121 @@ def finalize_options(self): ), ) -for info in ( - # (name, libraries, WINVER, sources) - ("mmapfile", "", None, "win32/src/mmapfilemodule.cpp"), - ("odbc", "odbc32 odbccp32", None, "win32/src/odbc.cpp"), +for name, libraries, sources in ( + ("mmapfile", "", "win32/src/mmapfilemodule.cpp"), + ("odbc", "odbc32 odbccp32", "win32/src/odbc.cpp"), ( "perfmon", "", - None, """ - win32/src/PerfMon/MappingManager.cpp - win32/src/PerfMon/PerfCounterDefn.cpp - win32/src/PerfMon/PerfObjectType.cpp - win32/src/PerfMon/PyPerfMon.cpp - """, + win32/src/PerfMon/MappingManager.cpp + win32/src/PerfMon/PerfCounterDefn.cpp + win32/src/PerfMon/PerfObjectType.cpp + win32/src/PerfMon/PyPerfMon.cpp + """, ), - ("timer", "user32", None, "win32/src/timermodule.cpp"), - ("win32cred", "AdvAPI32 credui", 0x0501, "win32/src/win32credmodule.cpp"), + ("timer", "user32", "win32/src/timermodule.cpp"), + ("win32cred", "AdvAPI32 credui", "win32/src/win32credmodule.cpp"), ( "win32crypt", "Crypt32 Advapi32", - 0x0500, """ - win32/src/win32crypt/win32cryptmodule.cpp - win32/src/win32crypt/win32crypt_structs.cpp - win32/src/win32crypt/PyCERTSTORE.cpp - win32/src/win32crypt/PyCERT_CONTEXT.cpp - win32/src/win32crypt/PyCRYPTHASH.cpp - win32/src/win32crypt/PyCRYPTKEY.cpp - win32/src/win32crypt/PyCRYPTMSG.cpp - win32/src/win32crypt/PyCRYPTPROV.cpp - win32/src/win32crypt/PyCTL_CONTEXT.cpp - """, + win32/src/win32crypt/win32cryptmodule.cpp + win32/src/win32crypt/win32crypt_structs.cpp + win32/src/win32crypt/PyCERTSTORE.cpp + win32/src/win32crypt/PyCERT_CONTEXT.cpp + win32/src/win32crypt/PyCRYPTHASH.cpp + win32/src/win32crypt/PyCRYPTKEY.cpp + win32/src/win32crypt/PyCRYPTMSG.cpp + win32/src/win32crypt/PyCRYPTPROV.cpp + win32/src/win32crypt/PyCTL_CONTEXT.cpp + """, ), ( "win32file", "ws2_32 mswsock", - 0x0500, """ - win32/src/win32file.i - win32/src/win32file_comm.cpp - """, + win32/src/win32file.i + win32/src/win32file_comm.cpp + """, ), - ("win32event", "user32", None, "win32/src/win32event.i"), + ("win32event", "user32", "win32/src/win32event.i"), ( "win32clipboard", "gdi32 user32 shell32", - None, "win32/src/win32clipboardmodule.cpp", ), # win32gui handled below - ("win32job", "user32", 0x0500, "win32/src/win32job.i"), - ("win32lz", "lz32", None, "win32/src/win32lzmodule.cpp"), + ("win32job", "user32", "win32/src/win32job.i"), + ("win32lz", "lz32", "win32/src/win32lzmodule.cpp"), ( "win32net", "netapi32 advapi32", - None, """ - win32/src/win32net/win32netfile.cpp win32/src/win32net/win32netgroup.cpp - win32/src/win32net/win32netmisc.cpp win32/src/win32net/win32netmodule.cpp - win32/src/win32net/win32netsession.cpp win32/src/win32net/win32netuse.cpp - win32/src/win32net/win32netuser.cpp - """, + win32/src/win32net/win32netfile.cpp + win32/src/win32net/win32netgroup.cpp + win32/src/win32net/win32netmisc.cpp + win32/src/win32net/win32netmodule.cpp + win32/src/win32net/win32netsession.cpp + win32/src/win32net/win32netuse.cpp + win32/src/win32net/win32netuser.cpp + """, ), - ("win32pdh", "", None, "win32/src/win32pdhmodule.cpp"), - ("win32pipe", "", None, "win32/src/win32pipe.i"), + ("win32pdh", "", "win32/src/win32pdhmodule.cpp"), + ("win32pipe", "", "win32/src/win32pipe.i"), ( "win32print", "winspool user32 gdi32", - 0x0500, "win32/src/win32print/win32print.cpp", ), - ("win32process", "advapi32 user32", 0x0500, "win32/src/win32process.i"), - ("win32profile", "Userenv", None, "win32/src/win32profilemodule.cpp"), - ("win32ras", "rasapi32 user32", 0x0500, "win32/src/win32rasmodule.cpp"), + ("win32process", "advapi32 user32", "win32/src/win32process.i"), + ("win32profile", "Userenv", "win32/src/win32profilemodule.cpp"), + ("win32ras", "rasapi32 user32", "win32/src/win32rasmodule.cpp"), ( "win32security", "advapi32 user32 netapi32", - 0x0500, """ - win32/src/win32security.i - win32/src/win32security_sspi.cpp win32/src/win32security_ds.cpp - """, + win32/src/win32security.i + win32/src/win32security_sspi.cpp + win32/src/win32security_ds.cpp + """, ), ( "win32service", "advapi32 oleaut32 user32", - 0x0501, """ - win32/src/win32service_messages.mc - win32/src/win32service.i - """, + win32/src/win32service_messages.mc + win32/src/win32service.i + """, ), - ("win32trace", "advapi32", None, "win32/src/win32trace.cpp"), + ("win32trace", "advapi32", "win32/src/win32trace.cpp"), ( "win32wnet", "netapi32 mpr", - None, """ - win32/src/win32wnet/PyNCB.cpp - win32/src/win32wnet/PyNetresource.cpp - win32/src/win32wnet/win32wnet.cpp - """, + win32/src/win32wnet/PyNCB.cpp + win32/src/win32wnet/PyNetresource.cpp + win32/src/win32wnet/win32wnet.cpp + """, ), ( "win32inet", "wininet", - 0x500, """ - win32/src/win32inet.i - win32/src/win32inet_winhttp.cpp - """, + win32/src/win32inet.i + win32/src/win32inet_winhttp.cpp + """, ), - ("win32console", "kernel32", 0x0501, "win32/src/win32consolemodule.cpp"), - ("win32ts", "WtsApi32", 0x0501, "win32/src/win32tsmodule.cpp"), - ("_win32sysloader", "", 0x0501, "win32/src/_win32sysloader.cpp"), - ("win32transaction", "kernel32", 0x0501, "win32/src/win32transactionmodule.cpp"), + ("win32console", "kernel32", "win32/src/win32consolemodule.cpp"), + ("win32ts", "WtsApi32", "win32/src/win32tsmodule.cpp"), + ("_win32sysloader", "", "win32/src/_win32sysloader.cpp"), + ("win32transaction", "kernel32", "win32/src/win32transactionmodule.cpp"), ): - name, lib_names = info[:2] - windows_h_ver = sources = None - if len(info) > 2: - windows_h_ver = info[2] - if len(info) > 3: - sources = info[3].split() ext = WinExt_win32( name, - libraries=lib_names, + libraries=libraries, extra_compile_args=[], - windows_h_version=windows_h_ver, - sources=sources, + sources=sources.split(), ) win32_extensions.append(ext) @@ -1229,7 +1180,6 @@ def finalize_options(self): """.split(), libraries="advapi32 oleaut32", delay_load_libraries="wevtapi", - windows_h_version=0x0600, ), WinExt_win32( "win32api", @@ -1238,7 +1188,6 @@ def finalize_options(self): """.split(), libraries="user32 advapi32 shell32 version", delay_load_libraries="powrprof", - windows_h_version=0x0500, ), WinExt_win32( "win32gui", @@ -1246,7 +1195,6 @@ def finalize_options(self): win32/src/win32dynamicdialog.cpp win32/src/win32gui.i """.split(), - windows_h_version=0x0500, libraries="gdi32 user32 comdlg32 comctl32 shell32", define_macros=[("WIN32GUI", None)], ), @@ -1255,7 +1203,6 @@ def finalize_options(self): "_winxptheme", sources=["win32/src/_winxptheme.i"], libraries="gdi32 user32 comdlg32 comctl32 shell32 Uxtheme", - windows_h_version=0x0500, ), ] win32_extensions += [ @@ -1264,7 +1211,6 @@ def finalize_options(self): sources=["win32/src/PythonServiceMessages.mc", "win32/src/PythonService.cpp"], extra_compile_args=["-DPYSERVICE_BUILD_DLL"], libraries="user32 ole32 advapi32 shell32", - windows_h_version=0x500, ), ] @@ -1273,7 +1219,6 @@ def finalize_options(self): "win32help", sources=["win32/src/win32helpmodule.cpp"], libraries="htmlhelp user32 advapi32", - windows_h_version=0x500, ), ] @@ -1340,9 +1285,7 @@ def finalize_options(self): {win32com}/extensions/PyICancelMethodCalls.cpp {win32com}/extensions/PyIContext.cpp {win32com}/extensions/PyIEnumContextProps.cpp {win32com}/extensions/PyIClientSecurity.cpp {win32com}/extensions/PyIServerSecurity.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), depends=( """ @@ -1369,15 +1312,12 @@ def finalize_options(self): {win32com}/include\\PyICancelMethodCalls.h {win32com}/include\\PyIContext.h {win32com}/include\\PyIEnumContextProps.h {win32com}/include\\PyIClientSecurity.h {win32com}/include\\PyIServerSecurity.h - """.format( - **dirs - ) + """.format(**dirs) ).split(), libraries="oleaut32 ole32 user32 urlmon", export_symbol_file="com/win32com/src/PythonCOM.def", extra_compile_args=["-DBUILD_PYTHONCOM"], pch_header="stdafx.h", - windows_h_version=0x500, base_address=dll_base_address, ) dll_base_address += 0x80000 # pythoncom is large! @@ -1399,9 +1339,7 @@ def finalize_options(self): {adsi}/adsilib.i {adsi}/PyADSIUtil.cpp {adsi}/PyDSOPObjects.cpp {adsi}/PyIADs.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1419,9 +1357,7 @@ def finalize_options(self): {axcontrol}/PyIOleClientSite.cpp {axcontrol}/PyIOleInPlaceSite.cpp {axcontrol}/PyIOleObject.cpp {axcontrol}/PyIViewObject2.cpp {axcontrol}/PyIOleCommandTarget.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1429,27 +1365,23 @@ def finalize_options(self): sources=( """ {axscript}/AXScript.cpp - {axscript}/GUIDS.CPP {axscript}/PyGActiveScript.cpp + {axscript}/GUIDS.cpp {axscript}/PyGActiveScript.cpp {axscript}/PyGActiveScriptError.cpp {axscript}/PyGActiveScriptParse.cpp {axscript}/PyGActiveScriptSite.cpp {axscript}/PyGObjectSafety.cpp {axscript}/PyIActiveScript.cpp {axscript}/PyIActiveScriptError.cpp {axscript}/PyIActiveScriptParse.cpp {axscript}/PyIActiveScriptParseProcedure.cpp {axscript}/PyIActiveScriptSite.cpp {axscript}/PyIMultiInfos.cpp {axscript}/PyIObjectSafety.cpp {axscript}/stdafx.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), depends=( """ {axscript}/AXScript.h - {axscript}/guids.h {axscript}/PyGActiveScriptError.h + {axscript}/GUIDs.h {axscript}/PyGActiveScriptError.h {axscript}/PyIActiveScriptError.h {axscript}/PyIObjectSafety.h {axscript}/PyIProvideMultipleClassInfo.h {axscript}/stdafx.h - """.format( - **dirs - ) + """.format(**dirs) ).split(), extra_compile_args=["-DPY_BUILD_AXSCRIPT"], implib_name="axscript", @@ -1505,9 +1437,7 @@ def finalize_options(self): {axdebug}/PyIRemoteDebugApplicationEvents.cpp {axdebug}/PyIRemoteDebugApplicationThread.cpp {axdebug}/stdafx.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1520,9 +1450,7 @@ def finalize_options(self): {internet}/PyIInternetPriority.cpp {internet}/PyIInternetProtocol.cpp {internet}/PyIInternetProtocolInfo.cpp {internet}/PyIInternetProtocolRoot.cpp {internet}/PyIInternetProtocolSink.cpp {internet}/PyIInternetSecurityManager.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), depends=["{internet}/internet_pch.h".format(**dirs)], ), @@ -1558,9 +1486,7 @@ def finalize_options(self): {mapi}/mapiguids.cpp {mapi}/MAPIStubLibrary/library/mapiStubLibrary.cpp {mapi}/MAPIStubLibrary/library/stubutils.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com_mapi( @@ -1576,16 +1502,13 @@ def finalize_options(self): {mapi}/exchangeguids.cpp {mapi}/MAPIStubLibrary/library/mapiStubLibrary.cpp {mapi}/MAPIStubLibrary/library/stubutils.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( "shell", libraries="shell32", pch_header="shell_pch.h", - windows_h_version=0x600, sources=( """ {shell}/PyIActiveDesktop.cpp @@ -1660,9 +1583,7 @@ def finalize_options(self): {shell}/PyIUniformResourceLocator.cpp {shell}/shell.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1690,9 +1611,7 @@ def finalize_options(self): {propsys}/PyIObjectWithPropertyKey.cpp {propsys}/PyIPropertyChange.cpp {propsys}/PyIPropertyChangeArray.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), implib_name="pypropsys", ), @@ -1708,9 +1627,7 @@ def finalize_options(self): {taskscheduler}/PyITaskScheduler.cpp {taskscheduler}/PyITaskTrigger.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1731,9 +1648,7 @@ def finalize_options(self): {bits}/PyIEnumBackgroundCopyJobs.cpp {bits}/PyIEnumBackgroundCopyFiles.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), WinExt_win32com( @@ -1754,18 +1669,14 @@ def finalize_options(self): {directsound}/PyIDirectSoundBuffer.cpp {directsound}/PyIDirectSoundCapture.cpp {directsound}/PyIDirectSoundCaptureBuffer.cpp {directsound}/PyIDirectSoundNotify.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), depends=( """ {directsound}/directsound_pch.h {directsound}/PyIDirectSound.h {directsound}/PyIDirectSoundBuffer.h {directsound}/PyIDirectSoundCapture.h {directsound}/PyIDirectSoundCaptureBuffer.h {directsound}/PyIDirectSoundNotify.h - """.format( - **dirs - ) + """.format(**dirs) ).split(), optional_headers=["dsound.h"], libraries="user32 dsound dxguid", @@ -1777,9 +1688,7 @@ def finalize_options(self): """ {authorization}/authorization.cpp {authorization}/PyGSecurityInformation.cpp - """.format( - **dirs - ) + """.format(**dirs) ).split(), ), ] @@ -1908,7 +1817,6 @@ def finalize_options(self): "Pythonwin/win32uioledoc.h", ], pch_header="stdafxole.h", - windows_h_version=0x500, optional_headers=["afxres.h"], ), WinExt_pythonwin( @@ -2133,7 +2041,6 @@ def convert_optional_data_files(files): "build": my_build, "build_ext": my_build_ext, "install_data": my_install_data, - "install_lib": my_install_lib, } classifiers = [ @@ -2150,67 +2057,18 @@ def convert_optional_data_files(files): "Programming Language :: Python :: Implementation :: CPython", ] -# 3.10 stopped supporting bdist_wininst, but we can still build them with 3.9. -# This can be kept until Python 3.9 or exe installers support is dropped. -if "bdist_wininst" in sys.argv: - # fixup https://github.com/pypa/setuptools/issues/3284 - def maybe_fixup_exes(): - import site - - from distutils.command import bdist_wininst - - # setuptools can't find .exe stubs in `site-packages/setuptools/_distutils` - # but they might exist in the original `lib/distutils`. - expected_dir = os.path.dirname(bdist_wininst.__file__) - if not len(glob.glob(f"{expected_dir}/*.exe")): - # might die, see if we can not! - for maybe in site.getsitepackages(): - maybe_dir = os.path.abspath(f"{maybe}/../distutils/command") - if len(glob.glob(f"{maybe_dir}/*.exe")): - print(f"pointing setuptools at '{maybe_dir}'") - bdist_wininst.__file__ = os.path.join(maybe_dir, "bdist_wininst.py") - break - else: - print("can't fixup distutils/setuptools exe stub location, good luck!") - - maybe_fixup_exes() - - # It doesn't really make sense to put README.md as the long description, so - # keep it short and sweet as it's the first thing shown by the UI. - long_description = ( - "Python extensions for Microsoft Windows\n" - "Provides access to much of the Win32 API, the\n" - "ability to create and use COM objects, and the\n" - "Pythonwin environment." - ) - long_description_content_type = "text/plain" -else: - # For wheels, the readme makes more sense as pypi does something sane - # with it. - my_dir = os.path.abspath(os.path.dirname(__file__)) - with open(os.path.join(my_dir, "README.md")) as f: - long_description = f.read() - long_description_content_type = "text/markdown" - dist = setup( name="pywin32", - version=str(build_id), + version=build_id, description="Python for Window Extensions", - long_description=long_description, - long_description_content_type=long_description_content_type, + long_description=(Path(__file__).parent / "README.md").read_text(), + long_description_content_type="text/markdown", author="Mark Hammond (et al)", author_email="mhammond@skippinet.com.au", url="https://github.com/mhammond/pywin32", license="PSF", classifiers=classifiers, cmdclass=cmdclass, - options={ - "bdist_wininst": { - "install_script": "pywin32_postinstall.py", - "title": f"pywin32-{build_id}", - "user_access_control": "auto", - }, - }, scripts=["pywin32_postinstall.py", "pywin32_testall.py"], ext_modules=ext_modules, package_dir={ diff --git a/win32/Demos/EvtFormatMessage.py b/win32/Demos/EvtFormatMessage.py index ecd5075a78..3709e18ea5 100644 --- a/win32/Demos/EvtFormatMessage.py +++ b/win32/Demos/EvtFormatMessage.py @@ -76,7 +76,7 @@ def main(): # > UnicodeEncodeError: \'charmap\' codec can\'t encode character \'\\u200e\' in position 57: character maps to \r\n' # Can't reproduce when running manually, so it seems more a subprocess.Popen() # than ours: - print(" Failed to decode:", repr(message)) + print(f" Failed to decode: {message!r}") if __name__ == "__main__": diff --git a/win32/Demos/EvtSubscribe_push.py b/win32/Demos/EvtSubscribe_push.py index 519ef0d72c..fa4feb7290 100644 --- a/win32/Demos/EvtSubscribe_push.py +++ b/win32/Demos/EvtSubscribe_push.py @@ -1,4 +1,8 @@ ## Demonstrates a "push" subscription with a callback function +from __future__ import annotations + +from time import sleep + import win32evtlog query_text = '*[System[Provider[@Name="Microsoft-Windows-Winlogon"]]]' @@ -15,7 +19,7 @@ def c(reason, context, evt): return 0 -evttext = [] +evttext: list[str] = [] s = win32evtlog.EvtSubscribe( "System", win32evtlog.EvtSubscribeStartAtOldestRecord, @@ -23,3 +27,6 @@ def c(reason, context, evt): Callback=c, Context=evttext, ) + +sleep(0.001) +print("\n".join(evttext)) diff --git a/win32/Demos/GetSaveFileName.py b/win32/Demos/GetSaveFileName.py index bff34dcdd3..2cbb657952 100644 --- a/win32/Demos/GetSaveFileName.py +++ b/win32/Demos/GetSaveFileName.py @@ -17,9 +17,9 @@ FilterIndex=1, ) -print("save file names:", repr(fname)) -print("filter used:", repr(customfilter)) -print("Flags:", flags) +print(f"save file names: {fname!r}") +print(f"filter used: {customfilter!r}") +print(f"Flags: {flags}") for k, v in win32con.__dict__.items(): if k.startswith("OFN_") and flags & v: print("\t" + k) @@ -35,9 +35,9 @@ FilterIndex=0, ) -print("open file names:", repr(fname)) -print("filter used:", repr(customfilter)) -print("Flags:", flags) +print(f"open file names: {fname!r}") +print(f"filter used: {customfilter!r}") +print(f"Flags: {flags}") for k, v in win32con.__dict__.items(): if k.startswith("OFN_") and flags & v: print("\t" + k) diff --git a/win32/Demos/c_extension/setup.py b/win32/Demos/c_extension/setup.py index 4ffacbba72..4ee8c396a7 100644 --- a/win32/Demos/c_extension/setup.py +++ b/win32/Demos/c_extension/setup.py @@ -1,7 +1,7 @@ # A sample distutils script to show to build your own # extension module which extends pywintypes or pythoncom. # -# Use 'python setup.py build' to build this extension. +# Use 'python -m build' to build this extension. import os from setuptools import Extension, setup from sysconfig import get_paths diff --git a/win32/Demos/dde/ddeclient.py b/win32/Demos/dde/ddeclient.py index f140e2438b..6e63c4d6fa 100644 --- a/win32/Demos/dde/ddeclient.py +++ b/win32/Demos/dde/ddeclient.py @@ -1,7 +1,7 @@ # 'Request' example added jjk 11/20/98 +import win32ui # isort: skip # Must be imported before dde ! import dde -import win32ui server = dde.CreateServer() server.Create("TestClient") diff --git a/win32/Demos/dde/ddeserver.py b/win32/Demos/dde/ddeserver.py index 0374827f01..57924aba64 100644 --- a/win32/Demos/dde/ddeserver.py +++ b/win32/Demos/dde/ddeserver.py @@ -1,7 +1,7 @@ # 'Request' example added jjk 11/20/98 +import win32ui # isort: skip # Must be imported before dde ! import dde -import win32ui from pywin.mfc import object diff --git a/win32/Demos/eventLogDemo.py b/win32/Demos/eventLogDemo.py index 1e327a80e0..918e4e0816 100644 --- a/win32/Demos/eventLogDemo.py +++ b/win32/Demos/eventLogDemo.py @@ -36,7 +36,9 @@ def ReadLog(computer, logType="Application", dumpEachRecord=0): user_desc = None if dumpEachRecord: print( - f"Event record from {object.SourceName!r} generated at {object.TimeGenerated.Format()}" + "Event record from {!r} generated at {}".format( + object.SourceName, object.TimeGenerated.Format() + ) ) if user_desc: print(user_desc) diff --git a/win32/Demos/getfilever.py b/win32/Demos/getfilever.py index 402a7bc436..fa405cf92c 100644 --- a/win32/Demos/getfilever.py +++ b/win32/Demos/getfilever.py @@ -26,7 +26,7 @@ ## \VarFileInfo\Translation returns list of available (language, codepage) pairs that can be used to retreive string info ## any other must be of the form \StringfileInfo\%04X%04X\parm_name, middle two are language/codepage pair returned from above for lang, codepage in pairs: - print("lang: ", lang, "codepage:", codepage) + print("lang:", lang, "codepage:", codepage) for ver_string in ver_strings: str_info = f"\\StringFileInfo\\{lang:04X}{codepage:04X}\\{ver_string}" # print(str_inf) diff --git a/win32/Demos/pipes/runproc.py b/win32/Demos/pipes/runproc.py index 2ed02dd3da..c3f3cb211b 100644 --- a/win32/Demos/pipes/runproc.py +++ b/win32/Demos/pipes/runproc.py @@ -100,10 +100,10 @@ def run(self, cmdline): self.stdin.close() self.stdout = os.fdopen(msvcrt.open_osfhandle(self.hStdout_r, 0), "rb") - print("Read on stdout: ", repr(self.stdout.read())) + print(f"Read on stdout: {self.stdout.read()!r}") self.stderr = os.fdopen(msvcrt.open_osfhandle(self.hStderr_r, 0), "rb") - print("Read on stderr: ", repr(self.stderr.read())) + print(f"Read on stderr: {self.stderr.read()!r}") if __name__ == "__main__": diff --git a/win32/Demos/security/GetTokenInformation.py b/win32/Demos/security/GetTokenInformation.py index 192c549e1b..7553a2c606 100644 --- a/win32/Demos/security/GetTokenInformation.py +++ b/win32/Demos/security/GetTokenInformation.py @@ -1,5 +1,5 @@ -""" Lists various types of information about current user's access token, - including UAC status on Vista +"""Lists various types of information about current user's access token, +including UAC status on Vista """ import pywintypes @@ -40,7 +40,7 @@ def dump_token(th): flag_names, unk = TOKEN_PRIVILEGE_ATTRIBUTES.lookup_flags(priv_flags) flag_desc = " ".join(flag_names) if unk: - flag_desc += "(" + str(unk) + ")" + flag_desc += f"({unk})" priv_name = win32security.LookupPrivilegeName("", priv_luid) priv_desc = win32security.LookupPrivilegeDisplayName("", priv_name) @@ -52,7 +52,7 @@ def dump_token(th): flag_names, unk = TOKEN_GROUP_ATTRIBUTES.lookup_flags(group_attr) flag_desc = " ".join(flag_names) if unk: - flag_desc += "(" + str(unk) + ")" + flag_desc += f"({unk})" if group_attr & TOKEN_GROUP_ATTRIBUTES.SE_GROUP_LOGON_ID: sid_desc = "Logon sid" else: diff --git a/win32/Demos/security/set_file_audit.py b/win32/Demos/security/set_file_audit.py index 324d72748d..e46d05d770 100644 --- a/win32/Demos/security/set_file_audit.py +++ b/win32/Demos/security/set_file_audit.py @@ -59,7 +59,7 @@ win32con.GENERIC_ALL, my_sid, ) -## keep dir from inheriting any permissions so it only has ACEs explicitely set here +## keep dir from inheriting any permissions so it only has ACEs explicitly set here win32security.SetNamedSecurityInfo( dir_name, SE_FILE_OBJECT, diff --git a/win32/Demos/security/sspi/simple_auth.py b/win32/Demos/security/sspi/simple_auth.py index 552e9dc59c..20610aac96 100644 --- a/win32/Demos/security/sspi/simple_auth.py +++ b/win32/Demos/security/sspi/simple_auth.py @@ -67,6 +67,6 @@ def lookup_ret_code(err): encbuf.append(win32security.PySecBufferType(trailersize, sspicon.SECBUFFER_TOKEN)) encbuf[0].Buffer = msg sspiclient.ctxt.EncryptMessage(0, encbuf, 1) -print("Encrypted data:", repr(encbuf[0].Buffer)) +print(f"Encrypted data: {encbuf[0].Buffer!r}") sspiserver.ctxt.DecryptMessage(encbuf, 1) -print("Unencrypted data:", encbuf[0].Buffer) +print(f"Encrypted data: {encbuf[0].Buffer}") diff --git a/win32/Demos/security/sspi/socket_server.py b/win32/Demos/security/sspi/socket_server.py index 09f005b46f..3d14fee221 100644 --- a/win32/Demos/security/sspi/socket_server.py +++ b/win32/Demos/security/sspi/socket_server.py @@ -96,7 +96,7 @@ def process_request(self, request, client_address): if data is None or key is None: break data = self.sa.decrypt(data, key) - print("Client sent:", repr(data)) + print(f"Client sent: {data!r}") finally: self.sa.ctxt.RevertSecurityContext() self.close_request(request) diff --git a/win32/Demos/win32ts_logoff_disconnected.py b/win32/Demos/win32ts_logoff_disconnected.py index 2a8bcc9403..3b7f882e07 100644 --- a/win32/Demos/win32ts_logoff_disconnected.py +++ b/win32/Demos/win32ts_logoff_disconnected.py @@ -1,4 +1,4 @@ -""" Finds any disconnected terminal service sessions and logs them off""" +"""Finds any disconnected terminal service sessions and logs them off""" import pywintypes import win32ts diff --git a/win32/Demos/win32wnet/testwnet.py b/win32/Demos/win32wnet/testwnet.py index d13917cf2f..3d6fbfc959 100644 --- a/win32/Demos/win32wnet/testwnet.py +++ b/win32/Demos/win32wnet/testwnet.py @@ -85,7 +85,9 @@ def TestConnection(): fname = os.path.join(localName + "\\", os.listdir(localName + "\\")[0]) try: print( - f"Universal name of '{fname}' is '{win32wnet.WNetGetUniversalName(fname)}'" + "Universal name of '{}' is '{}'".format( + fname, win32wnet.WNetGetUniversalName(fname) + ) ) except win32wnet.error as details: print(f"Couldn't get universal name of '{fname}': {details.strerror}") @@ -111,7 +113,7 @@ def TestConnection(): def TestGetUser(): u = win32wnet.WNetGetUser() - print("Current global user is", repr(u)) + print(f"Current global user is {u!r}") if u != win32wnet.WNetGetUser(None): raise RuntimeError("Default value didn't seem to work!") diff --git a/win32/Lib/commctrl.py b/win32/Lib/commctrl.py index 26641e8452..452fe62ef0 100644 --- a/win32/Lib/commctrl.py +++ b/win32/Lib/commctrl.py @@ -1,4 +1,4 @@ -# Generated by h2py from COMMCTRL.H +# Generated by h2py from CommCtrl.h WM_USER = 1024 ICC_LISTVIEW_CLASSES = 1 # listview, header ICC_TREEVIEW_CLASSES = 2 # treeview, tooltips diff --git a/win32/Lib/pywin32_testutil.py b/win32/Lib/pywin32_testutil.py index d9e5179136..e2b1b8b3ab 100644 --- a/win32/Lib/pywin32_testutil.py +++ b/win32/Lib/pywin32_testutil.py @@ -273,7 +273,7 @@ def _makeResult(self): return TestResult(self.stream, self.descriptions, self.verbosity) -# TestProgream subclass necessary just to get our TestRunner hooked up, +# TestProgram subclass necessary just to get our TestRunner hooked up, # which is necessary to get our TestResult hooked up *sob* class TestProgram(unittest.TestProgram): def runTests(self): @@ -282,7 +282,7 @@ def runTests(self): unittest.TestProgram.runTests(self) -# A convenient entry-point - if used, 'SKIPPED' exceptions will be supressed. +# A convenient entry-point - if used, 'SKIPPED' exceptions will be suppressed. def testmain(*args, **kw): new_kw = kw.copy() if "testLoader" not in new_kw: diff --git a/win32/Lib/pywintypes.py b/win32/Lib/pywintypes.py index 14ae04b682..36259df934 100644 --- a/win32/Lib/pywintypes.py +++ b/win32/Lib/pywintypes.py @@ -83,7 +83,7 @@ def __import_pywin32_system_module__(modname, globs): # There are 2 site-packages directories - one "global" and one "user". # We could be in either, or both (but with different versions!). Factors include - # virtualenvs, post-install script being run or not, `setup.py install` flags, etc. + # virtualenvs, post-install script being run or not, `pip install` flags, etc. # In a worst-case, it means, say 'python -c "import win32api"' # will not work but 'python -c "import pywintypes, win32api"' will, diff --git a/win32/Lib/regutil.py b/win32/Lib/regutil.py index cf3ab67f8e..5a72bc7aac 100644 --- a/win32/Lib/regutil.py +++ b/win32/Lib/regutil.py @@ -49,7 +49,7 @@ def SetRegistryDefaultValue(subKey, value, rootkey=None): elif isinstance(value, int): typeId = win32con.REG_DWORD else: - raise TypeError("Value must be string or integer - was passed " + repr(value)) + raise TypeError(f"Value must be string or integer - was passed {value!r}") win32api.RegSetValue(rootkey, subKey, typeId, value) diff --git a/win32/Lib/win32con.py b/win32/Lib/win32con.py index 5e798ee293..cc22e72db6 100644 --- a/win32/Lib/win32con.py +++ b/win32/Lib/win32con.py @@ -4197,6 +4197,7 @@ def GetBValue(rgb): MOD_CONTROL = 2 MOD_SHIFT = 4 MOD_WIN = 8 +MOD_NOREPEAT = 16384 IDHOT_SNAPWINDOW = -1 IDHOT_SNAPDESKTOP = -2 # EW_RESTARTWINDOWS = 0x0042 diff --git a/win32/Lib/win32cryptcon.py b/win32/Lib/win32cryptcon.py index 8d71996a08..92aac96ebc 100644 --- a/win32/Lib/win32cryptcon.py +++ b/win32/Lib/win32cryptcon.py @@ -972,7 +972,7 @@ def GET_CMSG_ENCODING_TYPE(X): CMC_FAIL_BAD_REQUEST = 2 CMC_FAIL_BAD_TIME = 3 CMC_FAIL_BAD_CERT_ID = 4 -CMC_FAIL_UNSUPORTED_EXT = 5 +CMC_FAIL_UNSUPORTED_EXT = 5 # Yes Microsoft made a typo in "UNSUPPORTED" CMC_FAIL_MUST_ARCHIVE_KEYS = 6 CMC_FAIL_BAD_IDENTITY = 7 CMC_FAIL_POP_REQUIRED = 8 diff --git a/win32/Lib/win32evtlogutil.py b/win32/Lib/win32evtlogutil.py index bf294905da..58d3326ef5 100644 --- a/win32/Lib/win32evtlogutil.py +++ b/win32/Lib/win32evtlogutil.py @@ -1,5 +1,4 @@ -"""Event Log Utilities - helper for win32evtlog.pyd -""" +"""Event Log Utilities - helper for win32evtlog.pyd""" import win32api import win32con @@ -145,7 +144,10 @@ 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 = f"SYSTEM\\CurrentControlSet\\Services\\EventLog\\{logType}\\{eventLogRecord.SourceName}" + keyName = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\{}\\{}".format( + logType, + eventLogRecord.SourceName, + ) # Now open this key and get the EventMessageFile value, which is # the name of the message DLL. diff --git a/win32/Lib/win32gui_struct.py b/win32/Lib/win32gui_struct.py index 41ef815fdb..5651c7bc83 100644 --- a/win32/Lib/win32gui_struct.py +++ b/win32/Lib/win32gui_struct.py @@ -463,7 +463,7 @@ def EmptyTVITEM(hitem, mask=None, text_buf_size=512): else: text_addr = text_buf_size = 0 buf = struct.pack( - _tvitem_fmt, mask, hitem, 0, 0, text_addr, text_buf_size, 0, 0, 0, 0 # text + _tvitem_fmt, mask, hitem, 0, 0, text_addr, text_buf_size, 0, 0, 0, 0 ) return array.array("b", buf), extra @@ -758,7 +758,7 @@ def PackLVCOLUMN(fmt=None, cx=None, text=None, subItem=None, image=None, order=N text_addr, _ = text_buffer.buffer_info() text_len = len(text) buf = struct.pack( - _lvcolumn_fmt, mask, fmt, cx, text_addr, text_len, subItem, image, order # text + _lvcolumn_fmt, mask, fmt, cx, text_addr, text_len, subItem, image, order ) return array.array("b", buf), extra @@ -808,9 +808,7 @@ def EmptyLVCOLUMN(mask=None, text_buf_size=512): text_addr, _ = text_buffer.buffer_info() else: text_addr = text_buf_size = 0 - buf = struct.pack( - _lvcolumn_fmt, mask, 0, 0, text_addr, text_buf_size, 0, 0, 0 # text - ) + buf = struct.pack(_lvcolumn_fmt, mask, 0, 0, text_addr, text_buf_size, 0, 0, 0) return array.array("b", buf), extra diff --git a/win32/Lib/win32pdhquery.py b/win32/Lib/win32pdhquery.py index 3f458e0a88..301b85c163 100644 --- a/win32/Lib/win32pdhquery.py +++ b/win32/Lib/win32pdhquery.py @@ -331,9 +331,8 @@ def collectdataslave(self, format=win32pdh.PDH_FMT_LONG): if not ok: temp.append(-1) # a better way to signal failure??? return temp - except ( - win32api.error - ): # will happen if, for instance, no counters are part of the query and we attempt to collect data for it. + # will happen if, for instance, no counters are part of the query and we attempt to collect data for it. + except win32api.error: return [-1] * len(self.counters) # pickle functions @@ -505,10 +504,10 @@ def collectdatafor(self, totalperiod, period=1): def collectdatawhile(self, period=1): """ Threaded collection of performance data: - This method sets up a simple semaphor system for signalling + This method sets up a simple semaphore system for signalling when you would like to start and stop a threaded data collection method. The collection runs every period seconds until the - semaphor attribute is set to a non-true value (which normally + semaphore attribute is set to a non-true value (which normally should be done by calling query.collectdatawhile_stop() .) e.g.: query.collectdatawhile(2) @@ -561,11 +560,11 @@ def __setstate__(self, volatilecounters): self.volatilecounters = volatilecounters -class QueryError: - def __init__(self, query): +class QueryError(Exception): + def __init__(self, query: BaseQuery): self.query = query def __repr__(self): - return "" % repr(self.query) + return f"" __str__ = __repr__ diff --git a/win32/Lib/win32rcparser.py b/win32/Lib/win32rcparser.py index b87bd96feb..183f075b1c 100644 --- a/win32/Lib/win32rcparser.py +++ b/win32/Lib/win32rcparser.py @@ -7,6 +7,7 @@ This is a parser for Windows .rc files, which are text files which define dialogs and other Windows UI resources. """ + from __future__ import annotations import os diff --git a/win32/Lib/win32timezone.py b/win32/Lib/win32timezone.py index fdd71c8557..13a3f6cc05 100644 --- a/win32/Lib/win32timezone.py +++ b/win32/Lib/win32timezone.py @@ -463,7 +463,7 @@ def _locate_day(year, cutoff): """ # MS stores Sunday as 0, Python datetime stores Monday as zero target_weekday = (cutoff.day_of_week + 6) % 7 - # For SYSTEMTIMEs relating to time zone inforamtion, cutoff.day + # For SYSTEMTIMEs relating to time zone information, cutoff.day # is the week of the month week_of_month = cutoff.day # so the following is the first day of that week @@ -632,7 +632,7 @@ def _LoadDynamicInfoFromKey(self, key): ) def __repr__(self): - result = f"{self.__class__.__name__}({repr(self.timeZoneName)}" + result = f"{self.__class__.__name__}({self.timeZoneName!r}" if self.fixedStandardTime: result += ", True" result += ")" diff --git a/win32/scripts/VersionStamp/vssutil.py b/win32/scripts/VersionStamp/vssutil.py index b4c8f3f58d..9518f51f65 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -88,7 +88,12 @@ def VssLog(project, linePrefix="", noLabels=5, maxItems=150): if i.Comment: commentDesc = f"\n{linePrefix}\t{i.Comment}" lines.append( - f"{linePrefix}{time.asctime(time.localtime(int(i.Date)))}\t{itemDesc}{commentDesc}" + "{}{}\t{}{}".format( + linePrefix, + time.asctime(time.localtime(int(i.Date))), + itemDesc, + commentDesc, + ) ) if labelNum > noLabels: break diff --git a/win32/scripts/h2py.py b/win32/scripts/h2py.py new file mode 100644 index 0000000000..50b54a92df --- /dev/null +++ b/win32/scripts/h2py.py @@ -0,0 +1,186 @@ +#! /usr/bin/env python3 +""" +Vendored from https://github.com/python/cpython/blob/3.8/Tools/scripts/h2py.py +Minimal changes to satisfy our checkers. + +--- + +Read #define's and translate to Python code. +Handle #include statements. +Handle #define macros with one argument. +Anything that isn't recognized or doesn't translate into valid +Python is ignored. + +Without filename arguments, acts as a filter. +If one or more filenames are given, output is written to corresponding +filenames in the local directory, translated to all uppercase, with +the extension replaced by ".py". + +By passing one or more options of the form "-i regular_expression" +you can specify additional strings to be ignored. This is useful +e.g. to ignore casts to u_long: simply specify "-i '(u_long)'". +""" + +# XXX To do: +# - turn trailing C comments into Python comments +# - turn C Boolean operators "&& || !" into Python "and or not" +# - what to do about #if(def)? +# - what to do about macros with multiple parameters? +from __future__ import annotations + +import getopt +import os +import re +import sys + +p_define = re.compile(r"^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]+") + +p_macro = re.compile( + r"^[\t ]*#[\t ]*define[\t ]+" r"([a-zA-Z0-9_]+)\(([_a-zA-Z][_a-zA-Z0-9]*)\)[\t ]+" +) + +p_include = re.compile(r"^[\t ]*#[\t ]*include[\t ]+<([^>\n]+)>") + +p_comment = re.compile(r"/\*([^*]+|\*+[^/])*(\*+/)?") +p_cpp_comment = re.compile("//.*") + +ignores = [p_comment, p_cpp_comment] + +p_char = re.compile(r"'(\\.[^\\]*|[^\\])'") + +p_hex = re.compile(r"0x([0-9a-fA-F]+)L?") + +filedict: dict[str, None] = {} +importable: dict[str, str] = {} + +try: + searchdirs = os.environ["include"].split(";") +except KeyError: + try: + searchdirs = os.environ["INCLUDE"].split(";") + except KeyError: + searchdirs = ["/usr/include"] + try: + searchdirs.insert(0, os.path.join("/usr/include", os.environ["MULTIARCH"])) + except KeyError: + pass + + +def main(): + global filedict + opts, args = getopt.getopt(sys.argv[1:], "i:") + for o, a in opts: + if o == "-i": + ignores.append(re.compile(a)) + if not args: + args = ["-"] + for filename in args: + if filename == "-": + sys.stdout.write("# Generated by h2py from stdin\n") + process(sys.stdin, sys.stdout) + else: + with open(filename) as fp: + outfile = os.path.basename(filename) + i = outfile.rfind(".") + if i > 0: + outfile = outfile[:i] + modname = outfile.upper() + outfile = modname + ".py" + with open(outfile, "w") as outfp: + outfp.write("# Generated by h2py from %s\n" % filename) + filedict = {} + for dir in searchdirs: + if filename[: len(dir)] == dir: + filedict[filename[len(dir) + 1 :]] = None # no '/' trailing + importable[filename[len(dir) + 1 :]] = modname + break + process(fp, outfp) + + +def pytify(body): + # replace ignored patterns by spaces + for p in ignores: + body = p.sub(" ", body) + # replace char literals by ord(...) + body = p_char.sub("ord('\\1')", body) + # Compute negative hexadecimal constants + start = 0 + UMAX = 2 * (sys.maxsize + 1) + while 1: + m = p_hex.search(body, start) + if not m: + break + s, e = m.span() + val = int(body[slice(*m.span(1))], 16) + if val > sys.maxsize: + val -= UMAX + body = body[:s] + "(" + str(val) + ")" + body[e:] + start = s + 1 + return body + + +def process(fp, outfp, env={}): + lineno = 0 + while 1: + line = fp.readline() + if not line: + break + lineno = lineno + 1 + match = p_define.match(line) + if match: + # gobble up continuation lines + while line[-2:] == "\\\n": + nextline = fp.readline() + if not nextline: + break + lineno = lineno + 1 + line = line + nextline + name = match.group(1) + body = line[match.end() :] + body = pytify(body) + ok = 0 + stmt = "%s = %s\n" % (name, body.strip()) + try: + exec(stmt, env) + except: + sys.stderr.write("Skipping: %s" % stmt) + else: + outfp.write(stmt) + match = p_macro.match(line) + if match: + macro, arg = match.group(1, 2) + body = line[match.end() :] + body = pytify(body) + stmt = "def %s(%s): return %s\n" % (macro, arg, body) + try: + exec(stmt, env) + except: + sys.stderr.write("Skipping: %s" % stmt) + else: + outfp.write(stmt) + match = p_include.match(line) + if match: + regs = match.regs + a, b = regs[1] + filename = line[a:b] + if filename in importable: + outfp.write("from %s import *\n" % importable[filename]) + elif filename not in filedict: + filedict[filename] = None + inclfp = None + for dir in searchdirs: + try: + inclfp = open(dir + "/" + filename) + break + except IOError: + pass + if inclfp: + with inclfp: + outfp.write("\n# Included from %s\n" % filename) + process(inclfp, outfp, env) + else: + sys.stderr.write("Warning - could not find file %s\n" % filename) + + +if __name__ == "__main__": + main() diff --git a/win32/scripts/regsetup.py b/win32/scripts/regsetup.py index da2f870e1d..ca44ed672b 100644 --- a/win32/scripts/regsetup.py +++ b/win32/scripts/regsetup.py @@ -447,8 +447,7 @@ def RegisterShellInfo(searchPaths): # FindRegisterApp("win32", ["win32con.pyc", "win32api%s.pyd" % suffix], searchPaths) -usage = ( - """\ +usage = """\ regsetup.py - Setup/maintain the registry for Python apps. Run without options, (but possibly search paths) to repair a totally broken @@ -475,9 +474,7 @@ def RegisterShellInfo(searchPaths): --description -- Print a description of the usage. --examples -- Print examples of usage. -""" - % sys.argv[0] -) +""" % sys.argv[0] description = """\ If no options are processed, the program attempts to validate and set @@ -500,9 +497,9 @@ def RegisterShellInfo(searchPaths): # Using raw string so that all paths meant to be copied read correctly inline and when printed examples = r""" Examples: -"regsetup c:\wierd\spot\1 c:\wierd\spot\2" +"regsetup c:\weird\spot\1 c:\weird\spot\2" Attempts to setup the core Python. Looks in some standard places, -as well as the 2 wierd spots to locate the core Python files (eg, Python.exe, +as well as the 2 weird spots to locate the core Python files (eg, Python.exe, pythonXX.dll, the standard library and Win32 Extensions). "regsetup -a myappname . .\subdir" diff --git a/win32/scripts/setup_d.py b/win32/scripts/setup_d.py index b723402839..6fcb730d93 100644 --- a/win32/scripts/setup_d.py +++ b/win32/scripts/setup_d.py @@ -50,7 +50,9 @@ def _docopy(src, dest): if not os.path.isfile(src): src = os.path.join(os.path.split(sys.argv[0])[0], src) print( - f"Can not find {os.path.abspath(orig_src)} or {os.path.abspath(src)} to copy" + "Can not find {} or {} to copy".format( + os.path.abspath(orig_src), os.path.abspath(src) + ) ) return 0 try: @@ -59,7 +61,7 @@ def _docopy(src, dest): return 1 except: print(f"Error copying '{src}' -> '{dest}'") - print(str(sys.exc_info()[1])) + print(sys.exc_info()[1]) usage_and_die(3) @@ -78,7 +80,9 @@ def _doregister(mod_name, dll_name): ) except winreg.error: print( - f"Could not find the existing '{mod_name}' module registered in the registry" + "Could not find the existing '{}' module registered in the registry".format( + mod_name + ) ) usage_and_die(4) # Create the debug key. diff --git a/win32/test/handles.py b/win32/test/handles.py index 01b7f17ef9..9e4f633581 100644 --- a/win32/test/handles.py +++ b/win32/test/handles.py @@ -5,6 +5,14 @@ import win32api +class TestError1(Exception): + pass + + +class TestError2(Exception): + pass + + # A class that will never die vie refcounting, but will die via GC. class Cycle: def __init__(self, handle): @@ -21,7 +29,7 @@ def f1(invalidate): h = win32event.CreateEvent(None, 0, 0, None) if invalidate: win32api.CloseHandle(int(h)) - 1 / 0 + raise TestError1 # If we invalidated, then the object destruction code will attempt # to close an invalid handle. We don't wan't an exception in # this case @@ -30,13 +38,13 @@ def f2(invalidate): """This function should throw an OSError.""" try: f1(invalidate) - except ZeroDivisionError as exc: - raise OSError("raise 2") + except TestError1: + raise TestError2 - self.assertRaises(OSError, f2, False) + self.assertRaises(TestError2, f2, False) # Now do it again, but so the auto object destruction # actually fails. - self.assertRaises(OSError, f2, True) + self.assertRaises(TestError2, f2, True) def testCleanup2(self): # Cause an exception during object destruction. diff --git a/win32/test/test_odbc.py b/win32/test/test_odbc.py index 30b1ce8210..7b61cb354d 100644 --- a/win32/test/test_odbc.py +++ b/win32/test/test_odbc.py @@ -43,7 +43,11 @@ def setUp(self): newdb.Close() - conn_str = f"Driver={{Microsoft Access Driver (*.mdb)}};dbq={self.db_filename};Uid=;Pwd=;" + conn_str = ( + "Driver={{Microsoft Access Driver (*.mdb)}};dbq={};Uid=;Pwd=;".format( + self.db_filename, + ) + ) # 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_win32api.py b/win32/test/test_win32api.py index 446315f54f..887ff2a36f 100644 --- a/win32/test/test_win32api.py +++ b/win32/test/test_win32api.py @@ -14,6 +14,10 @@ from pywin32_testutil import TestSkipped +class TestError(Exception): + pass + + class CurrentUserTestCase(unittest.TestCase): def testGetCurrentUser(self): domain = win32api.GetDomainName() @@ -63,7 +67,7 @@ def test1(self): # This used to leave a stale exception behind. def reg_operation(): hkey = win32api.RegCreateKey(win32con.HKEY_CURRENT_USER, self.key_name) - x = 3 / 0 # or a statement like: raise Exception + raise TestError # do the test try: @@ -71,10 +75,10 @@ def reg_operation(): try: reg_operation() except: - 1 / 0 # Force exception + raise TestError # Force a TestError finally: win32api.RegDeleteKey(win32con.HKEY_CURRENT_USER, self.key_name) - except ZeroDivisionError: + except TestError: pass def testValues(self): diff --git a/win32/test/test_win32clipboard.py b/win32/test/test_win32clipboard.py index f5d5c28d14..ccfc32e531 100644 --- a/win32/test/test_win32clipboard.py +++ b/win32/test/test_win32clipboard.py @@ -5,7 +5,6 @@ class TestGetSetClipboardData(unittest.TestCase): - def copyData(self, data, format_): win32clipboard.OpenClipboard() ret = None @@ -30,13 +29,13 @@ def test_data(self): test_data = { "Dummy str": win32clipboard.CF_UNICODETEXT, b"Dummy bytes text": win32clipboard.CF_TEXT, - b"Dummy\x00\xFF bytes": win32clipboard.CF_DIB, + b"Dummy\x00\xff bytes": win32clipboard.CF_DIB, } for data, fmt in test_data.items(): self.assertEqual(data, self.copyData(data, fmt)) test_data = { "Dummy str": (win32clipboard.CF_TEXT, win32clipboard.CF_DIB), - b"Dummy\x00\xFF bytes": (win32clipboard.CF_UNICODETEXT,), + b"Dummy\x00\xff bytes": (win32clipboard.CF_UNICODETEXT,), } for data, formats in test_data.items(): for fmt in formats: diff --git a/win32/test/test_win32cred.py b/win32/test/test_win32cred.py index c44fe18b85..4b9fe08d75 100644 --- a/win32/test/test_win32cred.py +++ b/win32/test/test_win32cred.py @@ -5,7 +5,6 @@ class TestCredFunctions(unittest.TestCase): - def setUp(self): self.flags = 0 self.dummy_cred = { diff --git a/win32/test/test_win32file.py b/win32/test/test_win32file.py index 4763f9289b..12ba8c31d9 100644 --- a/win32/test/test_win32file.py +++ b/win32/test/test_win32file.py @@ -641,7 +641,10 @@ def _watcherThread(self, dn, dh, changes): try: print("waiting", dh) changes = win32file.ReadDirectoryChangesW( - dh, 8192, False, flags # sub-tree + dh, + 8192, + False, # sub-tree + flags, ) print("got", changes) except: @@ -655,7 +658,11 @@ def _watcherThreadOverlapped(self, dn, dh, changes): overlapped.hEvent = win32event.CreateEvent(None, 0, 0, None) while 1: win32file.ReadDirectoryChangesW( - dh, buf, False, flags, overlapped # sub-tree + dh, + buf, + False, # sub-tree + flags, + overlapped, ) # Wait for our event, or for 5 seconds. rc = win32event.WaitForSingleObject(overlapped.hEvent, 5000) diff --git a/win32/test/test_win32trace.py b/win32/test/test_win32trace.py index c74a31605c..8cd79dbf3a 100644 --- a/win32/test/test_win32trace.py +++ b/win32/test/test_win32trace.py @@ -258,7 +258,9 @@ def __init__(self, threadCount): def start(self): procHandle, threadHandle, procId, threadId = win32process.CreateProcess( None, # appName - f'python.exe "{this_file}" /run_test_process {self.BucketCount} {self.threadCount}', + 'python.exe "{}" /run_test_process {} {}'.format( + this_file, self.BucketCount, self.threadCount + ), None, # process security None, # thread security 0, # inherit handles From 338089a8ad3baeacd7b07303c91ddb31d965fa2d Mon Sep 17 00:00:00 2001 From: Avasam Date: Sat, 14 Dec 2024 13:32:58 -0500 Subject: [PATCH 3/3] Run ruff check --fix && ruff 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/framework/sgrepmdi.py | 9 +- Pythonwin/pywin/scintilla/view.py | 9 +- Pythonwin/pywin/tools/hierlist.py | 4 +- Pythonwin/pywin/tools/regedit.py | 6 +- com/win32com/client/build.py | 54 ++------- com/win32com/client/dynamic.py | 8 +- com/win32com/client/gencache.py | 18 +-- com/win32com/client/genpy.py | 15 +-- com/win32com/client/makepy.py | 8 +- com/win32com/client/tlbrowse.py | 4 +- com/win32com/makegw/makegw.py | 52 ++------ com/win32com/makegw/makegwparse.py | 112 ++++-------------- com/win32com/server/dispatcher.py | 8 +- com/win32com/server/register.py | 4 +- com/win32com/test/testDCOM.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 +- 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 +- 34 files changed, 97 insertions(+), 338 deletions(-) diff --git a/Pythonwin/pywin/framework/app.py b/Pythonwin/pywin/framework/app.py index 931a007871..21d5baf81e 100644 --- a/Pythonwin/pywin/framework/app.py +++ b/Pythonwin/pywin/framework/app.py @@ -343,9 +343,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) import sysconfig diff --git a/Pythonwin/pywin/framework/editor/document.py b/Pythonwin/pywin/framework/editor/document.py index 1579dbfe62..2fba319452 100644 --- a/Pythonwin/pywin/framework/editor/document.py +++ b/Pythonwin/pywin/framework/editor/document.py @@ -157,17 +157,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 c26bf6e829..195a59a3b7 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 7d0ef2d289..2754cd3dac 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/framework/sgrepmdi.py b/Pythonwin/pywin/framework/sgrepmdi.py index 7635005b82..71413aacf7 100644 --- a/Pythonwin/pywin/framework/sgrepmdi.py +++ b/Pythonwin/pywin/framework/sgrepmdi.py @@ -325,14 +325,7 @@ def SearchFile(self, handler, count): return 1 def GetParams(self): - return "{}\t{}\t{}\t{!r}\t{!r}\t{!r}".format( - self.dirpattern, - self.filpattern, - self.greppattern, - self.casesensitive, - self.recurse, - self.verbose, - ) + return f"{self.dirpattern}\t{self.filpattern}\t{self.greppattern}\t{self.casesensitive!r}\t{self.recurse!r}\t{self.verbose!r}" def OnSaveDocument(self, filename): # print("OnSaveDocument() filename=", filename) diff --git a/Pythonwin/pywin/scintilla/view.py b/Pythonwin/pywin/scintilla/view.py index b1beb6f156..7496e4d765 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()) @@ -824,9 +822,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 1e4f8d7682..0f06b8c0e5 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 d8f854ff45..70a6aaac79 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 4b7628438e..dfe81b5bad 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 @@ -404,58 +404,24 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1): if len(bad_params) == 0 and len(retDesc) == 2 and retDesc[1] == 0: rd = retDesc[0] if rd in NoTranslateMap: - s = "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {}{})".format( - linePrefix, - id, - fdesc[4], - retDesc, - argsDesc, - _BuildArgList(fdesc, names), - ) + s = f"{linePrefix}\treturn self._oleobj_.InvokeTypes({id}, LCID, {fdesc[4]}, {retDesc}, {argsDesc}{_BuildArgList(fdesc, names)})" elif rd in [pythoncom.VT_DISPATCH, pythoncom.VT_UNKNOWN]: - s = "{}\tret = self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})\n".format( - linePrefix, - id, - fdesc[4], - retDesc, - argsDesc, - _BuildArgList(fdesc, names), - ) + s = f"{linePrefix}\tret = self._oleobj_.InvokeTypes({id}, LCID, {fdesc[4]}, {retDesc}, {argsDesc!r}{_BuildArgList(fdesc, names)})\n" 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 += f"{linePrefix}\t\tret = Dispatch(ret, {name!r}, {resclsid})\n" s += f"{linePrefix}\treturn ret" elif rd == pythoncom.VT_BSTR: s = f"{linePrefix}\t# Result is a Unicode object\n" - s += "{}\treturn self._oleobj_.InvokeTypes({}, LCID, {}, {}, {!r}{})".format( - linePrefix, - id, - fdesc[4], - retDesc, - argsDesc, - _BuildArgList(fdesc, names), - ) + s += f"{linePrefix}\treturn self._oleobj_.InvokeTypes({id}, LCID, {fdesc[4]}, {retDesc}, {argsDesc!r}{_BuildArgList(fdesc, names)})" # else s remains None if s is None: - s = "{}\treturn self._ApplyTypes_({}, {}, {}, {}, {!r}, {}{})".format( - linePrefix, - id, - fdesc[4], - retDesc, - argsDesc, - name, - resclsid, - _BuildArgList(fdesc, names), - ) + s = f"{linePrefix}\treturn self._ApplyTypes_({id}, {fdesc[4]}, {retDesc}, {argsDesc}, {name!r}, {resclsid}{_BuildArgList(fdesc, names)})" ret.append(s) ret.append("") diff --git a/com/win32com/client/dynamic.py b/com/win32com/client/dynamic.py index 3738da9031..1bc47dacfa 100644 --- a/com/win32com/client/dynamic.py +++ b/com/win32com/client/dynamic.py @@ -535,9 +535,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) @@ -689,9 +687,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 717f2a9c72..4a6428803a 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 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 aad03afa17..1b9747f45c 100644 --- a/com/win32com/client/genpy.py +++ b/com/win32com/client/genpy.py @@ -539,9 +539,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 @@ -758,12 +756,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! @@ -1343,9 +1336,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 4d60856ed7..bed5740296 100644 --- a/com/win32com/client/makepy.py +++ b/com/win32com/client/makepy.py @@ -106,16 +106,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 ceeabe8ec4..59ef804197 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 e3c85d61a5..ade36e51fb 100644 --- a/com/win32com/makegw/makegw.py +++ b/com/win32com/makegw/makegw.py @@ -244,20 +244,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 @@ -270,9 +264,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") @@ -307,16 +299,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") @@ -326,9 +314,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 @@ -375,9 +361,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") @@ -464,19 +448,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" @@ -522,9 +500,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. @@ -535,9 +511,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 14e800db60..5875273bf7 100644 --- a/com/win32com/makegw/makegwparse.py +++ b/com/win32com/makegw/makegwparse.py @@ -209,11 +209,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" @@ -323,9 +319,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) @@ -366,9 +360,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) @@ -395,9 +387,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) @@ -429,9 +419,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) @@ -453,10 +441,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) @@ -485,11 +470,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... @@ -510,18 +491,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): @@ -529,22 +503,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): @@ -552,19 +518,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): @@ -572,16 +533,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): @@ -592,19 +548,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): @@ -616,10 +564,7 @@ class ArgFormatterInterface(ArgFormatterPythonCOM): def GetInterfaceCppObjectInfo(self): return self.GetIndirectedArgName( 1, self.arg.indirectionLevel - ), "{} * {}".format( - self.GetUnconstType(), - self.arg.name, - ) + ), f"{self.GetUnconstType()} * {self.arg.name}" def GetParsePostCode(self): # This gets called for out params in gateway mode @@ -628,25 +573,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" @@ -654,9 +588,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 7aba2cb22c..a05438af65 100644 --- a/com/win32com/server/dispatcher.py +++ b/com/win32com/server/dispatcher.py @@ -150,9 +150,7 @@ def _QueryInterface_(self, iid): rc = DispatcherBase._QueryInterface_(self, iid) if not rc: self._trace_( - "in {!r}._QueryInterface_ with unsupported IID {} ({})".format( - self.policy._obj_, IIDToInterfaceName(iid), iid - ) + f"in {self.policy._obj_!r}._QueryInterface_ with unsupported IID {IIDToInterfaceName(iid)} ({iid})" ) return rc @@ -178,9 +176,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 8a05ea117f..56968c7a17 100644 --- a/com/win32com/server/register.py +++ b/com/win32com/server/register.py @@ -593,9 +593,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 fea4d20404..1160f9b5eb 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/testvb.py b/com/win32com/test/testvb.py index 91f06d3da2..352e8d6064 100644 --- a/com/win32com/test/testvb.py +++ b/com/win32com/test/testvb.py @@ -339,14 +339,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) @@ -479,14 +477,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})" repr_s = repr(s) if repr_s != expected: print("Expected repr:", expected) diff --git a/com/win32com/test/util.py b/com/win32com/test/util.py index 877d99bf12..d303724173 100644 --- a/com/win32com/test/util.py +++ b/com/win32com/test/util.py @@ -52,12 +52,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 c79d7d80a1..ec42039c2c 100644 --- a/com/win32com/universal.py +++ b/com/win32com/universal.py @@ -212,9 +212,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 5e7467c223..43c85d6b83 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 c4a04329f8..1bae7799a9 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 b5fb32e15e..084e97c4f6 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 f00e383cc3..1020d59479 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/setup.py b/setup.py index b463cc1193..be0bc16e9b 100644 --- a/setup.py +++ b/setup.py @@ -600,8 +600,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 918e4e0816..1e327a80e0 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 3d6fbfc959..f88ebeb3d6 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 58d3326ef5..6c1d0da82a 100644 --- a/win32/Lib/win32evtlogutil.py +++ b/win32/Lib/win32evtlogutil.py @@ -144,10 +144,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 9518f51f65..b4c8f3f58d 100644 --- a/win32/scripts/VersionStamp/vssutil.py +++ b/win32/scripts/VersionStamp/vssutil.py @@ -88,12 +88,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 6fcb730d93..4a7dd03e91 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 7b61cb354d..30b1ce8210 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 8cd79dbf3a..c74a31605c 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