I have an object for which I wish to modify a property if a condition is met, else leave it virginal.

I find my current code to be very repetitive and would instead like to use a more succinct form, but am unsure of how to lambda-fy it or at least tell it to pass if condition not met:

my_object.unique_id = 'TBC' if not my_object.unique_id else my_object.unique_id

I guess this is nicer, but still repetitive:

if not my_object.unique_id: my_object.unique_id = 'TBC'

I would like something more like

my_object.unique_id = 'TBC' if None

Is there a way to only reference the property once?


You can use

my_object.unique_id = my_object.unique_id or 'TBC'

Otherwise, stop worrying about having to repeat a variable name, which is not what people typically mean when they talk about DRY. Variable names are often repeated when you do in-place manipulation of a variable, because you are saying "do something to x and then store the result as x".

If you have lots of similar lines of code then you could submit some more of your code for review; there may be other ways to simplify.

  • \$\begingroup\$ Thanks Stuart, that's perfect. I agree if an isolated line of code like that, it's not really the structural DRY issue, I guess I was after something that felt more Pythonic as yours definitely is. \$\endgroup\$ – ljs.dev Oct 12 '13 at 14:54

Not the answer you're looking for? Browse other questions tagged or ask your own question.