Skip to content

Conversation

@BobTheBuidler
Copy link
Contributor

@BobTheBuidler BobTheBuidler commented Sep 18, 2025

This PR implements constant folding for builtin callables where possible.

If all args are constant foldable and the callable is one of the builtin callables below, mypy can, in most cases, fold the result.

The supported builtins are:

foldable_builtins = {
    "builtins.str": str,
    "builtins.int": int,
    "builtins.bool": bool,
    "builtins.float": float,
    "builtins.complex": complex,
    "builtins.repr": repr,
    "builtins.len": len,
    "builtins.hasattr": hasattr,
    "builtins.hex": hex,
    "builtins.min": min,
    "builtins.max": max,
    "builtins.oct": oct,
    "builtins.pow": pow,
    "builtins.round": round,
    "builtins.abs": abs,
    "builtins.ascii": ascii,
    "builtins.bin": bin,
    "builtins.chr": chr,
}

While this PR does not build off of #19885, it does need to come afterward because it contains a refactoring that moves around the code introduced in 19885.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

y = x # E: Cannot determine type of "x" # E: Name "x" is used before definition
y()
y = x # E: Name "x" is used before definition
y() # E: "int" not callable
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think this might indicate a bug in mypy itself? I don't think this should change just from the constant folding

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@BobTheBuidler BobTheBuidler changed the title feat: constant fold common builtin call expressions feat: constant fold common builtin call expressions [3/3] Oct 1, 2025
@BobTheBuidler BobTheBuidler marked this pull request as draft October 1, 2025 23:23
@BobTheBuidler
Copy link
Contributor Author

One example of where this would be useful: mypyc/mypyc#1152

@github-actions
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant