what’s happening earlier in python while creating a variable?

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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top