In Python, everything is an object. I’m fine with this. If I inspect a list or even a float, I can see there is a class associated with that data. But at the end of the day, if I make an value
x = 1
, there has to be a value of 1 somewhere. If the class has an attribute “value” like this:
class int:
self.__init__(value):
self.value = value
value has to have some meaning. If it tried to make another int, we would end up in some infinite recursion.
Is there some sort of base type I’m missing? At some point, there must be a raw value to represent literals.
2
There is a value of 1, but it’s buried in the implementation. In CPython, for example, you can see the definition of the int
type in https://github.com/python/cpython/blob/main/Objects/longobject.c (not intobject.c
for historical reasons). The comments go into detail about how it works, but the gist of it is that an integer is stored as an array of 30-bit values, each value serving as a “digit” in a very-high-base representation of the number.
The literal 1
itself refers to an instance of type int
that the implementation creates as necessary. In CPython, at the C level, this is a value of type PyObject
.
Put another way, the literal 1
is not an object; it’s a syntactic construct that acts as a reference to an int
object that represents the integer 1, just like x
does after the assignment x = 1
.
1