This post will supply a const module for Python 3.
Python does not has any constant-related keywords for constant, in the book 《Python Cookbook》(2nd edition), some one author give a const module for Python 2, This post will supply a same const module for Python 3.
Define a const module for Python 3
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # -*- coding: utf-8 -*- # @Author: suifengtec # @Date: 2018-09-17 21:27:59 # @Last Modified by: suifengtec # @Last Modified time: 2018-09-17 22:21:40 # 用Python定义 const # Python 中没有 const 类型,也没有这个关键字 # import sys class _const: class ConstError(TypeError): pass def __setattr__(self, name, value): if name not in self.__dict__: self.__dict__[name] = value else: raise TypeError("Can't rebind const: const." + name) sys.modules[__name__] = _const() |
Testing the Python const Module
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | # -*- coding: utf-8 -*- # @Author: suifengtec # @Date: 2018-09-17 21:40:43 # @Last Modified by: suifengtec # @Last Modified time: 2018-09-17 22:10:48 # # python constT.py # # 定义 const # # https://codeyarns.com/2014/12/23/how-to-define-constant-in-python/ # # import sys import os # this is the above Python module import const def main(): try: const.a = 'AA' const.a = 'BB' const.b = 1997 print(const.a) except Exception as e: b = bytes(str(e), encoding='utf-8') print("Error: {0}".format(str(b, encoding='utf-8'))) e_type, e_obj, e_tb = sys.exc_info() fname = os.path.split(e_tb.tb_frame.f_code.co_filename)[1] print("{0}: {1} Line {2}".format(e_type, fname, e_tb.tb_lineno)) if __name__ == '__main__': main() |