Python中的全局常量3



我有一些用Python2.7编写的代码,我需要将其转换为Python3。我的问题是我用了这个https://code.activestate.com/recipes/65207-constants-in-python/为了创建一个函数来存储我的所有常量并使它们全局可用,它还防止了它们被更改。该代码在Python3中不起作用,什么是最好的替代品?谢谢米克下面是一个在2.7中运行的示例,但如果我更改打印语句并在3 中运行,则会失败

# const.py
class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if self.__dict__.has_key(name):
raise self.ConstError, "Can't rebind const(%s) look at the log, it should only be set in constants.py"%name
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

#constants.py
import const as gc
gc.PASS = 0
gc.FAIL = -1
gc.INT_VAL = 1234
gc.STR_VAL = 'This is a string'
# test.py
import const as gc    # global constants class
from constants import *   # constants values
print 'INT_VAL is ',  gc.INT_VAL
print 'STR_VAL is ',  gc.STR_VAL

我很快移植了旧的const.py。请注意,如果它不在名为const.py的文件中,它将无法工作!

class _const:
class ConstError(TypeError): pass
def __setattr__(self,name,value):
if name in self.__dict__:
raise self.ConstError(f"Can't rebind const({name})")
self.__dict__[name]=value
import sys
sys.modules[__name__]=_const()

更改:

  • 在提升中向ConstError构造函数添加了括号
  • 已将字符串格式更改为f-string(不必要的更改,如果需要可以恢复(
  • in替换__haskey__

最新更新