I find myself writing stuff like this too often and it seems too wordy:
obj = my_dict.get('obj')
if obj:
var = obj
Is there a better way to do this? Maybe in one line?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There’s no clean way to replace this code in one line, because it conditionally binds the name
var. In the case thatvarwas already defined, this one-liner is possible:However, this is still slightly different than the original code in case
varwas not already defined: the one-liner is raising aNameErrorand the original code just continues withvarunbound.Note that other answers behave differently when the value exists but is falsey.