Does the interpretator make a name or object? for example: VAR = 100 Initially, interpreter makes a name VAR and assigns to VAR an object with the value 100 or interpreter creates an object with the value 100 and further creates a name VAR and assign to it an object ?
CodePudding user response:
It creates a new object, but according to this documentation, there are ready to use objects that have already been created for all integers between -5
and 256
, so in your example Python already has an integer object created for 100
that will be referenced instead of creating a brand new object.
To answer your next question, if var=257
Python will still create an object. What gets created first? Well, there is a module called dis
that lets us disassemble any Python code to the bytecode that gets generated. If we do
dis.dis('var = 257')
Then we get
1 0 LOAD_CONST 0 (257)
2 STORE_NAME 0 (var)
4 LOAD_CONST 1 (None)
6 RETURN_VALUE
You can see what each of the bytecode instructions do here.
The bytecode instruction for STORE_NAME says (TOS stands for top of stack):
STORE_NAME(namei)
Implements name = TOS. namei is the index of name in the attribute co_names of the code object.
No further information is shared if the name is added to co_names
(code object names) before the PyLongObject (cPython's int object) is created. Often times the compile.c file of cPython gives good insights into how bytecode operations work under the hood, but I wasn't able to find an exact answer to your question in the source code. I would imagine that the PyLongObject
is created first and then added to co_names
as otherwise you would have to add the name and set it to null and then go back and change it after you have created the PyLongObject
, which is just messier and slower.