How to use `RemovedFromDocument()` override in python component

Hello,

I want to generate some default values in a python component and add them to the sticky. Then when I delete the component the values should be removed from the sticky. If I understand correctly, this can be done with the RemovedFromDocument(GH_Document) override. Unfortunately I can’t get it to call the method upon deletion. What am I doing wrong? I am guessing that the GH_Document input parameter is wrong, but I’m just grasping at straws…

here’s a sample script:

from ghpythonlib.componentbase import executingcomponent as component

from scriptcontext import sticky
import System.Windows.Forms as WF

class MyComponent(component):
    def RunScript(self, x):
        if x:
            sticky["guid"] = str(self.InstanceGuid)
        return 

    def RemovedFromDocument(self, gh_document):
        WF.MessageBox.Show("removing value")
        sticky.pop("guid")

Thanks!!

You can use the __enter__ / __exit__ methods when running in SDK mode:

Also, you might consider adding the data to the Grasshopper document instead:

1 Like

This approach is prone to bugs. If the user places a second or third component, they will each overwrite sticky["guid"] with their own guid. The last one to be removed will then delete the lot.

Adding to a set, and removing themselves would be better.

Thanks for the response!

The __enter__ / __exit__ logic seems to be working just fine! Now I want to do basically do the same thing when the component is locked, eg when the component is disabled, it removes its guid from the sticky. can you point me in the right direction for that?

Hey thanks!

This approach is prone to bugs. If the user places a second or third component, they will each overwrite sticky[“guid”] with their own guid. The last one to be removed will then delete the lot.
Adding to a set, and removing themselves would be better.

Yes the general strategy is to use a List or Dict with multiple component guids, that was just sample code to make things simple.

1 Like

You can check the ghenv.Component.Locked property. You might also be interested in the GhPython SDK mode slideshow and examples I posted over here, sounds like many of the methods used there would be relevant to you. Also, if the data doesn’t need to be globally accessible, there are simpler ways of making persistent variables in GhPython. Edit: Here’s a SDK mode example too:


240712_PersistentVariable_SDKMode_00.gh (5.6 KB)

Edit II:

I don’t think that is possible. When the component is disabled it can’t do anything, I think…