Search code examples
pythonclassinstance-variables

How to get a list of all values from instance variables in a python class


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?


Solution

  • 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'}