Home > Net >  Get hold of variable value combining two strings
Get hold of variable value combining two strings

Time:02-26

I would like to have dynamic parameters for a API im using. For that im searching for a easy way to achive the following:

def __init__(self):
    self.search_param_list = [from, to]
    self.from = A
    self.to = B

def search_params2(self):
    parameters = {parameter: self.parameter for parameter in self.search_param_list}
    return parameters

The output is expectet to look something like this:

parameters ={"from": A, "to": B}

I do this to change the params in the init if wanted, but that i dont have to do it if not nessesary.

CodePudding user response:

from is an illegal variable name. Use from_ or something else.

Save the names to be searched as strings.

Access instance attributes via string-name with getattr.

class A:
    def __init__(self):
        self.x = 1
        self.from_ = 2
        self.to = 3
        self.search_param_list = ['from_', 'to']

    def search_params2(self):
        return {p: getattr(self, p) for p in self.search_param_list}

Demo:

>>> A().search_params2()
{'from_': 2, 'to': 3}

Of course, you can get all instance variables immediately with vars.

>>> vars(A())
{'x': 1, 'from_': 2, 'to': 3, 'search_param_list': ['from_', 'to']}
  • Related