0

Help, I'm trying to save all the data in my file as a list.

register = []


def some_command():
    register.append([variable,'variable_x'])

def save():
    outFile = open('Save.txt', 'wb')
    pickle.dump(register, outFile)
    outFile.close()

It saves the file succesfully. But when I use "some_command" to add a new element to "register" it doesn't update; It doesn't even give an error. What could be the problem?

madprogramer
  • 599
  • 3
  • 12
  • 36

1 Answers1

1

It will work if you pass register and variable into some_command, but otherwise you cant edit register properly from inside the function. So, it would look something like this:

def some_command( register, variable ):
    register.append([variable,'variable_x'])

It's not strictly necessary to pass variable in, but it does help keep things neat.

And obviously you would call it with

some_command( register, whatever you want )
max k.
  • 549
  • 4
  • 9
  • Can't I: def some_command(): global register ... instead? – madprogramer Mar 09 '13 at 06:30
  • Have you tried it? I know the method that I put up is recommended to keep things neat when the projects get large (and people just generally hate global), but if that worked it would definitely be a better fix, and a lot smaller too – max k. Mar 09 '13 at 06:32
  • Tried, but it doesn't work. The problem with your code is that this saving function is supposed to be automatic. So just passing in some_command() should be enough. – madprogramer Mar 09 '13 at 06:41
  • Not sure what you mean by supposed to be automatic, so just some_command() should be enough? As in it is a callback or something like that? If that's the problem, you can always use a lambda to call it – max k. Mar 09 '13 at 06:44
  • http://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them You can implement the register-variable as global, but as said above, global variables are mostly frowned upon (for a good reason). – Sami N Mar 09 '13 at 09:10
  • @madprogramer If you desperately wanted to use globals: `global register; register = []` (using semicolons so that you can see the separation; hard to show multiple lines of code in a comment. `def some_command(): register.append([variable, 'variable_x'])` You need it to be declared as `global` when you define the variable. – Rushy Panchal Mar 09 '13 at 16:48