Minimize method calls – Python

Question:

I have this method get_info when I pass a key and it gives me a value of it.

name = self.get_info("name_key")
age = self.get_info("age_key")
gender = self.get_info("gender_key")
hometown = self.get_info("hometown_key")
state = self.get_info("state_key")

I need to extract name, age, gender, hometown, state.

Is there any way I can get the values in a minimized way (reduce duplicate lines)?

I need to call the method again and again for each value.

Thanks for the help.

Asked By: Aman Raheja

||

Answers:

You can use a loop along with spread assignment.

name, age, gender, hometown, state = [self.get_info(x) for x in ('name_key', 'age_key', 'gender_key', 'hometown_key', 'state_key')]
Answered By: Barmar

Something like:

def new_get_info(keyLists):
    return tuple([self.get_info(key) for key in keyLists])

and call:

name, age = new_get_info(["name", "age"])

Hope this helps. You can query any parameter needed.

Answered By: Luc Nguyen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.