Skip to content

Commit

Permalink
Remove redundant str coercion and prefer !r marker for repr in format…
Browse files Browse the repository at this point in the history
…ting
  • Loading branch information
Avasam committed May 29, 2024
1 parent aa59486 commit 305e36a
Show file tree
Hide file tree
Showing 58 changed files with 220 additions and 274 deletions.
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 @@ -50,7 +50,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 = 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 @@ -164,7 +164,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 @@ -289,12 +289,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 @@ -391,7 +391,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 = self.fpndx + 1
Expand All @@ -417,18 +417,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 @@ -542,9 +537,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 @@ -612,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.


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 @@ -266,11 +266,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 @@ -303,7 +303,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 = self.fpndx + 1
Expand All @@ -329,18 +329,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
8 changes: 4 additions & 4 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 @@ -262,7 +262,7 @@ def newline_and_indent_event(self, event):
else:
self.reindent_to(y.compute_backslash_indent())
else:
assert 0, "bogus continuation type " + repr(c)
assert 0, f"bogus continuation type {c!r}"
return "break"

# This line starts a brand new stmt; indent relative to
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}"
)

# ensure all keys are strings.
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 = pos + 1
self.InsertDocString(ret)
return ret
Expand Down
4 changes: 2 additions & 2 deletions adodbapi/ado_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def ado_direction_name(ado_dir):
try:
return "adParam" + directions[ado_dir]
except:
return "unknown direction (" + str(ado_dir) + ")"
return f"unknown direction ({ado_dir})"


# ObjectStateEnum
Expand Down Expand Up @@ -166,7 +166,7 @@ def ado_direction_name(ado_dir):


def ado_type_name(ado_type):
return adTypeNames.get(ado_type, "unknown type (" + str(ado_type) + ")")
return adTypeNames.get(ado_type, f"unknown type ({ado_type})")


# here in decimal, sorted by value
Expand Down
Loading

0 comments on commit 305e36a

Please sign in to comment.