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

Demonstration of old python code using pyupgrade #2100

Closed
wants to merge 4 commits into from
Closed
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
6 changes: 3 additions & 3 deletions .github/workflows/download-arm64-libs.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@

VERSION = "{}.{}.{}".format(*sys.version_info[:3])
if sys.version_info.releaselevel == "alpha":
VERSION += "-a{}".format(sys.version_info.serial)
VERSION += f"-a{sys.version_info.serial}"
if sys.version_info.releaselevel == "beta":
VERSION += "-b{}".format(sys.version_info.serial)
VERSION += f"-b{sys.version_info.serial}"
if sys.version_info.releaselevel == "candidate":
VERSION += "-rc{}".format(sys.version_info.serial)
VERSION += f"-rc{sys.version_info.serial}"

URL = f"https://www.nuget.org/api/v2/package/pythonarm64/{VERSION}"
PATH = dest / f"pythonarm64.{VERSION}.zip"
Expand Down
6 changes: 5 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- run: pip install isort pycln
- run: pip install pyupgrade pycln isort
# Ignore adodbapi until this has been manually ran and merged in adodbapi code
# _dbgscript.py is non-UTF8 on purpose, which is not supported
# TODO: Remove the --keep-percent-format flag and fix all printf-style string formatting
- run: pyupgrade --keep-percent-format --py37-plus $(git ls-files '**.py*' ':!:adodbapi/*' ':!:Pythonwin/pywin/test/_dbgscript.py')
- run: pycln . --config=pycln.toml --check
- run: isort . --diff --check-only
- uses: psf/black@stable
Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/Dump2HHC.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ def main():
cats = parseCategories()
for cat in cats:
file = os.path.join(gen_dir, cat.dump_file)
input = open(file, "r")
input = open(file)
parseTopics(cat, input)
input.close()

Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/InsertExternalOverviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def main():
print("Invalid args")
sys.exit(1)
file = sys.argv[1]
input = open(file, "r")
input = open(file)
out = open(file + ".2", "w")
doc = document_object.GetDocument()
linksHTML = genLinksHTML(doc.links)
Expand Down
2 changes: 1 addition & 1 deletion AutoDuck/TOCToHHK.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
def main():
file = sys.argv[1]
output = sys.argv[2]
input = open(file, "r")
input = open(file)
out = open(output, "w")
line = input.readline()
out.write(
Expand Down
2 changes: 1 addition & 1 deletion Pythonwin/Scintilla/src/LexGen.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def Generate(inpath, outpath, commentPrefix, eolType, *lists):
# print "generate '%s' -> '%s' (comment prefix: %r, eols: %r)"\
# % (inpath, outpath, commentPrefix, eolType)
try:
infile = open(inpath, "r")
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know Scintilla is vendored, but these changes are automated. Just like pycln, isort and black, is that fine? I assume the idea is that we trust this won't lead to behaviour changes and that updating Scintilla won't cause these changes to be lost because they'll be automatically re-applied.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem then will be that re-vendoring in the future would break, meaning we'd need to work out what to re-run etc. It seems better long term to just ignore scintilla entirely, which works both today and in the future.

infile = open(inpath)
except OSError:
print("Can not open", inpath)
return
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/framework/mdi_pychecker.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def OnOpenDocument(self, fnm):
# and starting a new grep can communicate the default parameters to the
# new grep.
try:
params = open(fnm, "r").read()
params = open(fnm).read()
except:
params = None
self.setInitParams(params)
Expand Down Expand Up @@ -386,7 +386,7 @@ def _inactive_idleHandler(self, handler, count):
if self.verbose:
self.GetFirstView().Append("# .." + f + "\n")
win32ui.SetStatusText("Searching " + f, 0)
lines = open(f, "r").readlines()
lines = open(f).readlines()
for i in range(len(lines)):
line = lines[i]
if self.pat.search(line) is not None:
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 @@ -101,8 +101,8 @@ def IsOnPythonPath(path):

def GetPackageModuleName(fileName):
"""Given a filename, return (module name, new path).
eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path.
If no package found, will return ("my", "c:\a\b\c")
eg - given "c:\a\b\\c\\my.py", return ("b.c.my",None) if "c:\a" is on sys.path.
If no package found, will return ("my", "c:\a\b\\c")
"""
path, fname = os.path.split(fileName)
path = origPath = win32ui.FullPath(path)
Expand Down
4 changes: 2 additions & 2 deletions Pythonwin/pywin/framework/sgrepmdi.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def OnOpenDocument(self, fnm):
# and starting a new grep can communicate the default parameters to the
# new grep.
try:
params = open(fnm, "r").read()
params = open(fnm).read()
except:
params = None
self.setInitParams(params)
Expand Down Expand Up @@ -299,7 +299,7 @@ def SearchFile(self, handler, count):
# while grep is running
if os.path.isfile(f):
win32ui.SetStatusText("Searching " + f, 0)
lines = open(f, "r").readlines()
lines = open(f).readlines()
for i in range(len(lines)):
line = lines[i]
if self.pat.search(line) is not None:
Expand Down
1 change: 0 additions & 1 deletion Pythonwin/pywin/tools/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +0,0 @@

2 changes: 1 addition & 1 deletion com/win32com/client/genpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1036,7 +1036,7 @@ def open_writer(self, filename, encoding="mbcs"):
# don't step on each others' toes.
# Could be a classmethod one day...
temp_filename = self.get_temp_filename(filename)
return open(temp_filename, "wt", encoding=encoding)
return open(temp_filename, "w", encoding=encoding)

def finish_writer(self, filename, f, worked):
f.close()
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/client/makepy.py
Original file line number Diff line number Diff line change
Expand Up @@ -425,7 +425,7 @@ def main():
path = os.path.dirname(outputName)
if path != "" and not os.path.exists(path):
os.makedirs(path)
f = open(outputName, "wt", encoding="mbcs")
f = open(outputName, "w", encoding="mbcs")

else:
f = None
Expand Down
2 changes: 0 additions & 2 deletions com/win32com/demos/iebutton.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: latin-1 -*-

# PyWin32 Internet Explorer Button
#
# written by Leonard Ritter (paniq@gmx.net)
Expand Down
2 changes: 0 additions & 2 deletions com/win32com/demos/ietoolbar.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: latin-1 -*-

# PyWin32 Internet Explorer Toolbar
#
# written by Leonard Ritter (paniq@gmx.net)
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/test/testIterators.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def suite():
and issubclass(item, unittest.TestCase)
and item != _BaseTestCase
):
suite.addTest(unittest.makeSuite(item))
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(item))
return suite


