简体   繁体   中英

Global variable not defined even though it appears in globals()

I wrote this code:

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

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

As you can see, I have defined tupleMain as a global variable, but when I try to use it outside the function, I get:

NameError: name 'tupleMain' is not defined

If I run:

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

The output is:

True

I just don't get why it says it's not defined if it's in globals() and have set it to global.

Thanks in advance

EDIT: I use the variable in the following function:

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)

You never called the function before using the global variable it declares in some other function, so the code inside the function which declares the variable as global never got executed. You need to at-least execute or call the function before referencing the global variable.

Either call the function before you use the global variable elsewhere or define the global variable at the module level inside your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM