0

I encountered this error "SyntaxError: can't assign to function call" while experimenting with the pickle method. What I was trying to do was store something simple like the string "x = 5"
and have python eval() the string later to bring the variable x back into existence in a later script. I understand why the code fails but I was wondering if there was any workaround for assigning the result of a function an object. As in have a function return the name of a variable and be able to assign that variable an object. Here is the code that fails:

import pickle
y = "x = 5"
open_file = open("pickle_file.pkl", "wb")
pickle.dump(y, open_file, -1)
open_file.close()
del y
newly_opened = open("pickle_file.pkl", "rb")
loaded = pickle.load(newly_opened)
loaded.split('=')[0] = eval(loaded.split('=')[-1]) #this fails because of the function on the  #variable side
print loaded.split("=")[0], 'should equal', eval(loaded.split('=')[-1])
2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by ihatehippies
0

I think you are confusing eval() with exec():

import pickle

y = "x = 5"

open_file = open("pickle_file.pkl", "wb")
pickle.dump(y, open_file, -1)
open_file.close()

del y

newly_opened = open("pickle_file.pkl", "rb")
loaded = pickle.load(newly_opened)
newly_opened.close()

# test
print loaded, type(loaded)  #  x = 5 <type 'str'>

exec(loaded)
print x      # 5
0

holy crap you look like a genius to a newb like me. thanks a ton. You single handedly fixed 2 of my scripts.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.