Add-on loading: use natural sort order

Since this commit in 2018 add-ons in Anki are loaded in a predictable order by using .sort() on the list of add-on folder names.

I suggest to enhance this so that add-ons with a lower ankiweb id are loaded first. This could be done by replacing l.sort() with something like

def lpad_ankiweb_ids(name):
    return f"{int(name):012}" if name.isdigit() else name

Manually installed add-ons can have non-digits in their name so l.sort(key=int) would fail.

I think these two additional lines make sense in Anki because sometimes the load order of add-ons or the order of functions from add-ons appended to gui_hooks is relevant. At the moment add-on creators have to rely on workarounds for delayed loading like the profile_did_init hook etc. But I think a better sort order of the list of addons is preferable.

E.g. I have an add-on that allows allows multi-line rows in the browser. For this I want to truncate the text of long cells. I use the gui_hook “browser_did_fetch_row” for this. The same hook is used by the advanced browser add-on to add the contents of the additional columns created by the AB add-on. My add-on only works with the AB if the AB fills the cells first, and then my addon truncates them. The AB has the nine digit id 874215009 so my add-on id may not start with 1 or 2 which is pretty common for the common 10 digit ankiweb ids. Ankiweb assigns random(?) ids that can be up to 10 digits long so it’s pretty hard to get the needed id by chance when creating a new add-on.

My proposed change could in theory break add-ons (e.g. a nine digit add-on 9… that assumes to be loaded after a 10 digit add-on 1…). But due to the limitations of the current sorting I doubt that this problem will exist in practice.

@glutanimate (pinged because he was involved in the discussion Sort addons by meta field by ChrisK91 · Pull Request #225 · ankitects/anki · GitHub in 2018 and he has many add-ons on ankiweb).

1 Like

The predictable sorting is more about ensuring you get the same results from run to run, as it makes debugging problems harder if problems only happen intermittently. The sorting is not intended as a way of ensuring one add-on runs before or after another - for that, I’d suggest you add to the fetch_row hook in the main_window_did_init hook.