import string
import random
def usage():
print(isimmutable(1))
print(isimmutable('Hello, world!'))
class C:
pass
print(isimmutable(C()))
print(isimmutable({'a': 1}))
print(isimmutable({'a'}))
print(isimmutable([]))
print(isimmutable(()))
def isimmutable(obj):
"""Check the obj is immutable or not by adding new attribute or sequence."""
while True:
attr_name = random_str()
if not hasattr(obj, attr_name):
break
try:
setattr(obj, attr_name, None)
except (AttributeError, TypeError):
pass
else:
delattr(obj, attr_name)
return False
if not hasattr(obj, '__iter__'):
return True
while True:
key_name = random_str()
if key_name not in obj:
break
try:
obj[key_name] = None
except (AttributeError, TypeError):
pass
else:
del obj[key_name]
return False
while True:
element = random_str()
if element not in obj:
break
try:
set.add(obj, element)
except (AttributeError, TypeError):
pass
else:
set.remove(obj, element)
return False
try:
list.append(obj, None)
except (AttributeError, TypeError):
pass
else:
list.pop(obj)
return False
return True
def random_str():
N = 5
return ''.join([random.choice(string.ascii_letters) for i in range(N)])
if __name__ == '__main__':
usage()