1

I am preparing a GraphQL query string in Python, I need to interpolate three variables in the string, there is just one problem. GraphQL contains a lot of curly brackets and it interferes with the way Python f strings work.

number = 10
owner = "me"
name = "my_repo"
query = f"""
query {
    repository(owner:"{owner}", name:"{repo}") {
      pullRequests(first: {number}) {
        edges {
          node {
            state
            merged
            createdAt
          }
        }
      }
    }
  }
"""

Code above raises SyntaxError. So I assume I need to drop using f strings altogether? Is there a way to still use f string in Python when it contains curly brackets unrelated to the interpolation?

Piotr Zakrzewski
  • 3,591
  • 6
  • 26
  • 28

1 Answers1

5

You can replace all { with {{ and similarly replace all } with }} and then run your f string.

To escape the curly brackets you simply add another on in Python. So for example:

x=3
print(f'x={{{x}}}')

That would print x={3}.

Salaah Amin
  • 382
  • 3
  • 14
  • 1
    Correct. Welcome to stackoverflow! :-) – jsbueno Dec 19 '20 at 15:30
  • thanks! Used it for ages, thought it's time I gave a little back! :) – Salaah Amin Dec 19 '20 at 15:32
  • 1
    I won't add another answer for this, but for the O.P.: if you have a lot of templates, and doubling all `{` would impair data readability, you can make use of a template package, like "jinja2" and have your JSON as jinja2 templates : `{name}` are left alone and `{{name }}` are used as replacement markups by default, and you get a lot more options like the ability to have templates in files, use simple loops and conditionals inside the templates themselves. – jsbueno Dec 19 '20 at 15:36
  • @jsbueno thanks! This indeed might end up being more readable. – Piotr Zakrzewski Dec 20 '20 at 08:38