Skip to content

Commit

Permalink
Prefer more f-strings and non-printf-style format
Browse files Browse the repository at this point in the history
Run updated f-string format checks
Use ruff to prevent regressions
And a few manual changes needed for checks to pass
  • Loading branch information
Avasam committed Mar 25, 2024
1 parent 493aba1 commit 905d359
Show file tree
Hide file tree
Showing 56 changed files with 194 additions and 397 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,9 @@ jobs:
- run: pip install isort pycln
- run: pycln . --config=pycln.toml --check
- run: isort . --diff --check-only
- uses: chartboost/ruff-action@v1
with:
version: '0.3.4'
- uses: psf/black@stable
with:
options: "--fast --check --diff --verbose"
Expand Down
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ repos:
- id: isort
name: isort (python)
verbose: true
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.3.4
hooks:
- id: ruff # Run the linter.
args: [--fix]
- repo: https://github.com/psf/black-pre-commit-mirror
rev: 24.2.0
hooks:
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/framework/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 2 additions & 6 deletions Pythonwin/pywin/framework/editor/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/framework/interact.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,9 +328,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(banner)
Expand Down
8 changes: 3 additions & 5 deletions Pythonwin/pywin/framework/intpyapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,8 +298,8 @@ def ProcessArgs(self, args, dde=None):
if dde:
dde.Exec(
"from pywin.framework import scriptutils\n"
"ed = scriptutils.GetActiveEditControl()\n"
"if ed: ed.SetSel(ed.LineIndex(%s - 1))" % gotoline
+ "ed = scriptutils.GetActiveEditControl()\n"
+ "if ed: ed.SetSel(ed.LineIndex(%s - 1))" % gotoline
)
else:
from . import scriptutils
Expand All @@ -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,
)
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/mdi_pychecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ def threadPycheckerRun(self):
elif not os.path.isfile(pychecker):
result = (
"Can't find checker.py - please install pychecker "
"(or run 'setup.py install' if you have the source version)\n"
+ "(or run 'setup.py install' if you have the source version)\n"
)
else:
cmd = f'{py} "{pychecker}" {options} {files} 2>&1'
Expand Down
8 changes: 3 additions & 5 deletions Pythonwin/pywin/scintilla/IDLEenvironment.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ def GetIDLEModule(module):
except ImportError as details:
msg = (
f"The IDLE extension '{module}' can not be located.\r\n\r\n"
"Please correct the installation and restart the"
f" application.\r\n\r\n{details}"
+ "Please correct the installation and restart the"
+ f" application.\r\n\r\n{details}"
)
win32ui.MessageBox(msg)
return None
Expand Down Expand Up @@ -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)}"
)


Expand Down
13 changes: 4 additions & 9 deletions Pythonwin/pywin/scintilla/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,9 +330,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())
Expand Down Expand Up @@ -508,9 +506,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.
Expand Down Expand Up @@ -820,9 +816,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 = msg + "\n\nThe default configuration will be loaded."
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/test/test_pywin.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ def t_print(*args):
pywin.scintilla.IDLEenvironment.test()
ed = scriptutils.GetActiveEditControl()
doc = ed.GetDocument()
assert "hi " "there" in ed.GetTextRange()
assert "hi there" in ed.GetTextRange()
assert doc.IsModified()

# edit w auto-indent
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/tools/hierlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 2 additions & 4 deletions Pythonwin/pywin/tools/regedit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions com/win32com/client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ def CastTo(ob, target, typelib=None):
if not hasattr(mod, target):
raise ValueError(
f"The interface name '{target}' does not appear in the "
f"specified library {typelib.ver_desc!r}"
+ f"specified library {typelib.ver_desc!r}"
)

elif hasattr(target, "index"): # string like
Expand Down Expand Up @@ -199,7 +199,7 @@ def CastTo(ob, target, typelib=None):
if target_clsid is None:
raise ValueError(
f"The interface name '{target}' does not appear in the "
f"same library as object '{ob!r}'"
+ f"same library as object '{ob!r}'"
)
mod = gencache.GetModuleForCLSID(target_clsid)
if mod is not None:
Expand Down
23 changes: 9 additions & 14 deletions com/win32com/client/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,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
Expand Down Expand Up @@ -429,23 +429,18 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1):
if rd == pythoncom.VT_UNKNOWN:
s = (
s
+ "{}\t\t# See if this IUnknown is really an IDispatch\n".format(
linePrefix,
)
+ f"{linePrefix}\t\t# See if this IUnknown is really an IDispatch\n"
)
s = s + f"{linePrefix}\t\ttry:\n"
s = (
s
+ "{}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n".format(
linePrefix
)
+ f"{linePrefix}\t\t\tret = ret.QueryInterface(pythoncom.IID_IDispatch)\n"
)
s = s + f"{linePrefix}\t\texcept pythoncom.error:\n"
s = s + f"{linePrefix}\t\t\treturn ret\n"
s = s + "{}\t\tret = Dispatch(ret, {}, {})\n".format(
linePrefix,
repr(name),
resclsid,
s = (
s
+ f"{linePrefix}\t\tret = Dispatch(ret, {repr(name)}, {resclsid})\n"
)
s = s + "%s\treturn ret" % (linePrefix)
elif rd == pythoncom.VT_BSTR:
Expand Down
12 changes: 3 additions & 9 deletions com/win32com/client/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,9 +539,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)

Expand Down Expand Up @@ -644,9 +642,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_:
Expand Down Expand Up @@ -695,9 +691,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:
Expand Down
18 changes: 4 additions & 14 deletions com/win32com/client/gencache.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,9 +415,7 @@ def ForgetAboutTypelibInterface(typelib_ob):
except KeyError:
# Not worth raising an exception - maybe they dont 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()):
Expand Down Expand Up @@ -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__:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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): # Dont bother reporting this when directory is empty!
print("Done.")
Expand Down
19 changes: 4 additions & 15 deletions com/win32com/client/genpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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!
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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,
)

Expand Down
8 changes: 2 additions & 6 deletions com/win32com/client/makepy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})"
)


Expand Down
Loading

0 comments on commit 905d359

Please sign in to comment.