0

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

4
  • 1
    Why not to use value = '"%s"' % v always Commented Nov 11, 2012 at 16:35
  • Because the value that I am looking for may not be a string. If it is a datetime object or a float, then the comparison will fail. Commented Nov 11, 2012 at 16:37
  • 1
    Why do you never use value after calculating it? Commented Nov 11, 2012 at 16:37
  • i tried it with datetime and float it still works ok Commented Nov 11, 2012 at 16:40

2 Answers 2

3

I think what you might be after is:

value = repr(v)

Furthermore, your second half never uses value anyway.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.