Edit During Review Plugin Code Feedback

I am modifying a plugin for first time (also learning python with it on the go). I read the anki online docs entirely. The plugin I am modifying is the Edit During Review plugin (not the cloze one). I saw the following code in the handle js method:

def on_js_message(handled, msg, context):
    if msg.startswith("ankisave#"):
        fld, nid, val = msg.lstrip("ankisave#").split("#", 2)
        nid = int(nid)
        card = context.card
        note = card.note()
        config = mw.addonManager.getConfig(__name__)
        if config['debug']:
            assert nid == note.id, "{} == {}".format(nid, note.id)
        try:
            # make sure note is not deleted
            note2 = mw.col.getNote(nid)
        except NotFoundError:
            return True, None
        except TypeError as e:
            # NotFoundError if Anki < 2.1.28
            if str(e) == "cannot unpack non-iterable NoneType object":
                return True, None
            raise(e)
        # we need to reuse context.card.note() if nid == note.id
        # as changes will be lost once we open the editor window
        if nid != note.id:
            note = note2
        saveField(note, fld, val)
        card.q(reload=True)
        return True, None

Is all of this actually neccessary? Specifically it seems he gets the note object from 2 sources. First source is the function argument, and the other is from the collections object. And what about the note==note2 part. That seems redundant. Would appreciate any insight. It seems perhaps whoever was writing this plugin maybe was hacking it like myself and hence merely kept whatever worked when faced with error, etc. Why would nid ever not equal note.id?

Presumably it’s to prevent a race condition where the text would be saved to the wrong note if the user happened to transition to a new card before the message arrived.

Ah thanks! That makes sense. So why not just use the nid supplied directly in the message itself. Seems that is always reliable whereas the other method is not always. You think I can safely get rid of using context and rely exclusively on the message supplied nid?

Perhaps. I suggest you ask the author of the code why they did it that way.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.