Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python avoiding using a variable when using a value twice?

I currently have:

tmp = myfunc()
mydict[mykey] = tmp
return tmp

..which seems a little too long. In javascript, I could just do:

return (mydict[mykey] = myfunc()) 

Is the above Python code the accepted way to do it, or is there something else?

edit: I'm aware of the possibility of doing:

mydict[mykey] = myfunc()
return mydict[mykey]

..but I wouldn't want to do a key lookup twice. Unless

like image 347
mowwwalker Avatar asked Dec 02 '22 22:12

mowwwalker


2 Answers

tmp = mydict[mykey] = myfunc()
return tmp
like image 69
John La Rooy Avatar answered Dec 07 '22 22:12

John La Rooy


You can do this if you want less lines of code:

mydict[mykey] = myfunc()
return mydict[mykey]

Assignment isn't an expression in Python, though, so you can't do the javascript version.


EDIT: If you know the key is not in the dictionary, you can do this:

return mydict.setdefault(mykey, myfunc())

setdefault is a lookup function that sets the key to the 2nd value if the key is not in the dictionary.


You could also write a helper function:

def set_and_return(d, k, v):
    d[k] = v 
    return v

Then, everywhere else, you can do:

return set_and_return(mydict, mykey, myfunc())
like image 27
Claudiu Avatar answered Dec 07 '22 23:12

Claudiu