Can we still create new small int objects?

It used to be possible to create for example a new int object with value 1 this way:

x = (99**99 + 1) % 99**99
print(type(x), x == 1, x is 1)

Output in Python 3.8 (Try it online!):

<class 'int'> True False

That apparently got changed here, in Python 3.11 the is check now gives True:

Is it still possible to create new small int objects in some other way? (In a “nice” way, I mean, I guess I could still create a new int object with a larger value and use ctypes to change its value, but that’s ugh…)

Why do you want to create a new integer object? The identity of integer objects shouldn’t ever matter. Can you elaborate on this?

Well, I only used it a few times, and I think mostly to demonstrate that it’s possible. I only remember one time where I “seriously” used it to create a new object because I both needed the number and needed a “marker” object to identify something with certainty (similar to sentinel = object()), so I created a new number object to achieve both aspects.

Ah, that’s fair. I’d probably subclass int for that, since you presumably don’t need to do any arithmetic with it.

1 Like

The number was part of a result, so the user code getting that result might want to do arithmetic with it. But a subclass would allow that, no? This works:

x = type('', (int,), {})(1)
print(type(x), x == 1, x is 1)
print(x + 41)

Output in Python 3.11 (Attempt This Online!):

<class '__main__.'> True False

So type of course isn’t int, but I think that would’ve been ok in that use case. And the advantage is that it’s sure to give a new object, unlike the big-modulo hack.

Anyway, to be clear: I never used the big-modulo hack for something serious, even that use case I described was a toy thing. This is all just curiosity.

Yep, but it would lose its “flagginess”. That’s the usual complaint with subclassing builtins - it takes a lot of work to make arithmetic correctly return the subclass in all situations. But in this case, it will behave exactly as the “normal” integer would, and as soon as you do arithmetic, you just get back normal integers.

You may also want to consider IntEnum though, as it may be suitable for “it’s an integer, but it has special meaning too”.