How to know if an object is mutable?

Gerhard Häring gerhard.haering at gmx.de
Mon Oct 14 14:21:13 EDT 2002


sismex01 at hebmex.com wrote in comp.lang.python:
> Greetings,
> 
> The subject says it all: How to know (in advance) if an
> object is mutable?

One method is to look if it is hashable. If it is hashable, it better
be immutable, too.

A rough sketch:

def isImmutable(obj):
    try:
        hash(obj)
        return True
    except TypeError:
        return False

The reason I'm not simply checking for hasattr(obj, "__hash__") is
that obj might be an old-style type where hasattr doesn't work this
way.

-- Gerhard



More information about the Python-list mailing list