dash-docs icon indicating copy to clipboard operation
dash-docs copied to clipboard

Questionable practices in the Pattern Matching Callbacks example

Open etrotta opened this issue 2 years ago • 0 comments

In https://dash.plotly.com/pattern-matching-callbacks, more specifically in the Todo App example, there are some parts which are not very Pythonic. In the edit_list function,

def edit_list(add, add2, clear, new_item, items, items_done):
    triggered = [t["prop_id"] for t in dash.callback_context.triggered]
    adding = len([1 for i in triggered if i in ("add.n_clicks", "new-item.n_submit")])
    clearing = len([1 for i in triggered if i == "clear-done.n_clicks"])

You could change these lines such that:

# Instead of creating lists containing 1 then taking the length...
adding = len([1 for i in triggered if i in ("add.n_clicks", "new-item.n_submit")])
clearing = len([1 for i in triggered if i == "clear-done.n_clicks"])
# Determine if any of them match the condition, and use a more descriptive name than "i"
adding = any(trigger in ("add.n_clicks", "new-item.n_submit") for trigger in triggered)
clearing = any(trigger == "clear-done.n_clicks" for trigger in triggered)

The show_totals function also suffers slightly from a similar practice,

def show_totals(done):
    count_all = len(done)
    count_done = len([d for d in done if d])

Even though it is not as bad, it could be changed to either of:

count_done = len(d for d in done if d)  # Just use a generator instead of a list comprehension
count_done = sum(1 for d in done if d)  # Sum of 1s instead of taking the length
count_done = sum(done)  # Since the value is automatically converted to 1, just take the sum directly

etrotta avatar Apr 12 '22 00:04 etrotta