Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Prefer more f-strings and non-printf-style format #2223

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -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)
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/framework/intpyapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 1 addition & 3 deletions Pythonwin/pywin/scintilla/IDLEenvironment.py
Original file line number Diff line number Diff line change
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 @@ -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())
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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."
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
20 changes: 7 additions & 13 deletions com/win32com/client/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
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 @@ -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)

Expand Down Expand Up @@ -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_:
Expand Down Expand Up @@ -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:
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 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()):
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): # Don't 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
4 changes: 1 addition & 3 deletions com/win32com/client/tlbrowse.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
Loading
Loading