def __init__(self):

Chris Angelico rosuav at gmail.com
Tue Apr 26 13:04:07 EDT 2016


On Wed, Apr 27, 2016 at 2:59 AM, Chris Kaynor <ckaynor at zindagigames.com> wrote:
> On Tue, Apr 26, 2016 at 9:32 AM, Steven D'Aprano <steve at pearwood.info>
> wrote:
>
>> Subclassing immutable built-ins is the most obvious and simple (and
>> probably
>> common) way to get an immutable class. Actually immutable, short of doing
>> wicked things with ctypes.
>>
>
> By wicked things with ctypes, do you mean something like this? By no means
> do I suggest this actually be used by anybody for any reason.
>
> Tested with '2.7.10 (default, Jul 14 2015, 19:46:27) \n[GCC 4.2.1
> Compatible Apple LLVM 6.0 (clang-600.0.39)]'
>
> import ctypes
> def changeTuple(tuple, index, newValue):
>     obj = ctypes.cast(id(tuple), ctypes.POINTER(ctypes.c_long))
>     obj[3+index] = id(newValue)
>
>>>> a = ('a','b','c')
>>>> changeTuple(a, 0, 1)
>>>> a
> (1, 'b', 'c')
>>>> changeTuple(a, 1, 3)
>>>> a
> (1, 3, 'c')

Yeah. By the look of things, you've just destroyed the reference counts.

>>> a = ('a','b','c')
>>> b = object()
>>> changeTuple(a, 0, b)
>>> a
(<object object at 0x7f1240b22080>, 'b', 'c')
>>> del b
>>> a
Segmentation fault

ChrisA



More information about the Python-list mailing list