CynicalPassion63
CynicalPassion63

Reputation: 153

"Large" Numbers in Python

I was doing a little bit of reading on how integers are represented in Python. I found this really neat article (http://www.laurentluce.com/posts/python-integer-objects-implementation/) which explains how everything set up, and how the set of "small" numbers (-5 to 256) are essentially created for free at the start of your program in a big array, so if I had

x = 5 y = 5

both x and y would be pointing to the same universal 5 object that was created at the program's start. The article gives an example that if x or y were to be set to 300 (out of range of the small numbers) then simply a new integer would be created in the next block of free space representing 300.

Does this mean that if I set both x and y to 300, they would both know to point to the same 300? It makes sense with the 5 because you can just index into the special small integer data structure offsetting bu the negative numbers, but since any numbers larger than that are created arbitrarily, is there any way for Python to know "oh yeah, I just made a 300, I'll just point y there instead of making another one".

Just curious! Thanks in advance.

Upvotes: 0

Views: 344

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799570

If it's done, the compiler handles it:

import dis

def f():
  a = 300
  b = 300

dis.dis(f)

print f.__code__.co_consts

Note the argument to LOAD_CONST each time:

  4           0 LOAD_CONST               1 (300)
              3 STORE_FAST               0 (a)

  5           6 LOAD_CONST               1 (300)
              9 STORE_FAST               1 (b)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE        
(None, 300)

Upvotes: 1

Related Questions