ILostMySpoon
ILostMySpoon

Reputation: 2409

Concatenating object with attribute as String

I have the following function that takes in a response, a CallableInterface object, and an attribute as a String.

def assert_response(response, api, expectedResponse):
    # api = self.Startup
    # expectedResponse = "ERROR_NOT_SUPPORTED"
    eval(api + "." + expectedResponse) 

The line seen above should evaluate to an attribute call as such:

self.Startup.ERROR_NOT_SUPPORTED

However, I am getting the following error because the value contained in expectedResponse is not being expanded.

AttributeError: 'CallableInterface' object has no attribute 'expectedResponse'

Any suggestions on how to work around this?

Upvotes: 0

Views: 72

Answers (1)

bosnjak
bosnjak

Reputation: 8614

You should use getattr to access object attributes:

getattr(api, expectedResponse)

If the api is an object (i.e. self.Startup) which attribute is named as the value of expectedResponse, that should do it.

But before anything, make sure that contents of expectedResponse is actually what you think it is, by printing it beforehand.

Upvotes: 1

Related Questions