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])

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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.