So I saw a need for and came up with a class implementation to group constants, which I'm calling a Constant Class. I wondered if there existed other similar implementations or if there is a flaw in what I'm doing. My team is currently finding it fairly useful and thought we should see what other people thought. Also to offer out into the world if it indeed is useful to others.
The need was simple. We wanted to group constants as to allow auto-completion and also the ability to reference a list of all the values for validation. This mainly was for the development of an API backend which handle many groups of different types.
import inspect
import re
class ConstantClass(object):
""" Container class for meant for grouped constants """
@classmethod
def all(cls):
"""
Returns all constant values in class with the attribute requirements:
- only uppercase letters and underscores
- must begin and end with a letter
"""
regex = r'^[A-Z][A-Z_]*[A-Z]$'
class_items = inspect.getmembers(cls)
constants = filter(lambda item: re.match(regex, item[0]), class_items)
values = map(lambda constant: constant[1], constants)
return values
class TypeNames(ConstantClass):
TYPE_A = 'Whatever you want it to be'
TYPE_B = 'Another example'
TypeNames.TYPE_A # returns 'Whatever you want it to be'
TypeNames.all() # returns list of constant values
TypeNames.TYPE_A in TypeNames.all() # Returns True
Enums the closest thing but it requires we type out EnumClass.CONSTANT.value
(I honestly find kind of annoying) and there isn't a built-in function to get all the values. I don't know, maybe I'm splitting hairs here but I'm just curious if there is any draw-back to what I'm doing.
Enum
use-case than aConstant
use-case -- can you explain a little more why you don't want to useEnum
? \$\endgroup\$