How do I create a constant in Python?

后端 未结 30 2670
既然无缘
既然无缘 2020-11-22 09:07

Is there a way to declare a constant in Python? In Java we can create constant values in this manner:

public static          


        
30条回答
  •  -上瘾入骨i
    2020-11-22 09:44

    I've recently found a very succinct update to this which automatically raises meaningful error messages and prevents access via __dict__:

    class CONST(object):
        __slots__ = ()
        FOO = 1234
    
    CONST = CONST()
    
    # ----------
    
    print(CONST.FOO)    # 1234
    
    CONST.FOO = 4321              # AttributeError: 'CONST' object attribute 'FOO' is read-only
    CONST.__dict__['FOO'] = 4321  # AttributeError: 'CONST' object has no attribute '__dict__'
    CONST.BAR = 5678              # AttributeError: 'CONST' object has no attribute 'BAR'
    

    We define over ourselves as to make ourselves an instance and then use slots to ensure that no additional attributes can be added. This also removes the __dict__ access route. Of course, the whole object can still be redefined.

    Edit - Original solution

    I'm probably missing a trick here, but this seems to work for me:

    class CONST(object):
        FOO = 1234
    
        def __setattr__(self, *_):
            pass
    
    CONST = CONST()
    
    #----------
    
    print CONST.FOO    # 1234
    
    CONST.FOO = 4321
    CONST.BAR = 5678
    
    print CONST.FOO    # Still 1234!
    print CONST.BAR    # Oops AttributeError
    

    Creating the instance allows the magic __setattr__ method to kick in and intercept attempts to set the FOO variable. You could throw an exception here if you wanted to. Instantiating the instance over the class name prevents access directly via the class.

    It's a total pain for one value, but you could attach lots to your CONST object. Having an upper class, class name also seems a bit grotty, but I think it's quite succinct overall.

提交回复
热议问题