Elif conditional with data bindings?

Greetings.

Can anyone provide guidance on using an elif conditional within a data binding?

In the forums, I have found references to if … else … but not to elif.

For example, here’s the format suggested for the if/else situation.

'desired_value' if self.item['your_column']==actual_value else some_other_value

but every combination that I have tried to accommodate a third possible state throws a syntax error.

Thank you.

elif is not valid in a Python expression. However, you could use parentheses to achieve the net effect, e.g.,

x = y1 if c1 else (y2 if c2 else (y3 if c3 else y4))
5 Likes

if condition value_if_true else value_if_false is the ternary operator in Python and you can use it in any expression, elif is a statement that cannot be used in an expression.

If you want to use more complex expressions you can use the example from @p.colbert or create a pick_the_right_value() function and use that, by entering the function in the databinding, something like self.pick_the_right_value(self.item)

5 Likes

Thanks so much for the guidance. I had never realized that functions were directly accessible through data bindings. This completely changes how I look at customization options. Although @p.colbert’s solution was the direct answer to my question, your functions within databindings solution is both the answer to my question as well as the answer to questions I hadn’t even considered. Thanks again.

A pattern I frequently use in this circumstance is to create a property and bind to that. Whatever logic is required sits within the property body and the data binding line becomes very simple.

4 Likes

I do the same.

The only problem with properties is that the automatic data binding with the key of DataGrid columns expects dictionary or dictionary-like objects, so I always derive my classes from the AttributeToKey class described here.

Data binding on most components can be any of these (considering self.item is a box of cookies):

# full expression in data binding
sum(1 for c in self.item.cookies if cookie.color == 'red']

# pre-calculated value in dictionary
self.item["n_red_cookies"]

# property that calculates the value
self.item.n_red_cookies

Driving a class from AttributeToKey allows to use n_red_cookies as the key on DataGrid columns.

Yep. I have a very similar Mixin class called WithAttributesAsKeys tucked away for just that purpose!

2 Likes