【问题标题】:How to fix SyntaxError: f-string: expressions nested too deeply in python 3.7.0?如何修复 SyntaxError: f-string: 在 python 3.7.0 中嵌套太深的表达式?
【发布时间】:2020-11-13 08:10:22
【问题描述】:

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

【问题讨论】:

  • 是的,你应该重构你的代码。

标签: python f-string


【解决方案1】:

你可以使用多行字符串f"""This will work as expected with other nested strings '{3+5}'"""

【讨论】:

    【解决方案2】:

    你不能嵌套f-string,就像f'{f"my_var"}'一样,所以你应该重构你的代码,去掉嵌套的f-string并将它们分成更多的f-string。

    Dimitris Fasarakis Hilliard所述:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-29
      • 2022-01-13
      • 2022-01-24
      • 2021-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多