简体   繁体   中英

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

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

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

Opinions vary but here is my $.02.

  1. Please do not use default dict. If I'm reading your code, I might not know what you know, that there is no key in the dict. Someone could later update the code and violate that silent assumption and the code will break.
  2. Please do not use the "set_and_return" function. Your code might be clever but it's less readable. More lines, harder to follow and the function lookup costs the same as the dict lookup.
  3. @gnibbler has a nice "fewer lines of code" solution but I wouldn't suggest it and reading a lot of python source I rarely see that syntax (more at the start of a function than anywhere else)

I appreciate how it happens in javascript but for the accepted way to do it: I vote for your original format, easiest to read and understand and no slower or less efficient than any other solution.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM