Add \ remove eventHandler from event


Currently i am building a solution which checks the door swings “on fly” (defines whether the door Left or Right handed) using iUpdater routine. Everything that concerns the updater works well: i’ve got a toggle (smartbutton), which registers and unregisters it.

I also decided to add up an another feature: when the “DoorSwingChecker” is switched on for user, it does not only check the doors on fly, but also checks all the doors, contained in the project, once the document is opend. In order to achive it, i am just adding new event handler to revit Application DocumentOpened:

__revit__.Application.DocumentOpened += event_handler

And the eventhandler does it’s buisness succesfuly. But when i’m trying to unregister it, it doesn’t give a result. My python code is not throwing any exception, but the eventHandler keeps on working as before:

__revit__.Application.DocumentOpened -= event_handler

As far as i understand, my problem is as following: when i am switching the toggle in order to register or unregister the EventHandler, i am creating it from anew. This causes, that possibly those to objects have the same strcture and meaning, but obtaining the different Guid. Like i am creating a variable with EventHandler object (object1 let’s say), but then i am constructing a new object and trying to remove completely another EventHandler (object2). There is no option to store this variable in a session, because when user switches the toggle, he is actualy running two different sessions of script.

Storing EventHandler object in a memory (either pyRevit’s functional or pickle regular functional) didn’t succeed because pickle says, that it is impossible to pickle EventHandler into an object.

Is there any possibility to store\pickle EventHandler object to use it between scripts? Or maybe i can write down my objects Guid somwhere in order to query it during the unregistring?

Here’s what my code looks like:

from pyrevit import framework
from pyrevit import DB, UI
import pickle as pl

def construct_event_handler():
    return framework.EventHandler[DB.Events.DocumentOpenedEventArgs](checkout_all_the_swings)

def checkout_all_the_swings(sender=None, args=None):
    ##very long function

def register_updater(my_updater, event_handler):
    ##registring iUpdater
    __revit__.Application.DocumentOpened += event_handler

def unregister_updater(my_updater, event_handler): 
    ##unregistring iUpdater object,
    __revit__.Application.DocumentOpened -= event_handler

def toggle_state():
    current_state = pl.load(f)
    new_state = not current_state

    my_updater = DoorSwingUpdater()

    if new_state: