How to fix SyntaxError: f-string: expressions nested too deeply in python 3.7.0?

How to fix SyntaxError: f-string: expressions nested too deeply in python 3.7.0?

下面是我的代码片段。当 运行 python 3.7 中的代码时,我得到错误 SyntaxError: f-string: expressions nested too deeply。我应该如何重构我的代码?

    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'}}'
            )

您不能像 f'{f"my_var"}' 那样嵌套 f-string,因此您应该通过删除嵌套的 f 字符串并将它们分成更多的 f 字符串来重构您的代码。

所述:

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.

您可以使用 multi-line 个字符串 f"""This will work as expected with other nested strings '{3+5}'"""