首页 > 解决方案 > 全局变量未定义,即使它出现在 globals()

问题描述

我写了这段代码:

def openFile():
  f = open("test.txt", "r")
  mainInput = f.read()

  global tupleMain
  tupleMain = [tuple(mainInput.split(" ")) for mainInput in mainInput.strip(",").split("\n")]

如您所见,我已将 tupleMain 定义为全局变量,但是当我尝试在函数外部使用它时,我得到:

NameError: name 'tupleMain' is not defined

如果我运行:

is_global = "tupleMain" in globals()
print(is_global)

输出是:

True

我只是不明白为什么它说如果它在 globals() 中并已将其设置为全局则未定义。

提前致谢

编辑:我在以下函数中使用变量:

def tableFunction():

  fname = [x[2] for x in tupleMain]
  sname = [x[3] for x in tupleMain]
  position = [x[1] for x in tupleMain]
  salary = [x[4] for x in tupleMain]
  team = [x[0] for x in tupleMain]


  playerTable = PrettyTable()

  playerTable.field_names= ["Surname", "First Name", "Salary", "Position", "Team"]

  for x in tupleMain:
      playerTable.add_row([x[3], x[2], x[4], x[1], x[0]])
    


  print(playerTable)

标签: python

解决方案


在使用它在其他函数中声明的全局变量之前,您从未调用过该函数,因此函数内声明该变量的代码global从未被执行。在引用全局变量之前,您至少需要执行或调用该函数。

在其他地方使用全局变量之前调用该函数,或者在代码中的模块级别定义全局变量。


推荐阅读