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?

4
  • just checking it's not an indenting problem, so in the actual source you have the register.append... line tabbed in? Commented Mar 9, 2013 at 6:22
  • Of course :D Thanks for telling fixed that. Commented Mar 9, 2013 at 6:23
  • Can you give a more complete example showing what variable is when you are using some_command? Commented Mar 9, 2013 at 6:24
  • There are several not just one. For example: [Yellow,'Color'] [True, 'Is Monty Python funny?'] [42, 'Meaning of Life'] Commented Mar 9, 2013 at 6:27

1 Answer 1

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 )
Sign up to request clarification or add additional context in comments.

6 Comments

Can't I: def some_command(): global register ... instead?
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
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.
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
stackoverflow.com/questions/423379/… You can implement the register-variable as global, but as said above, global variables are mostly frowned upon (for a good reason).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.