0

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']
Milano
  • 16,084
  • 32
  • 124
  • 293
  • 1
    Does this answer your question? [How to make dictionary read-only in Python](https://stackoverflow.com/questions/19022868/how-to-make-dictionary-read-only-in-python) – Thomas Weller Dec 08 '21 at 11:35
  • @ThomasWeller I don't think so. It does not have to be non-editable but I want to be able to call values as attributes (not by getitem) as I want IDE to autocomplete the variables. – Milano Dec 08 '21 at 11:37
  • Then I got the word "constant" wrong. For me, a constant is non-editable. The IDE syntax highlighting and autocompletion is also an aspect that is not mentioned in the question yet. – Thomas Weller Dec 08 '21 at 11:42
  • [`dir()`](https://docs.python.org/3/library/functions.html#dir) may be related: it lists all names. You just need to exclude the dunder ones (`__`) – Thomas Weller Dec 08 '21 at 11:45
  • @ThomasWeller Yes, that's one way to do that. I was curious if there is something built-in or some module that does that. I've added an example at the bottom of the question now. – Milano Dec 08 '21 at 11:50

0 Answers0