Python constants class

class _const:
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
        pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError(f"Can't change const:{name}")
        if not name.isupper():
            raise self.ConstCaseError(f'const name {name} is not all uppercase')
        self.__dict__[name] = value


const = _const()

use

from constant import const
const.MY_CONSTANT = 1
const.MY_SECOND_CONSTANT = 2
const.MY_THIRD_CONSTANT = 'a'
const.MY_FORTH_CONSTANT = 'b'

Guess you like

Origin www.cnblogs.com/c-x-a/p/11929320.html