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

Remove redundant str() calls and prefer !r marker for repr in formatting #2272

Open
wants to merge 2 commits 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
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/app/basictimerapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/cmdserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/Demos/objdoc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,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:
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/editor/vss.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion Pythonwin/pywin/framework/intpyapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def ProcessArgs(self, args, dde=None):
)
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":
Expand Down
37 changes: 17 additions & 20 deletions Pythonwin/pywin/framework/mdi_pychecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,12 +287,12 @@ def doSearch(self):
)
# self.text = []
self.GetFirstView().Append(
"#Pychecker Run in " + self.dirpattern + " %s\n" % time.asctime()
f"#Pychecker Run in {self.dirpattern} {time.asctime()}\n"
)
if self.verbose:
self.GetFirstView().Append("# =" + repr(self.dp.dirs) + "\n")
self.GetFirstView().Append("# Files " + self.filpattern + "\n")
self.GetFirstView().Append("# Options " + self.greppattern + "\n")
self.GetFirstView().Append(f"# ={self.dp.dirs!r}\n")
self.GetFirstView().Append(f"# Files {self.filpattern}\n")
self.GetFirstView().Append(f"# Options {self.greppattern}\n")
self.fplist = self.filpattern.split(";")
self.GetFirstView().Append(
"# Running... ( double click on result lines in order to jump to the source code ) \n"
Expand Down Expand Up @@ -389,7 +389,7 @@ def _inactive_idleHandler(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
Expand All @@ -415,18 +415,13 @@ def _inactive_idleHandler(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):
Expand Down Expand Up @@ -540,9 +535,11 @@ def OnAddComment(self, cmd, code):
if view.GetTextRange(pos - 1, pos) in ("\r", "\n"):
pos -= 1
view.SetSel(pos, pos)
errtext = m.group(3)
if start != end and line_start == line_end:
errtext = self.GetSelText()
errtext = (
self.GetSelText()
if start != end and line_start == line_end
else m.group(3)
)
errtext = repr(re.escape(errtext).replace(r"\ ", " "))
view.ReplaceSel(addspecific and cmnt % locals() or cmnt)
return 0
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/framework/scriptutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,10 +614,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.


Expand Down
29 changes: 12 additions & 17 deletions Pythonwin/pywin/framework/sgrepmdi.py
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,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)
Expand Down Expand Up @@ -301,7 +301,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
Expand All @@ -327,18 +327,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):
Expand Down
6 changes: 3 additions & 3 deletions Pythonwin/pywin/idle/AutoIndent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/idle/CallTips.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 1 addition & 5 deletions Pythonwin/pywin/scintilla/IDLEenvironment.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,11 +516,7 @@ def TestCheck(index, edit, expected=None):
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)
)
)
print(f"ERROR: get({fr!r}, {to!r}) expected {expected!r}, but got {got!r}")


def test():
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/scintilla/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/pywin/scintilla/keycodes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
4 changes: 1 addition & 3 deletions Pythonwin/pywin/scintilla/view.py
Original file line number Diff line number Diff line change
Expand Up @@ -512,9 +512,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 - {sys.exc_info()[0]!r}"
)

items = [
Expand Down
15 changes: 4 additions & 11 deletions Pythonwin/pywin/tools/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
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 @@ -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):
Expand All @@ -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):
Expand Down
25 changes: 11 additions & 14 deletions com/win32com/client/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,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:
Expand Down Expand Up @@ -404,7 +403,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],
Expand All @@ -413,12 +412,12 @@ 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"
Expand All @@ -432,29 +431,27 @@ def MakeDispatchFuncMethod(self, entry, name, bMakeClass=1):
)
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 += "%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),
)
Expand Down
Loading
Loading