Expand Down
2 changes: 1 addition & 1 deletion com/win32com/test/testall.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def make_test_suite(test_level=1):
for mod_name in unittest_modules[i]:
mod, func = get_test_mod_and_func(mod_name, import_failures)
if mod is None:
raise Exception("no such module '{}'".format(mod_name))
raise Exception(f"no such module '{mod_name}'")
if func is not None:
test = CapturingFunctionTestCase(func, description=mod_name)
else:
Expand Down
2 changes: 1 addition & 1 deletion com/win32com/test/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def ExecuteShellCommand(
output_name = tempfile.mktemp("win32com_test")
cmd = cmd + ' > "%s" 2>&1' % output_name
rc = os.system(cmd)
output = open(output_name, "r").read().strip()
output = open(output_name).read().strip()
os.remove(output_name)

class Failed(Exception):
Expand Down
2 changes: 1 addition & 1 deletion com/win32comext/authorization/demos/EditServiceSecurity.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Implements a permissions editor for services.
Service can be specified as plain name for local machine,
or as a remote service of the form \\machinename\service
or as a remote service of the form \\machinename\\service
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm quite surprised this tool is so opinionated about comments, but it got it wrong here - the existing "\\" should now be "\\\\"

Copy link
Collaborator Author

@Avasam Avasam Aug 17, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's an opinion about comments: it correctly found (and fixed) an invalid escape sequence in the dosctring: \s. It didn't touch the existing \\ because that"s a valid \ character once escaped.

That being said, you're right this docstring should have \\\\machinename\\ to properly escape to \\machinename\ (or make the whole thing a raw docstring)

"""

import os
Expand Down
2 changes: 1 addition & 1 deletion com/win32comext/axdebug/Test/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def _query_interface_(self, iid):
def _GetCodeContainer(self):
if self.codeContainer is None:
try:
codeText = open(self.module.__file__, "rt").read()
codeText = open(self.module.__file__).read()
except OSError as details:
codeText = "# Exception opening file\n# %s" % (details)

Expand Down
2 changes: 1 addition & 1 deletion com/win32comext/axdebug/codecontainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def GetText(self):
fname = self.GetFileName()
if fname:
try:
self.text = open(fname, "r").read()
self.text = open(fname).read()
except OSError as details:
self.text = "# Exception opening file\n# %s" % (repr(details))
else:
Expand Down
8 changes: 8 additions & 0 deletions format_all.bat
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
@echo off
@REM Ignore adodbapi until this has been manually ran and merged in adodbapi code
@REM _dbgscript.py is non-UTF8 on purpose, which is not supported
for /f "delims=" %%F in ('git ls-files **.py* :!:adodbapi/* :!:Pythonwin/pywin/test/_dbgscript.py') do (
@REM TODO: Remove the --keep-percent-format flag and fix all printf-style string formatting
pyupgrade --keep-percent-format --py37-plus %%F
)
@echo on
pycln . --config=pycln.toml
isort .
black .
4 changes: 2 additions & 2 deletions pywin32_postinstall.py
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,7 @@ def uninstall(lib_dir):

def verify_destination(location):
if not os.path.isdir(location):
raise argparse.ArgumentTypeError('Path "{}" does not exist!'.format(location))
raise argparse.ArgumentTypeError(f'Path "{location}" does not exist!')
return location


Expand Down Expand Up @@ -756,7 +756,7 @@ def main():
args = parser.parse_args()

if not args.quiet:
print("Parsed arguments are: {}".format(args))
print(f"Parsed arguments are: {args}")

if not args.install ^ args.remove:
parser.error("You need to either choose to -install or -remove!")
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ def _check_vc(self):
# so find and add them
if vcbase and not atlmfc_found:
atls_lib = glob.glob(
vcbase + r"ATLMFC\lib\{}\atls.lib".format(self.plat_dir)
vcbase + fr"ATLMFC\lib\{self.plat_dir}\atls.lib"
)
if atls_lib:
self.library_dirs.append(os.path.dirname(atls_lib[0]))
Expand Down
10 changes: 5 additions & 5 deletions win32/Demos/EvtFormatMessage.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def main():
event, win32evtlog.EvtRenderEventValues, Context=context
)

print("Event {}".format(i))
print(f"Event {i}")

level_value, level_variant = result[win32evtlog.EvtSystemLevel]
if level_variant != win32evtlog.EvtVarTypeNull:
Expand All @@ -42,17 +42,17 @@ def main():
win32evtlog.EvtSystemTimeCreated
]
if time_created_variant != win32evtlog.EvtVarTypeNull:
print(" Timestamp: {}".format(time_created_value.isoformat()))
print(f" Timestamp: {time_created_value.isoformat()}")

computer_value, computer_variant = result[win32evtlog.EvtSystemComputer]
if computer_variant != win32evtlog.EvtVarTypeNull:
print(" FQDN: {}".format(computer_value))
print(f" FQDN: {computer_value}")

provider_name_value, provider_name_variant = result[
win32evtlog.EvtSystemProviderName
]
if provider_name_variant != win32evtlog.EvtVarTypeNull:
print(" Provider: {}".format(provider_name_value))
print(f" Provider: {provider_name_value}")

try:
metadata = win32evtlog.EvtOpenPublisherMetadata(provider_name_value)
Expand All @@ -69,7 +69,7 @@ def main():
pass
else:
try:
print(" Message: {}".format(message))
print(f" Message: {message}")
except UnicodeEncodeError:
# Obscure error when run under subprocess.Popen(), presumably due to
# not knowing the correct encoding for the console.
Expand Down
10 changes: 5 additions & 5 deletions win32/Lib/win32rcparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -584,21 +584,21 @@ def ParseStreams(rc_file, h_file):

def Parse(rc_name, h_name=None):
if h_name:
h_file = open(h_name, "r")
h_file = open(h_name)
else:
# See if same basename as the .rc
h_name = rc_name[:-2] + "h"
try:
h_file = open(h_name, "r")
h_file = open(h_name)
except OSError:
# See if MSVC default of 'resource.h' in the same dir.
h_name = os.path.join(os.path.dirname(rc_name), "resource.h")
try:
h_file = open(h_name, "r")
h_file = open(h_name)
except OSError:
# .h files are optional anyway
h_file = None
rc_file = open(rc_name, "r")
rc_file = open(rc_name)
try:
return ParseStreams(rc_file, h_file)
finally:
Expand All @@ -617,7 +617,7 @@ def GenerateFrozenResource(rc_name, output_name, h_name=None):
rcp = Parse(rc_name, h_name)
in_stat = os.stat(rc_name)

out = open(output_name, "wt")
out = open(output_name, "w")
out.write("#%s\n" % output_name)
out.write("#This is a generated file. Please edit %s instead.\n" % rc_name)
out.write("__version__=%r\n" % __version__)
Expand Down
2 changes: 0 additions & 2 deletions win32/Lib/win32timezone.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# -*- coding: UTF-8 -*-

"""
win32timezone:
Module for handling datetime.tzinfo time zones using the windows
Expand Down
2 changes: 1 addition & 1 deletion win32/scripts/VersionStamp/bulkstamp.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def load_descriptions(fname, vars):
retvars = {}
descriptions = {}

lines = open(fname, "r").readlines()
lines = open(fname).readlines()

for i in range(len(lines)):
line = lines[i].strip()
Expand Down
2 changes: 1 addition & 1 deletion win32/scripts/VersionStamp/vssutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def SubstituteInString(inString, evalEnv):


def SubstituteInFile(inName, outName, evalEnv):
inFile = open(inName, "r")
inFile = open(inName)
try:
outFile = open(outName, "w")
try:
Expand Down
4 changes: 2 additions & 2 deletions win32/scripts/regsetup.py
Original file line number Diff line number Diff line change
Expand Up @@ -506,9 +506,9 @@ def RegisterShellInfo(searchPaths):
as well as the 2 wierd spots to locate the core Python files (eg, Python.exe,
pythonXX.dll, the standard library and Win32 Extensions.

"regsetup -a myappname . .\subdir"
"regsetup -a myappname . .\\subdir"
Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and
"C:\\I\\AM\\HERE\subdir" added to the path (ie, all args are converted to
"C:\\I\\AM\\HERE\\subdir" added to the path (ie, all args are converted to
absolute paths)

"regsetup -c c:\\my\\python\\files"
Expand Down
2 changes: 1 addition & 1 deletion win32/test/test_odbc.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def testLongBinary(self):

def testRaw(self):
## Test binary data
self._test_val("rawfield", memoryview(b"\1\2\3\4\0\5\6\7\8"))
self._test_val("rawfield", memoryview(b"\1\2\3\4\0\5\6\7\\8"))

def test_widechar(self):
"""Test a unicode character that would be mangled if bound as plain character.
Expand Down
2 changes: 1 addition & 1 deletion win32/test/testall.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ def find_exception_in_output(data):
class TestRunner:
def __init__(self, argv):
self.argv = argv
self.__name__ = "Test Runner for cmdline {}".format(argv)
self.__name__ = f"Test Runner for cmdline {argv}"

def __call__(self):
import subprocess
Expand Down