-2

In C language I was used to doing this by passing address of variables (pass by reference), but in Python, despite having already read about some alternatives, I have no ideia how can I do to pass a Google Sheet (worksheet) to a function that must change and save it online, using gspread library.

Here is my code:

def ordenar(self, list):
     sheet = len(list.worksheets())
     for i in range(sheet):
         lista = list.get_worksheet(i).row_values(1)
         lista.sort()
         size = len(lista)
         if size > 1:
             cell_list = list.get_worksheet(i).range(1, size)
             j = 0
             for cell in cell_list:
                 cell.value = lista[j]
                 j = j+1
             # Update in batch
             list.get_worksheet(i).update_cells(cell_list)

Now the part of the main code that uses the function:

#Teste de ordenação
Jose.vocabulario.ordenar(Jose.vocabulario.artigo)
AMC
  • 2,642
  • 7
  • 13
  • 35
  • 1
    You can pass an object into a function to alter the object in Python. You don't need to pass the address of a variable. What actual problem are you having with your code? – khelwood Apr 10 '20 at 17:00
  • As an aside, naming anything `list` is a bad idea. – AMC Apr 10 '20 at 17:28

2 Answers2

0

First off, don't use list as a parameter name, since it shadows Python's built-in list function.

You can change an object in a function simply by... modifying it somehow. Of course, the object has to be mutable. Ex:

mylist = [1, 2, 3]
print(mylist)  # output: [1, 2, 3]

def append_five(list_to_modify):
    list_to_modify.append(5)

append_five(mylist)
print(mylist)  # output: [1, 2, 3, 5]

What I suspect is happening in your case is that, at some point, the Google Sheets worksheet needs to be saved in order to the resulting file reflect the changes in your code. I don't know much about Google Sheets API and you didn't mention the module you are using to work with them, but that's how you'd do it in openpyxl, a Python module for working with Excel spreadsheets.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25
0

I've solved it. The error was in the worksheet.range() function: worksheet.range(start line, start column, final line, final column).