Search code examples
pythonclasstkinterreturn

When returning a function I am getting TypeError: invalid file


I am trying to use a variable in one class in another. I am doing this by returning a function then accessing it in the other class.

My program is trying to display a csv file in a gui using python tkinter.

But all I am getting is this:

TypeError: invalid file:<< function NewSession.returnCsvFileDir at 0x0363E228 >>

File "\cur-fsm\2011$\userdata\11azama\COMPUTER SCIENCE PROJECT\Project (NEW VERSIONS) (1)\NEW PROJECT V7\MainApplication.py", line 188, in showCSV with open(testCSV, newline = "") as file: TypeError: invalid file: << function NewSession.returnCsvFileDir at 0x0363E228 >>

This is some of my code:

From the first class:

def returnCsvFileDir(self, master, csvFileDir):
    NewSession.csvFile = print(csvFileDir)
    return NewSession.csvFile

From the other class:

def showCSV(self,master,NewSession):
    testCSV = (NewSession.returnCsvFileDir)
    print(testCSV)
    with open(testCSV, newline = "") as file:
       reader = csv.reader(file)
       r = 0
       for col in reader:
          c = 0
          for row in col:
             label = Label(root, width = 10, height = 2, \
                                   text = row, relief = RIDGE)
             label.grid(row = r, column = c)
             c += 1
          r += 1

Solution

  • Part of the problem is that NewSession.csvFile = print(csvFileDir) is assigning NewSession.csvFile to the return value of print(csvFile), which is None. You are not assigning a function to NewSession.csvfile.

    To fix, you might consider just using

    NewSession.csvFile = print

    Also, you are calling print(testcsv)m which will not work, since testcsv does not return a value. You probably want to call testcsv with an argument.

    At a higher level, it looks like you're trying to use a closure and partially evaluated function to grab the csvFileDir parameter and pass it inside a function call. While you could do this, (I haven't done this in python, so I don't know the details), I'd recommend finding a simpler way to just pass the filename around as a string and not worry about passing a function.