Home > Enterprise >  How can I use the value of a variable as a keyword in a function definition?
How can I use the value of a variable as a keyword in a function definition?

Time:11-29

I'm passing an object to a function definition and would like to use the object as the 'key' within another function call but I'm unsure on how to do this.

Below is an example of what I'm trying to achieve as I'm not sure on how this can be done.

def _read(self, x):
    return self.query.filter_by(x=self.y)

CodePudding user response:

You can pass keyword arguments with runtime-dependent keys by wrapping the keywords arguments in a dictionary and then using argument unpacking:

def _read(self, x):
    return self.query.filter_by(**{x: self.y})
  • Related