Skip to content

gh-126835: Remove unused docstring const #130016

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

WolframAlph
Copy link
Contributor

@WolframAlph WolframAlph commented Feb 11, 2025

If no docstring present, extra unused constant from CFG optimization pass will reuse always preserved slot for docstring which leads to unused constant in co_consts. This breaks some unrelated tests when migrating optimizations from AST to CFG. Bug example:

@support.cpython_only
def test_remove_unused_consts(self):
def f():
"docstring"
if True:
return "used"
else:
return "unused"
self.assertEqual(f.__code__.co_consts,
(f.__doc__, "used"))
@support.cpython_only
def test_remove_unused_consts_no_docstring(self):
# the first item (None for no docstring in this case) is
# always retained.
def f():
if True:
return "used"
else:
return "unused"
self.assertEqual(f.__code__.co_consts,
(True, "used"))

First test case does not have True in co_consts but second one does even though it is not used (not used in first either) which is funny. Another example:

def f():
    return x

print(f.__code__.co_consts)  #  (None,)

None is in co_consts even though None is not used in f. It sneaks in by implicitly adding return None when compiling code unit, and it stays there because of always preserved slot for docstring.

Related comment: #126835 (comment)

@WolframAlph WolframAlph changed the title remove unused docstring const Remove unused docstring const Feb 11, 2025
@WolframAlph WolframAlph changed the title Remove unused docstring const gh-130016: Remove unused docstring const Feb 11, 2025
@WolframAlph WolframAlph changed the title gh-130016: Remove unused docstring const gh-126835: Remove unused docstring const Feb 11, 2025
@WolframAlph WolframAlph marked this pull request as ready for review February 11, 2025 21:25
@WolframAlph
Copy link
Contributor Author

WolframAlph commented Feb 11, 2025

@iritkatriel let me know if you prefer having this linked to a separate issue. And also if we need to add some tests for this & news entry.

index_map[i] = -1;
}
// The first constant may be docstring; keep it always.
index_map[0] = 0;
Copy link
Member

Choose a reason for hiding this comment

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

Maybe update the comment above? It's only kept when we have the docstring now

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants