Skip to content

Python cleanups - #6496

Merged
Stephan T. Lavavej (StephanTLavavej) merged 27 commits into
microsoft:mainfrom
StephanTLavavej:python-cleanups-gpt-6.1-sol
Oct 29, 2026
Merged

Stephan T. Lavavej (StephanTLavavej) merged 27 commits into
microsoft:mainfrom
StephanTLavavej:python-cleanups-gpt-6.1-sol

Conversation

@StephanTLavavej

Copy link
Copy Markdown
Member

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.py script with both passing and failing JSON and XML.

  • Python 3.15 added frozendict as a built-in type.
  • Replace deprecated Dict, List, Set, Tuple aliases.
  • Replace Optional and Union with union type expressions.
  • Use str.removesuffix().
  • Remove Windows workaround in subprocess.Popen().
    • This workaround became unnecessary in Python 3.7. In our repo, this workaround dates back to when our test harness was added by Add tests using lit as a test harness #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).
    • 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.

  • Use itertools.pairwise().
    • This was added in Python 3.10, and is simpler than reasoning about indices. It correctly handles zero/one values.
    • itertools.pairwise
    • It will be empty if the input iterable has fewer than two values.

  • Use enumerate().
  • Use yield from.
    • They are equivalent here.
  • Use set comprehensions.
    • This avoids extra layers of lists and lambdas. Simplifying set(['*']) to {'*'} is an even simpler transformation, not a set comprehension.
    • Sets
  • Directly enumerate() a file's lines.
    • The file is already iterable, so we don't need an extra list.
    • enumerate
  • Pass a generator expression to any().
  • Directly read an exception's __traceback__.
  • Python 3.15 added explicit lazy imports.
  • Python 3.15 added unpacking in comprehensions.
  • Use f-strings, especially after Python 3.12 improved them.
  • Use f-strings instead of string concatenation (simple cases).
    • This makes it easier to see what strings are being formed. Also we can implicitly concatenate adjacent string literals.
  • Use f-strings instead of string concatenation (moderate cases).
  • Use f-strings (complex case).
    • This is significantly clearer than constructing a format string via concatenation. envNumWidth is exactly the right concept to introduce.
  • Use set.isdisjoint.
    • This is more efficient than performing a full set intersection just to test whether it's non-empty.
    • set.isdisjoint
  • Use list comprehensions.
  • Use super().__init__().
    • This is slightly more direct than naming the superclass again and passing self.
  • Use os.scandir().
    • It's also cleaner that we don't need to reconstruct a filepath. This is worth an additional level of nesting.
    • os.scandir
    • Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information

  • Python 3.15 added re.prefixmatch() and soft-deprecated re.match().
  • Use augmented assignments.
  • Use set equality.
    • 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).

  • Test for membership directly.
    • This reads slightly more naturally.
  • Call sys.exit().
    • Plain exit() is a convenience for the interactive interpreter shell. When we call it, it raises SystemExit, just like sys.exit().
    • Constants added by the site module
      • They are useful for the interactive interpreter shell and should not be used in programs.

    • sys.exit

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.
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.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()`.
@StephanTLavavej Stephan T. Lavavej (StephanTLavavej) added the test Related to test code label Oct 19, 2026
Copilot AI balanced review requested due to automatic review settings October 19, 2026 19:47
@azure-pipelines

This comment was marked as resolved.

This comment was marked as resolved.

@StephanTLavavej Stephan T. Lavavej (StephanTLavavej) moved this from Final Review to Ready To Merge in STL Code Reviews Oct 19, 2026
@StephanTLavavej

Copy link
Copy Markdown
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.

@StephanTLavavej Stephan T. Lavavej (StephanTLavavej) moved this from Ready To Merge to Merging in STL Code Reviews Oct 27, 2026
@StephanTLavavej
Stephan T. Lavavej (StephanTLavavej) merged commit 9f84539 into microsoft:main Oct 29, 2026
48 checks passed
@github-project-automation github-project-automation Bot moved this from Merging to Done in STL Code Reviews Oct 29, 2026
@StephanTLavavej
Stephan T. Lavavej (StephanTLavavej) deleted the python-cleanups-gpt-6.1-sol branch October 29, 2026 07:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test Related to test code

Projects

Archived in project

Development

Successfully merging this pull request may close these issues.

3 participants