I have programmed in Python for a while, and just recently started using Ruby at work. The languages are very similar. However, I 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With