Reputation: 3349
I have the following TOML:
[gps]
measurement = "gps"
tags = ["lat", "lon", "alt"]
limit = 10
which translates to the following dictionary in Python:
{
"gps": {
"measurement": "gps",
"tags": [ "lat", "lon", "alt"],
"limit": 10
}
I have a class where I wish to create a member function read_gps
as follows:
**kwargs
from above dict select "lat", "lon", "alt", from "gps" limit 10
class dbClass:
def __init__(self, db=None, **kwargs):
self.kwargs = kwargs # this kwargs is different from the above kwargs
# do some initialization stuff here
def read_gps(self, **kwargs):
# pass the above mentioned dict here
# instance_dbClass.read_gps(gps_dict)
_data = kwargs
_tags = kwargs.get('tags')
print('select "{}","{}","{}" from "{}" limit {}'.format(*_tags,
_data.get('measurement'),
_data.get('limit'))
)
But I get the following error:
SyntaxError: only named arguments may follow *expression
On the contrary, if i remove the measurement
and limit
it would work fine.
What is a pythonic way to achieve this? should i create two different strings and then in the end concatenate them?
query = """
select "{}", "{}", "{}" from "{}" limit {}
""".format(_tags[0], _tags[1], _tags[2], _data.get('measurement'),
_data.get('limit'))
print(query)
works however it there a way to use the *
unpacking for tuple within the .format()
along with the other values
Upvotes: 0
Views: 559
Reputation: 1133
Your code will work in Python version 3.5+, following Pep 448. If you have to use a version lower than 3.5, you can use named parameters:
print(select "{}","{}","{}" from "{measurement}" limit {limit}'.format(*_tags, measurement=measurement, limit=limit))
Alternatively, join the _tags
into a single string first:
print('select "{}" from "{}" limit {}'.format('","'.join(_tags), measurement, limit))
The second option will work even if the length of _tags
changes.
Upvotes: 3