How do I create a constant in Python?

后端 未结 30 3019
既然无缘
既然无缘 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条回答
  •  野性不改
    2020-11-22 09:35

    There is a cleaner way to do this with namedtuple:

    from collections import namedtuple
    
    
    def make_consts(name, **kwargs):
        return namedtuple(name, kwargs.keys())(**kwargs)
    

    Usage Example

    CONSTS = make_consts("baz1",
                         foo=1,
                         bar=2)
    

    With this exactly approach you can namespace your constants.

提交回复
热议问题