Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Pretty easy, all you have to do is to wrap a list.</p> <pre><code>class ImmutableList(object): def __init__(self, *args): self.__values = args; # internally we store the values in a list # make imuList[0] = 2 raise an error, just like a tuple would def __setitem__(self, index, value): raise TypeError('ImmutableList does not support item assignment') # del imuList[0] should also raise def __delitem__(self, index, value): raise TypeError('ImmutableList does not support item deletion')** # make our imuList indexable, also catch the normal index error and raise one # that tells that this is an immutable list, will make it easier to debug :) def __getitem__(self, index): try: return self.__values[index] except IndexError: raise IndexError('ImmutableList index out of range') # the usual stuff def __repr__(self): return repr(self.__values) def __str__(self): return str(self.__values) # create a new imulist e = ImmutableList(1, 2, 3, 4) # works! print e[0] # raises an error e[0] = 5 # raises another error print e[9] </code></pre> <p>Now all you have to do is to modify <code>self._values</code> inside the class. One last advise, it's still possible to mess with <code>self._values</code> from the outside, that because Python doesn't support <a href="https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private">private members</a>.</p> <p>You can take further measures against the manipulation of <code>__values</code> by subclassing from list directly, but that's more work and one can still fiddle around with the values by using <code>list.__setitem__(imListInstance, 0, 5)</code> and the like.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload