相关疑难解决方法(0)

构建自引用元组

在多年前在一个论坛中看到一个从未解决过的对话之后,它让我想知道如何正确地创建一个引用自身的元组.从技术上讲,这是一个非常糟糕的主意,因为元组应该是不可变的.一个不可变对象怎么可能包含自己呢?但是,这个问题不是关于最佳实践,而是关于Python中可能的内容的查询.

import ctypes

def self_reference(array, index):
    if not isinstance(array, tuple):
        raise TypeError('array must be a tuple')
    if not isinstance(index, int):
        raise TypeError('index must be an int')
    if not 0 <= index < len(array):
        raise ValueError('index is out of range')
    address = id(array)
    obj_refcnt = ctypes.cast(address, ctypes.POINTER(ctypes.c_ssize_t))
    obj_refcnt.contents.value += 1
    if ctypes.cdll.python32.PyTuple_SetItem(ctypes.py_object(array),
                                            ctypes.c_ssize_t(index),
                                            ctypes.py_object(array)):
        raise RuntimeError('PyTuple_SetItem signaled an error')
Run Code Online (Sandbox Code Playgroud)

前一个函数旨在访问Python的C API,同时牢记内部结构和数据类型.但是,运行该函数时通常会生成以下错误.通过未知的过程,之前可以通过类似的技术创建自引用元组.

问题:如何self_reference修改功能以始终如一地工作?

>>> import string
>>> a = tuple(string.ascii_lowercase)
>>> self_reference(a, 2)
Traceback (most recent call last):
  File …
Run Code Online (Sandbox Code Playgroud)

python ctypes tuples creation self-reference

14
推荐指数
3
解决办法
1242
查看次数

标签 统计

creation ×1

ctypes ×1

python ×1

self-reference ×1

tuples ×1