Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #59160
| References | <CAB6+5b_w+kBT=EDqd9wRO80am+Wp2DgrEqSpVEPWkcTAVmYQtQ@mail.gmail.com> <1384206048.30461.46091021.634F0FCA@webmail.messagingengine.com> <CAB6+5b-KZE1xWqyefFicRkk4xhr9aqSWvaOhvgHJGf0s4RpexQ@mail.gmail.com> |
|---|---|
| Date | 2013-11-12 18:12 +1100 |
| Subject | Re: 'isimmutable' and 'ImmutableNester' |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.2431.1384240366.18130.python-list@python.org> (permalink) |
On Tue, Nov 12, 2013 at 6:01 PM, Frank-Rene Schäfer <fschaef@gmail.com> wrote:
> A tuple is immutable but it may contain mutable objects. In larger
> hierarchies of objects it may become less obvious whether down
> the lines, there is some mutable object somewhere in the data tree.
>
> One can define a recursive function to check for immutability
> manually. However first, it may not be as efficient as if it was
> built-in. Second, the existence of a built-in function 'isimmutable'
> puts the concept of immutability some more into the spotlight.
>
> You might indeed implement some personal 'policy for copy/deepcopy'.
> But, how can you prevent the insertion of an object into the data
> tree which does not follow your copy/deepcopy convention? As soon
> as you allow members of type 'tuple' you must either check recursively
> or only allow ints and strings as tuple members.
>>> x=1,2,3
>>> hash(x)
-378539185
>>> x=1,2,[3]
>>> hash(x)
Traceback (most recent call last):
File "<pyshell#424>", line 1, in <module>
hash(x)
TypeError: unhashable type: 'list'
There's your recursive function!
def isimmutable(x):
try:
hash(x)
return True
except TypeError:
return False
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Re: 'isimmutable' and 'ImmutableNester' Chris Angelico <rosuav@gmail.com> - 2013-11-12 18:12 +1100
Re: 'isimmutable' and 'ImmutableNester' Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-11-12 11:14 +0000
Re: 'isimmutable' and 'ImmutableNester' Robert Kern <robert.kern@gmail.com> - 2013-11-12 14:00 +0000
csiph-web