Home > Mobile >  Minimize method calls - Python
Minimize method calls - Python

Time:09-20

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.

CodePudding user response:

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')]

CodePudding user response:

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.

  • Related