1

Below is my code snippet. When running the code in python 3.7 I get the error SyntaxError: f-string: expressions nested too deeply. How should I refactor my code?

    GRAPH_QL_FIELDS = """
                cubeId
                title
                deleted
                timeVariableFormat
                statisticalProgram {
                  name
                }
                topics{
                    topicId
                }
              }
    """

    query_topics = (
                f'query cubesWithTopicLink($deleted: Boolean!, $topicId: String, $first: Int, $skip: Int) {{'
                f'dataCubes(where:{AND:[{topics_some: {{topicId: $topicId}}}, {deleted: $deleted}]}, first: $first, skip: $skip) {{'
                f'{GRAPH_QL_FIELDS}'
                f'dataCubesConnection(where: {topics_some: {topicId: $topicId}})'
                f'{{aggregate{{count}}}}'
                f'}}'
            )
Jaana
  • 266
  • 1
  • 3
  • 14

2 Answers2

0

You could use multi-line strings f"""This will work as expected with other nested strings '{3+5}'"""

oropo
  • 30
  • 6
-1

You cannot nest f-string, like f'{f"my_var"}', so you should refactor your code by removing nested f-string and dividing them into more f-string.

As stated by Dimitris Fasarakis Hilliard:

I don't think formatted string literals allowing nesting (by nesting, I take it to mean f'{f".."}') is a result of careful consideration of possible use cases, I'm more convinced it's just allowed in order for them to conform with their specification.

The specification states that they support full Python expressions* inside brackets. It's also stated that a formatted string literal is really just an expression that is evaluated at run-time (See here, and here). As a result, it only makes sense to allow a formatted string literal as the expression inside another formatted string literal, forbidding it would negate the full support for Python expressions.

The fact that you can't find use cases mentioned in the docs (and only find test cases in the test suite) is because this is probably a nice (side) effect of the implementation and not it's motivating use-case.

Saeed
  • 3,255
  • 4
  • 17
  • 36