0

Overview

In this simplified example I have a function that returns a string. The string is ultimately going to be used for a GraphQL mutation.

def updateHasura (description,url,user_id):    

    query = f"""
    mutation {{
      insert_post(objects: {{description: {description}, url: {url}, user_id: {user_id}}}) {{
        affected_rows
      }}
    }}
    """
    print(query)

When I call the function I need to wrap the double quotation marks with single ones in order for the function to return the desired string.

updateHasura('"test"','"test"','"1"')

Gives me the desired output:

mutation {
      insert_post(objects: {description: "test", url: "test", user_id: "1"}) {
        affected_rows
      }
    }

Question

I don't want to double wrap the text when calling the function i.e. '"test"'.

The nested curly brackets {{}} in the f-string are also less than ideal.

How can I simplify this function and still return the desired output? I'm happy to use another approach other than the f-string if it simplifies this.

1
  • I guess you could always do something like args = [arg.join('""') for arg in ['test', 'test', '1']] updateHasura(*args) but technically you still didn't get rid of using double quotation.
    – mapf
    Commented Apr 30, 2020 at 14:53

4 Answers 4

2

EDIT 2

Inspired by Ramon Moraes answer, I came up with another solution, which might be a good compromise:

def updateHasura(description, url, user_id):
    args = f'description: "{description}", url: "{url}", user_id: "{user_id}"'
    query = """
    mutation {
      insert_post(objects: args) {
        affected_rows
      }
    }
    """.replace('args', args)
    print(query)


updateHasura('test', 'test', '1')

Original Answer

To get rid of the double quotation, you could simply put the quotation marks in the f-string like so:

def updateHasura(description, url, user_id):

    query = f"""
    mutation {{
      insert_post(objects: {{description: "{description}", url: "{url}", user_id: "{user_id}"}}) {{
        affected_rows
      }}
    }}
    """
    print(query)

updateHasura('test', 'test', '1')

I don't see how you could get rid of the nested curly brackets though as long as you are using a formatted string.

EDIT

If you really want to not have nested curly brackets, I guess you could do this, but I would not recommend it:

    query = """
    mutation {
      insert_post(objects: {description: "{""" + description + """}", url: "{"""  + url + """}", user_id: "{""" + user_id + """}"}) {
        affected_rows
      }
    }
    """

or

    query = """
    mutation {
      insert_post(objects: {description: "%s", url: "%s", user_id: "%s"}) {
        affected_rows
      }
    }
    """ % (description, url, user_id)
1

An easy way to simplify your function and make it easier to write parameters would be to simply surround your usage of the parameters in quotes where they are used in the f string.

def updateHasura (description, url, user_id):
  query = f"""
  mutation {{
    insert_post(objects: {{description: "{description}", url: "{url}", user_id: "{user_id}"}}) {{
      affected_rows
    }}
  }}
  """
  print(query)

updateHasura('test','test','1')

This will give the same desired output but without needing to have nested quotes in your parameters.

mutation {
  insert_post(objects: {description: "test", url: "test", user_id: "1"}) {
    affected_rows
  }
}

Unfortunately, without writing your own function that parses the string itself, there's no way to keep the same conveniences the f string provides while avoiding the use of doubled up curly braces.

0

Just as an alternative to f-string, you can use str.format. You will still have to keep the nested curly brackets though.

query = """
mutation {{
  insert_post(objects: {{description: "{0}", url: "{1}", user_id: "{2}"}}) {{
    affected_rows
  }}
}}
"""

print(query.format("test", "test", "1"))
0

[1] - Since you passed a 1 i assume that the "user_id" us originally a int. So throw a sugarcoat and convert it inside if need.

[2] - Apparently you're trying to inject a JSON inside of your string. Based on that i think it's just easier to build it outside of the string and later inject it. This will give a lot more flexibility to update the code later:

[3] - After the code changes I see no point on try "force" a pattern using interpolation. It look clean and lean but on this case i think it's worth dropping it in favor a simple replace. It removes the need to extra { leaving your template more clear to read

import json


def updateHasura (description, url, user_id):
    if isinstance(user_id, int):  # [1]
        user_id = str(user_id)
    # [2]
    args = {
        'description': description,
        'url': url,
        'user_id': user_id,
        }
    args = json.dumps(args)
    query = '''
    mutation {
      insert_post(
        objects: args) {
        affected_rows
      }
    }
    '''
    return query.replace('args', args)  # [3]

print(updateHasura('test', 'test', '1'))
print(updateHasura('test', 'test', 1))

[4] If you really want to reduce a code even more you can force the user to pass all the params formatted and with the respective final key name and pull the kwargs straight to the dumps

import json


def updateHasura (**kwargs):  # 4
    query = '''
    mutation {
      insert_post(
        objects: args) {
        affected_rows
      }
    }
    '''
    return query.replace('args', json.dumps(kwargs))

print(updateHasura(description='test', url='test', user_id='1'))
1
  • I like your idea, but it adds additional quotes to the keys when they are placed inside the query. But maybe op is ok with that. Any way around it though?
    – mapf
    Commented May 1, 2020 at 9:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.