Search code examples
pythonencapsulation

Using encapsulation/functions to modify a variable and pass it to the current namespace


I'm trying to write a function which gets the header of a CSV file and stores it as a list, which will be useful later:

def getHeader(filename, headername):
     import csv
     charList = ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E', 'F'] <<<---a lot longer
     headercsv = open(filename, 'r', newline = '')
     headerreader = csv.reader(headercsv, delimiter = ',')
     for row in headerreader:
         if row[0][0] in charList:
              headername = row

     headercsv.close()
     return headername

Then I do the following:

thisHeader = []
getHeader('csvfile.csv', thisHeader)

If I'm trying this in the shell, it returns the correct info, but when I try to look at the information contained within the variable thisHeader, it only returns [], a blank list.

I also define another function to aggregate population info, across every entry, for each cohort. It needs to use the header obtained in the above function and is defined as such:

def newPopCount(filename, fileheader, popholder):
     import csv
     cohorts = []
     for i in range (3, len(fileheader)):
          cohorts.append(fileheader[i])
     for i in range (len(cohorts)):
          popholder.append(0)

     popcsv = open(filename, 'r', newline = '')
     popreader = csv.reader(popcsv, delimiter = ',')

     for row in popreader:
         counter = 0
         if row[0] == fileheader[0]:
             continue
         else:
             for i in range(3, len(fileheader)):
                 popholder[counter] += int(row[i])
                 counter += 1

     popcsv.close()
     return popholder

I have these functions defined within another function, so as to only call the outer most function with a file name test('csvfile.csv') and then some print statements to assess whether the code is doing what it supposed to, by passing on the information obtained from one function to the other function - they are not.


Solution

  • Aren't you overcomplicating things?

    def getHeader(filename):
         import csv
         headername = None
         charList = ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E', 'F']
         headercsv = open(filename, 'r', newline = '')
         headerreader = csv.reader(headercsv, delimiter = ',')
         for row in headerreader:
             if row[0][0] in charList:
                  headername = row
    
         headercsv.close()
         return headername
    

    Now you can:

    thisHeader = getHeader('csvfile.csv')
    

    Make sure you understand how functions work, and the difference between pass-by-value and pass-by-reference.