Last Updated: February 25, 2016
·
2.212K
· iaincampbell

Dynamic parameter substitution in Python

When substituting a variable for a parameter name, things aren't as obvious as you might expect. The SQLAlchemy example below illustrates this.

What we're trying to achieve in this case is:

params(name='bob')

The way we approach it throws a ValueError as it (correctly) interprets the parameter name as a string rather than a parameter and value:

field = 'name'
value = 'bob'
params = "%s='%s'"%(field, value)
query = query.params(params)

The solution is to pass the key/value pair to the function call as **kwargs:

params = {
    'name': 'bob'
}
query = query.params(**params)