This is all going to be CPython implementation details. Other implementations may behaved differently.
Memory allocation for variables is completely independent of what type of object they refer to. Whether you assign x = []
, x = 5
, or x = SomeCrazyHugeThing()
, the value doesn't affect the memory allocated for x
. Local variables are allocated as a PyObject *
in a Python stack frame's f_localsplus
when the function call is entered; other variables are "allocated" as dict
entries in the corresponding namespace's dict at time of first assignment. (Crazy metaclasses and exec
shenanigans can change this in weird ways, but we're not going to go into that.)
That's for variables. Objects, like the float
instance the 9.89
expression evaluates to in your example code, are allocated differently. Each type is responsible for allocating memory when an instance of the type is created and reallocating or deallocating it as needed when the object grows, shrinks, or is destroyed. The manner in which this is done depends on the type.
Note that the time at which an object is created can be surprising. For example, in x = 9.89
, Python creates (and allocates memory for) a float
object when the bytecode for that statement is compiled. During bytecode execution, Python just retrieves the existing float
; no new float
is allocated.