0

I have a class that looks like this:

class HTTP_HEADERS:
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

To get all the variable names out of the class I can do something along the lines of:

members = [
        attr for attr in dir(HTTP_HEADER)
        if not callable(getattr(HTTP_HEADER, attr))
        and not attr.startswith("__")
    ]

This will return a list of variable names, like so:

["ACCEPT", "DECLINE"]

Now what I want to do, is get the values of those variables into a list. For example the output should be:

["X-Accept", "X-Decline"]

How can I do this successfully?

2
  • It looks like you should be using enum Commented Aug 14, 2019 at 19:04
  • Note, you aren't working with instance variables here .. Commented Aug 14, 2019 at 19:47

3 Answers 3

2

If you have this:

class HTTP_HEADER:
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

names = ["ACCEPT", "DECLINE"]

Getting the values is simply a matter of

values = [getattr(HTTP_HEADER, name) for name in names]

I think a dictionary is more appropriate though, and it can be done with minimal change to your original code:

members = {
        k: v for k, v in vars(HTTP_HEADER).items()
        if not callable(v)
        and not k.startswith("__")
    }

which gives

{'ACCEPT': 'X-Accept', 'DECLINE': 'X-Decline'}
Sign up to request clarification or add additional context in comments.

Comments

1

You should define this as an Enum.

class HTTP_HEADERS(enum.Enum):
    ACCEPT = "X-Accept"
    DECLINE = "X-Decline"

Now you can simply do:

[x.value for x in HTTP_HEADERS]

Comments

0

Use getattr again to access class variable

[getattr(HTTP_HEADERS,m) for m in members]

Output

['X-Accept', 'X-Decline']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.