How do I create a constant in Python?

后端 未结 30 3169
既然无缘
既然无缘 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:21

    I am trying different ways to create a real constant in Python and perhaps I found the pretty solution.

    Example:

    Create container for constants

    >>> DAYS = Constants(
    ...     MON=0,
    ...     TUE=1,
    ...     WED=2,
    ...     THU=3,
    ...     FRI=4,
    ...     SAT=5,
    ...     SUN=6
    ... )   
    

    Get value from container

    >>> DAYS.MON
    0
    >>> DAYS['MON']
    0  
    

    Represent with pure python data structures

    >>> list(DAYS)
    ['WED', 'SUN', 'FRI', 'THU', 'MON', 'TUE', 'SAT']
    >>> dict(DAYS)
    {'WED': 2, 'SUN': 6, 'FRI': 4, 'THU': 3, 'MON': 0, 'TUE': 1, 'SAT': 5}
    

    All constants are immutable

    >>> DAYS.MON = 7
    ...
    AttributeError: Immutable attribute
    
    >>> del DAYS.MON 
    ...
    AttributeError: Immutable attribute
    

    Autocomplete only for constants

    >>> dir(DAYS)
    ['FRI', 'MON', 'SAT', 'SUN', 'THU', 'TUE', 'WED']
    

    Sorting like list.sort

    >>> DAYS.sort(key=lambda (k, v): v, reverse=True)
    >>> list(DAYS)
    ['SUN', 'SAT', 'FRI', 'THU', 'WED', 'TUE', 'MON']
    

    Copability with python2 and python3

    Simple container for constants

    from collections import OrderedDict
    from copy import deepcopy
    
    class Constants(object):
        """Container of constant"""
    
        __slots__ = ('__dict__')
    
        def __init__(self, **kwargs):
    
            if list(filter(lambda x: not x.isupper(), kwargs)):
                raise AttributeError('Constant name should be uppercase.')
    
            super(Constants, self).__setattr__(
                '__dict__',
                OrderedDict(map(lambda x: (x[0], deepcopy(x[1])), kwargs.items()))
            )
    
        def sort(self, key=None, reverse=False):
            super(Constants, self).__setattr__(
                '__dict__',
                OrderedDict(sorted(self.__dict__.items(), key=key, reverse=reverse))
            )
    
        def __getitem__(self, name):
            return self.__dict__[name]
    
        def __len__(self):
            return  len(self.__dict__)
    
        def __iter__(self):
            for name in self.__dict__:
                yield name
    
        def keys(self):
            return list(self)
    
        def __str__(self):
            return str(list(self))
    
        def __repr__(self):
            return '<%s: %s>' % (self.__class__.__name__, str(self.__dict__))
    
        def __dir__(self):
            return list(self)
    
        def __setattr__(self, name, value):
            raise AttributeError("Immutable attribute")
    
        def __delattr__(*_):
            raise AttributeError("Immutable attribute")
    
    

提交回复
热议问题