-1

下面是我的代码片段。在 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'}}'
            )
4

1 回答 1

0

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

正如Dimitris Fasarakis Hilliard所说:

我不认为允许嵌套的格式化字符串文字(通过嵌套,我认为它的意思是 f'{f".."}')是仔细考虑可能的用例的结果,我更相信它只是允许在令他们符合他们的规范。

规范声明它们支持括号内的完整 Python 表达式*。它还指出,格式化的字符串文字实际上只是在运行时评估的表达式(请参阅此处此处)。因此,只有允许格式化字符串文字作为另一个格式化字符串文字中的表达式才有意义,禁止它会否定对 Python 表达式的完全支持。

您找不到文档中提到的用例(并且只能在测试套件中找到测试用例)这一事实是因为这可能是实现的一个很好的(副作用),而不是激励用例。

于 2020-11-13T09:26:03.167 回答