Is there a way in Python to create immutable objects like C and C ++ const constants? When I looked at the Python CookBook and introduced const, I was able to prevent reassignment, but since the dictionary itself can be manipulated, it does not work as expected.
I also want to make the state of the object immutable. Please let me know if there is a general and good method.
Code from the cookbook
qiita.rb
puts 'The best way to log and share programmers knowledge.'
const.py
## -*- coding: utf-8 -*-
class _const(object):
class ConstError(TypeError):pass
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError("Can't rebind const(%s)" % name)
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise self.ConstError("Can't unbind const(%s)" % name)
raise NameError(name)
import sys
sys.modules[__name__] = _const()
Test program
const_test.py
# -*- coding: utf-8 -*-
import const
#First assignment is OK
const.dic = {'a':'b'}
#This is an error
# const.dic = {'c':'d'}
#Can be added
const.dic['c'] = 'd'
#Can be deleted
del const.dic['a']
print const.dic
Recommended Posts