-1

I have a method to read from a file and assign the contents to a variable.

def recall_data(self, file, d):
    try:
        with open(file) as f:
            d = json.load(f)
            print(d)
    except FileNotFoundError:
        print('No File!')

I call the method and know that the value of d is assigned to the contents of the file (a dictionary). However, the code doesn't store the value of d in the variable I pass as d.

self.recall_data(self.file_name, self.data)

This is my method call. self.data is an empty dictionary. I don't understand why it isn't assigning self.data with the contents of self.file_name.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • What's the output when you `print(d)`? `d` should point to some dict returned by `json.load` at that point. However, remember that the name `d` is lost when the method returns, so that might be the problem here if you expected `d` to persist. – timgeb Jan 26 '22 at 17:57
  • 1
    `d` is just a local variable here - assigning to it has absolutely no effect outside of the function. To get a value out of a function, `return` it. – jasonharper Jan 26 '22 at 17:58
  • 1
    Try `|=` instead of `=`. – Kelly Bundy Jan 26 '22 at 18:04

1 Answers1

-1

You aren't passing the argument for reference.

That's how the argument passage for value works in Python:

var = 'hey'
def foo(arg):
    arg = 'yay'
    print(arg)
foo(var) # 'yay'
print(var) # 'hey'

In your case, you can do this:

def recall_data(self, file, d: list): # d is a list with one element
try:
    with open(file) as f:
        d[0] = json.load(f) # This way you are really editing the variable in the global scope
        print(d[0])
except FileNotFoundError:
    print('No File!')

Notice that the d argument in this case MUST be of type list, so self.data must too.

If you want to know more about this method, you can read the answers to this question.


Otherwise you can do something like this:

def recall_data(self, file, d):
try:
    with open(file) as f:
        d = json.load(f)
        print(d)
        return d
except FileNotFoundError:
    print('No File!')

self.data = self.recall_data(self.file_name, self.data) # The returned value will be stored into self.data

Notice that you should never use the first way I suggested above, it was just to solve the problem without changin so much your code.

FLAK-ZOSO
  • 3,873
  • 4
  • 8
  • 28