In python, how can I check if a string-like object is mutable?

I have a function that takes a string argument.

I want to decide if I can safely keep the argument and be sure that it will not change. Therefore, I would like to check if it is not modified, for example, a result buffer()built from array.array(), or not.

I am currently using:

type(s) == str

Is there a better way to do this?

(copying an argument is too expensive, so I want to avoid it)

+5
source share
4 answers

, , . isinstance (x, str), , , . (, , , , .)


(. , , , , , .)

, , , . - .

>>> hash({})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: dict objects are unhashable

, , , , break; , python , :

hashabe: str (Immutable), buffer (Warning, immutable slice of (possibly) mutable object!)
unhashable: list, array.array
+4

isinstance(s, basestring)

Unicode.

+5

- , " , ". , .

+3

:

>>> s1 = "possibly mutable"
>>> 
>>> s2 = str(s1)
>>> s1 is s2
True

, s1 , , . , .

+3

All Articles