Constant in python

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

Constant in python
Constant in python
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 18 in Python
Singleton pattern in Python
File operations in Python
Key input in Python
Daily AtCoder # 33 in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Daily AtCoder # 24 in Python
case class in python
RNN implementation in python
Daily AtCoder # 8 in Python
File processing in Python
Elasticsearch Reindex in Python
Daily AtCoder # 42 in Python