Set a variable equal to result if result exists
This seems very verbose, particularly with long function names, is there a better way to do this in Python?
if someRandomFunction():
开发者_Python百科 variable = someRandomFunction()
Edit: For more context variable is not already defined, and it will be a new node on a tree. I only want to create this node if someRandomFunction() returns a value. And someRandomFunction() is supposed to return the string representation of some node from a different type of tree.
Could you:
variable = someRandomFunction() or variable
See Boolean Operations in the Python documentation for more information.
temp= someRandomFunction()
if temp:
variable = temp
A bit unorthodox perhaps, but you could modify someRandomFunction()
so that it saves its last result in a function attribute before returning it, you could then do this.
def someRandomFunction():
...
someRandomFunction.result = <...>
return someRandomFunction.result
if someRandomFunction():
variable = someRandomFunction.result
I don't think your answer is too verbose. It says exactly what it does. However, since you've already said it's too verbose for your tastes I would opt for the
s = myFunc() or someVariable
approach
(Apparently you can't delete your answers if you haven't registered.)
These are not the droids you're looking for... move along...
精彩评论