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)
Written by Iain Campbell
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#