Skip to content

mypyc: Use widened parameter types in native signatures - #22228

Open
charan-rathore wants to merge 3 commits into
python:masterfrom
charan-rathore:fix/redefined-param-widened-signature
Open

charan-rathore wants to merge 3 commits into
python:masterfrom
charan-rathore:fix/redefined-param-widened-signature

Conversation

@charan-rathore

Copy link
Copy Markdown

Fixes #22221.

With --allow-redefinition, mypy widens a redefined parameter's variable type to the join of the declaration and every redefinition (e.g. n: int later assigned object() becomes union[int, object]). mypyc creates the argument's local register and any closure environment attribute with that widened type, but Mapper.fdef_to_sig built the native signature from the declared Callable type. The generated C entry then received the narrow declared type (CPyTagged) and stored it straight into the wider environment attribute (PyObject *), which fails to compile:

build/__native.c:551:33: error: incompatible types when assigning to type 'PyObject *' {aka 'struct _object *'} from type 'CPyTagged' {aka 'long unsigned int'}

Now each argument's runtime type comes from the parameter variable's type, falling back to the declared Callable type when the variable has none. Without --allow-redefinition the variable type equals the declared type, so existing signatures are unchanged.

One behavior note: the native wrapper for such a function now accepts any object for a widened parameter (mypy still rejects non-conforming calls statically). That matches the flag's semantics - the variable can hold non-declared values at runtime.

Tested:

  • The issue's repro compiles now, and the compiled module behaves like the interpreter (f(3) == 2).
  • Added a unit test asserting the native signature uses the widened type; it fails without the fix.
  • pytest mypyc/test/test_irbuild.py: 783 passed.

Prepared with AI assistance (Instinct assisted).

charan-rathore and others added 3 commits October 19, 2026 20:10
Updated argument type retrieval in fdef_to_sig to use variable types instead of declared types, addressing issue python#22221.
Add a test case to verify widening of native signatures under redefinition.
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.

[mypyc] Invalid C for an int-annotated parameter rebound via nonlocal with --allow-redefinition-new

1 participant