def __init__(self):

Chris Kaynor ckaynor at zindagigames.com
Tue Apr 26 13:13:40 EDT 2016


On Tue, Apr 26, 2016 at 10:04 AM, Chris Angelico <rosuav at gmail.com> wrote:

> 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
>

Yah, if you really wanted to make it work properly, you'd need to incref
the newValue, while decref the oldValue. The incref would not be that
difficult, but the decref would be more challenging, as you may have to
also destroy the old object, though that might be possible by casting it
back to a python object without the incref,. One way or the other, I did
not exactly spend a ton of time to make it work properly :)



More information about the Python-list mailing list