0

I am trying to write a function that will print the values of a object but only those values that are defined in a list.

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
for alarm in alarms:
    print alarm.name

this will return a particular value for all alarms. How ever I want to make it work in such a way that I am able to print all the values that are defined in a list. Here is what I am trying to do

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
whitelist = ["name", "metric", "namespace"]
for alarm in alarms:
    print alarm.whitelist[0]

However this wont works of course. Any suggestion about what will be the best way to do that? SO that I am able to print everything that is defined in a whitelist.

2 Answers 2

2

You can use getattr (note that you are referring to attributes, or possibly methods, not functions):

for alarm in alarms:
    for attr in whitelist:
        print getattr(alarm, attr)

getattr takes an optional third argument, the default value in case attr isn't found, so you could do e.g.:

for attr in whitelist:
    print "{0}: {1}".format(attr, getattr(alarm, attr, "<Not defined>"))
Sign up to request clarification or add additional context in comments.

Comments

0

You can use the getattr() built-in function.

Your code would looks something like this:

import boto.ec2.cloudwatch
conn = boto.ec2.cloudwatch.connect_to_region('ap-southeast-1')
alarms = conn.describe_alarms()
whitelist = ["name", "metric", "namespace"]
for alarm in alarms:
    for attribute in whitelist:
        print(getattr(alarm, attribute))

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.