I'm searching for a collection that can be used to store multiple constants and also can be used to get a list of them?
EDIT: It does not have to be constants, it can be variables.
I want to get a value this way:
Constants.first_one
But also get a list of values like:
Constants.values
Which returns something like:
['First one', 'Second one' .... ]
Using a class and class attributes is good for the first usage but not for the second one:
class Constants:
first_one = 'First one'
second_one = 'Second one'
To get a list of attributes I'd need to make a method that does that.
I'm also considering named tuple but I again don't know how to get the list of values:
class Constants(typing.NamedTuple):
first_one = 'First one'
second_one = 'Second one'
EDIT:
Enum does not seem to have such option neither and moreover I need to get values this way Constants.first_one.value
EDIT2:
Basically, all I want is to know if there is some collection that behaves like this:
class Properties:
PHONE = 'phone'
FIRSTNAME = 'firstname'
LASTNAME = 'lastname'
@classmethod
@property
def values(cls):
return [x for x in dir(cls) if not x.startswith('__') and x != 'values']
print(Properties.PHONE)
> phone
print(Properties.FIRSTNAME)
> firstname
print(Properties.values)
> ['phone', 'firstname', 'lastname']
Given that no one answered yet heres my two cents:
A) You're going the wrong way around.
Instead of a @property returning a list of your attributes, implement a
__getattr__/__setattr__to access your stored data by attribute (by dot-notation).B) Take a look at something called a 'bunch'.
Bunches are a subclass of a dict, that expose their content as attribute while retaining the benefits of a dictionary. E.g. they provide the .values() method, allow key-access and attribute-access, and they are true dictionaries. There are multiple libraries implementing their own versions of it, for example "bunch" on pypi or github.
Example
The easiest implementation of a bunch, which I can come up with, is done by mangling the instance into its own
__dict__slot. Given its simplicity, I imagine it being somewhat common, even though it is certainly not the best:A better version would add the actual data in a (possibly private) attribute and implement custom
__getattr__/__setattr__/__delattr__as mentioned above. This need no longer be a 'bunch', and indeed in your case a bunch would probably be unnecessary...... but as stated above in B) there are libraries that do that for you. The 'bunch' type would solve your problem (even my crude one) and the 'bunch'-library mentioned above would add functionality you might find useful (like 'bunchify', 'to_yaml', 'from/to dict', etc.).
There may also be options with pydantic or with data classes.