在 Python 中强制复制一个小整数

Force copy of a small int in Python

作为一个玩具问题,我试图想出对象 a, b 使得

type(a) == type(b) == int # True
a + 1 == b + 1 == 1       # True
a is b                    # False

deepcopy似乎回到了 _deepcopy_atomic,正如所讨论的 here

是否可以在 Python 中创建一个 small int 的副本?

您问题的答案取决于您认为什么是 small int。根据 documentation:

The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object.

对于整数,第 a is b 行等同于 id(a) == id(b)。对于范围 [-5, 256],所有数字的 ID 都是预定义的,这意味着 ab 充当现有对象的别名。

a, b 满足您的条件 a + 1 == b + 1 == 1 的唯一方法是 a = b = 0。由于0在上述范围内,所以无法使a is breturnFalse.

我能够为 CPython 工作:

import ctypes

x = 2
y = 3

ctypes.c_int.from_address(id(y) + 24).value = x

print(x == y) # True
print(x is y) # False

我无法在不使解释器崩溃的情况下摆脱 x = 0x = 1

这可能不是问题的意图,但是如果允许覆盖int,则可以满足问题中的 3 个断言,这样以下代码将通过:

int = type('', (int,), dict(vars(int)))
a = int(0)
b = int(0)
assert type(a) == type(b) == int
assert a + 1 == b + 1 == 1
assert a is not b

是的,这是可能的,而且没有低级黑客或作弊:

>>> a = 0
>>> b = 9**99 % 9**99
>>> type(a) == type(b) == int
True
>>> a + 1 == b + 1 == 1
True
>>> a is b
False

我在本地使用 Python 3.8.1 执行此操作,但您也可以复制它 at repl.it and at www.python.org/shell/

小正数:

>>> a = 7
>>> b = (9**99 + a) % 9**99
>>> b, type(b), a == b, a is b
(7, <class 'int'>, True, False)

对于小底片:

>>> a = -2
>>> b = (9**99 + a) % -9**99
>>> b, type(b), a == b, a is b
(-2, <class 'int'>, True, False)