Mismatch between func.__globals__ and globals retrieved using globals in function in CPython 3.12


I have stumbled on a weird issue.

In a library, I assemble function bytecode manually using the bytecode library. Up to Python 3.11 everything works fine. In Python 3.12, I have one instance in which the following occurs:

  • the function__globals__ attribute of a function contains a specific name (checked by instrumenting the bytecode)
  • when calling that function this name cannot be retrieved and the globals dict actually differs from the function one (checked by instrumenting the bytecode)

I will try to make a minimal reproducer but it may not be easy and I wanted to know if anybody was aware of changes in 3.12 (optimization) that could lead to such an inconsistency ?



1 Like

Diving deeper I believe my problem may find its roots in the fact that globals are loaded from the frame and not the function object. However since CPython creates fewer frames now, I believe it leads to the issue described.

If anybody can point me towards what would force CPython to create the missing frames, it would be great.

I managed to get to the bottom of this. When generating the code object some of them were missing the initial RESUME instruction which turned out to be the root cause of this issue.