开发者

Freeze in Python?

I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I开发者_StackOverflow just came across a Ruby feature that I don't know how to replicate in Python. It's Ruby's freeze method.

irb(main):001:0> a = [1,2,3]
=> [1, 2, 3]
irb(main):002:0> a[1] = 'chicken'
=> "chicken"
irb(main):003:0> a.freeze
=> [1, "chicken", 3]
irb(main):004:0> a[1] = 'tuna'
TypeError: can't modify frozen array
        from (irb):4:in `[]='
        from (irb):4

Is there a way to imitate this in Python?

EDIT: I realized that I made it seem like this was only for lists; in Ruby, freeze is a method on Object so you can make any object immutable. I apologize for the confusion.


>>> a = [1,2,3]
>>> a[1] = 'chicken'
>>> a
[1, 'chicken', 3]
>>> a = tuple(a)
>>> a[1] = 'tuna'
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    a[1] = 'tuna'
TypeError: 'tuple' object does not support item assignment

Also, cf. set vs. frozenset, bytearray vs. bytes.

Numbers, strings are immutable themselves:

>>> a = 4
>>> id(a)
505408920
>>> a = 42        # different object
>>> id(a)
505409528


You could always subclass list and add the "frozen" flag which would block __setitem__ doing anything:

class freezablelist(list):
    def __init__(self,*args,**kwargs):
        list.__init__(self, *args)
        self.frozen = kwargs.get('frozen', False)

    def __setitem__(self, i, y):
        if self.frozen:
            raise TypeError("can't modify frozen list")
        return list.__setitem__(self, i, y)

    def __setslice__(self, i, j, y):
        if self.frozen:
            raise TypeError("can't modify frozen list")
        return list.__setslice__(self, i, j, y)

    def freeze(self):
        self.frozen = True

    def thaw(self):
        self.frozen = False

Then playing with it:

>>> from freeze import freezablelist as fl
>>> a = fl([1,2,3])
>>> a[1] = 'chicken'
>>> a.freeze()
>>> a[1] = 'tuna'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "freeze.py", line 10, in __setitem__
    raise TypeError("can't modify frozen list")
TypeError: can't modify frozen list
>>> a[1:1] = 'tuna'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "freeze.py", line 16, in __setslice__
    raise TypeError("can't modify frozen list")
TypeError: can't modify frozen list
>>>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