Repository navigation
Python cleanups - #6496
Merged
Stephan T. Lavavej (StephanTLavavej) merged 27 commits intoOct 29, 2026
Merged
Python cleanups#6496Stephan T. Lavavej (StephanTLavavej) merged 27 commits into
Stephan T. Lavavej (StephanTLavavej) merged 27 commits into
Conversation
They were deprecated in Python 3.9: https://docs.python.org/3.15/library/typing.html#aliases-to-built-in-types
https://docs.python.org/3.15/library/typing.html#typing.Optional https://docs.python.org/3.15/library/typing.html#typing.Union https://docs.python.org/3.15/builtins/stdtypes.html#types-union Optional and Union aren't deprecated, but Python 3.10's union type expressions are considered cleaner.
https://docs.python.org/3/builtins/stdtypes.html#str.removesuffix This was added in Python 3.9. Example: ``` Python 3.15.0 (tags/v3.15.0:d220409, Oct 9 2026, 11:55:56) [MSC v.1951 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> file1 = 'meow.whatever.txt' >>> file1.endswith('.cpp') False >>> file1.removesuffix('.cpp') 'meow.whatever.txt' >>> file2 = 'test.pass.cpp' >>> file2.endswith('.cpp') True >>> file2[:-4] 'test.pass' >>> file2.removesuffix('.cpp') 'test.pass' ```
This workaround became unnecessary in Python 3.7: https://docs.python.org/3.15/library/subprocess.html#subprocess.Popen > Changed in version 3.7: On Windows the default for `close_fds` was changed from `False` to `True` when redirecting the standard handles. It's now possible to set `close_fds` to `True` when redirecting the standard handles. In our repo, this workaround dates back to when our test harness was added by GH 520 on 2020-03-25 when Python 3.8 was latest. However, it was copied from `llvm/utils/lit/lit/util.py` upstream where it was truly ancient (dating back to at least 2013).
https://docs.python.org/3.15/library/itertools.html#itertools.pairwise This was added in Python 3.10, and is simpler than reasoning about indices. It correctly handles zero/one values: > It will be empty if the input iterable has fewer than two values.
Builtin `enumerate()` is clearly more direct than `zip()` with `itertools.count()`. https://docs.python.org/3.15/builtins/functions.html#enumerate https://docs.python.org/3.15/builtins/functions.html#zip https://docs.python.org/3.15/library/itertools.html#itertools.count
They are equivalent here:
```
C:\Temp>type meow.py
def for_yield(X):
for step in X:
yield step
def yield_from(X):
yield from X
values = [11, 22, 33]
print(f" for_yield: {list( for_yield(iter(values)))}")
print(f"yield_from: {list(yield_from(iter(values)))}")
C:\Temp>py meow.py
for_yield: [11, 22, 33]
yield_from: [11, 22, 33]
```
https://docs.python.org/3/tutorial/datastructures.html#sets This avoids extra layers of lists and lambdas. Simplifying `set(['*'])` to `{'*'}` is an even simpler transformation, not a set comprehension.
https://docs.python.org/3/builtins/functions.html#enumerate The file is already iterable, so we don't need an extra list. Example: ``` C:\Temp>type cats.txt cute fluffy kittens C:\Temp>type meow.py from pathlib import Path filename_path = Path("cats.txt") with filename_path.open() as f: print("enumerating f.readlines():") for line_number, line in enumerate(f.readlines(), start=1): print(f"{line_number}: {line.strip()}") with filename_path.open() as f: print("enumerating f directly:") for line_number, line in enumerate(f, start=1): print(f"{line_number}: {line.strip()}") C:\Temp>py meow.py enumerating f.readlines(): 1: cute 2: fluffy 3: kittens enumerating f directly: 1: cute 2: fluffy 3: kittens ```
https://docs.python.org/3/whatsnew/3.15.html#whatsnew315-lazy-imports print_failures.py parses either JSON or XML on any given run, so lazy loading is appropriate. In util.py, we can now centralize our imports while preserving lazy behavior.
This makes it easier to see what strings are being formed. Also we can implicitly concatenate adjacent string literals.
This is significantly clearer than constructing a format string via concatenation. envNumWidth is exactly the right concept to introduce.
https://docs.python.org/3/builtins/stdtypes.html#set.isdisjoint This is more efficient than performing a full set intersection just to test whether it's non-empty.
This is slightly more direct than naming the superclass again and passing `self`.
https://docs.python.org/3/library/os.html#os.scandir > Using `scandir()` instead of `listdir()` can significantly increase the performance > of code that also needs file type or file attribute information It's also cleaner that we don't need to reconstruct a `filepath`. This is worth an additional level of nesting.
https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements This is clearly less verbose.
https://docs.python.org/3.15/builtins/stdtypes.html#set-types-set-frozenset > Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other).
This reads slightly more naturally.
https://docs.python.org/3/builtins/constants.html#constants-added-by-the-site-module https://docs.python.org/3/library/sys.html#sys.exit Plain `exit()` is a convenience for the interactive interpreter shell. When we call it, it raises `SystemExit`, just like `sys.exit()`.
Stephan T. Lavavej (StephanTLavavej)
requested a review
from a team
as a code owner
October 19, 2026 19:47
This comment was marked as resolved.
This comment was marked as resolved.
Billy O'Neal (BillyONeal)
approved these changes
Oct 19, 2026
Member
Author
|
I'm mirroring this to the MSVC-internal repo. Please notify me if any further changes are pushed, otherwise no action is required. |
Stephan T. Lavavej (StephanTLavavej)
merged commit Oct 29, 2026
9f84539
into
microsoft:main
48 checks passed
Stephan T. Lavavej (StephanTLavavej)
deleted the
python-cleanups-gpt-6.1-sol
branch
October 29, 2026 07:28
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
After I upgraded Python to 3.15 in #6491, I remembered that we had an ancient comment about working around the lack of
frozendict, which Python 3.15 added as a built-in type. This PR contains a bunch of modernizations and cleanups, identified and performed by GPT-6.1 Sol since I'm not a Python expert. As usual, this writeup is entirely mine. In each case, I reviewed the changes, looking up the documentation to figure out when features were added/deprecated/etc. and why various changes worked. I also structured everything into fine-grained commits for ease of reviewing. (GPT-6.1 Sol was quite good about identifying possible improvements in a table, then making individual changes upon request, which I could then review and package up into commits.) I kept going until the issues it identified didn't meet my risk-reward threshold.Do not do this cool thing: I don't really want to see others creating AI-assisted cleanup PRs, especially in our C++ code, where the risk is much greater. In this case, I'm a maintainer so the risk and review burden is mine, and the Python code is used only for our GitHub test harness and helper scripts, so there's no direct impact on the product.
I ran a full local test pass for x64, manually exercised the Unicode scripts to verify unchanged output, and exercised my
print_failures.pyscript with both passing and failing JSON and XML.frozendictas a built-in type.frozendictbuilt-in typeDict,List,Set,Tuplealiases.OptionalandUnionwith union type expressions.OptionalandUnionaren't deprecated, but Python 3.10's union type expressions are considered cleaner.typing.Optionaltyping.Unionstr.removesuffix().str.removesuffixsubprocess.Popen().llvm/utils/lit/lit/util.pyupstream where it was truly ancient (dating back to at least 2013).subprocess.Popenitertools.pairwise().itertools.pairwiseenumerate().enumerate()is clearly more direct thanzip()withitertools.count().enumeratezipitertools.countyield from.set(['*'])to{'*'}is an even simpler transformation, not a set comprehension.enumerate()a file's lines.enumerateany().any__traceback__.sys.exc_infoBaseException.__traceback__print_failures.pyparses either JSON or XML on any given run, so lazy loading is appropriate. Inutil.py, we can now centralize our imports while preserving lazy behavior.envNumWidthis exactly the right concept to introduce.set.isdisjoint.set.isdisjointsuper().__init__().self.os.scandir().filepath. This is worth an additional level of nesting.os.scandirre.prefixmatch()and soft-deprecatedre.match().reset,frozensetsys.exit().exit()is a convenience for the interactive interpreter shell. When we call it, it raisesSystemExit, just likesys.exit().sitemodulesys.exit