[ How to convert a Python object into the correct string representation ]
Debate abounds about using "hasattr" or "isinstance to determine the type of an object. However, I have a situation where I am trying to build a query for numexpr
and I need to quote strings, but not other values. I was going to use the following code:
def get_query(key_map):
"""
Generate an equality query, based on key/value
pair in key_map
"""
stmnt = ""
for k,v in key_map.items():
value = '"%s"' % v if isinstance(v, str) else v
if not stmnt:
# first equality in statement
stmnt = "'(%s == %s)" % (k,value)
else:
stmnt += " & (%s == %s)" % (k,value)
if stmnt:
# close statement
stmnt += "'"
return stmnt
I considered using hasattr
as well:
value = '"%v"' % v if hasattr(v,'lower') else v
I had a music teacher once tell me it's OK to break the rules as long as you know how to break them correctly. This seems like one of those cases to me. Does anyone have a suggestion for a more Pythonic way to implement this bit of code?
Sample Inputs:
key_map = {'symbol':'APPL', 'price':698.38'}
In the sample, above I want to quote APPL because it is a string, but not 698.38, because it is a float.
Regards
Answer 1
I think what you might be after is:
value = repr(v)
Furthermore, your second half never uses value
anyway.
Answer 2
One thing that strikes me however is your quotation marks. Suppose the string you're wrapping in quotation marks already contains quotation marks. @Eric's proposed answer takes care of that for you, it'll correctly handle escaping the quotation marks in the string should there be any.