Search code examples
pythonclassclass-method

Return all class variable values from a Python Class


I have a Python class that contains all the AWS regions. I wrote a class method that would return me the list of all the regions. Is there a better way of returning all the class variable values so I don't have to hard-code all the values in the return statement like I am doing in the example below?

class AwsRegion():
    '''
    Class to define AWS Regions
    '''
    OHIO = 'us-east-2'
    NORTH_VIRGINIA = 'us-east-1'
    NORTH_CALIFORNIA = 'us-west-1'
    OREGON = 'us-west-2'
    MUMBAI = 'ap-south-1'
    SEOUL = 'ap-northeast-2'
    SINGAPORE = 'ap-southeast-1'
    SYDNEY = 'ap-southeast-2'
    TOKYO = 'ap-northeast-1'
    FRANKFURT = 'eu-central-1'
    IRELAND = 'eu-west-1'
    LONDON = 'eu-west-2'
    SAO_PAULO = 'sa-east-1'

    @classmethod
    def all(cls, ):
        return [AwsRegion.OHIO, AwsRegion.NORTH_VIRGINIA, AwsRegion.NORTH_CALIFORNIA, AwsRegion.OREGON, \
            AwsRegion.MUMBAI, AwsRegion.SEOUL, AwsRegion.SINGAPORE, AwsRegion.SYDNEY, AwsRegion.TOKYO, \
            AwsRegion.FRANKFURT, AwsRegion.IRELAND, AwsRegion.LONDON, AwsRegion.SAO_PAULO]

Solution

  • In this case, you can enumerate all the attributes of the class that are uppercase; I'd use the vars() function to access the class namespace:

    @classmethod
    def all(cls):
        return [value for name, value in vars(cls).items() if name.isupper()]
    

    Demo:

    >>> class AwsRegion():
    ...     '''
    ...     Class to define AWS Regions
    ...     '''
    ...     OHIO = 'us-east-2'
    ...     NORTH_VIRGINIA = 'us-east-1'
    ...     NORTH_CALIFORNIA = 'us-west-1'
    ...     OREGON = 'us-west-2'
    ...     MUMBAI = 'ap-south-1'
    ...     SEOUL = 'ap-northeast-2'
    ...     SINGAPORE = 'ap-southeast-1'
    ...     SYDNEY = 'ap-southeast-2'
    ...     TOKYO = 'ap-northeast-1'
    ...     FRANKFURT = 'eu-central-1'
    ...     IRELAND = 'eu-west-1'
    ...     LONDON = 'eu-west-2'
    ...     SAO_PAULO = 'sa-east-1'
    ...     @classmethod
    ...     def all(cls):
    ...         return [value for name, value in vars(cls).items() if name.isupper()]
    ...
    >>> AwsRegion.all()
    ['us-east-2', 'us-east-1', 'us-west-1', 'us-west-2', 'ap-south-1', 'ap-northeast-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'eu-west-2', 'sa-east-1']