Causing a Python Grasshopper Component to Unload or Fail to Load if a programmatic check fails

I am writing a Grasshopper component using Python and I want to be able to carry out a check at the beginning (when components are loaded) and cause the component to fail to load or unload it the check fails. In case it is relevant, the check actually involves a call to a dll to check whether the computer is compliant. How can I do this?

# ...
from ghpythonlib.componentbase import dotnetcompiledcomponent as component

__author__ = "piac"

# What can I put in here to carry out a check and then abort the loading (or unload)?
# Can python override the base loading method?
#  Grasshopper.Kernel.GH_AssemblyPriority ???
#  GH_LoadingInstruction.Abort ???
# Or is there a method that I should call that will unload?


class MyComponent(component):
    def __new__(cls):
        instance = Grasshopper.Kernel.GH_Component.__new__(cls,
            "Axes", "Axes_1", """Draws a graphic symbol ....""", 
            "Display", "Preview")
        return instance

    # etc...

@piac - I am following your tutorial on creating a Grasshopper component, and I already have the Axes component working.

Hi Andrew,
In case this is still live, it sounds like you are looking for a

try:
    Something
except ImportError:
    Something else

Replace ImportError with your specific error

1 Like

Thank you for your reply. Where would this code go? Is it in the component class or is it outside?

I guess it depends on how you are structuring your code but the idea would be to ensure the exception is triggered within the try block and, if so, not to execute anything which relies on the behaviour you are checking for.
In your case that might simply mean putting all of your code inside the try, (or in a function which is only called within the try block), with an error message in the except block.
Also watch out for naked exceptions: :blush:

Hi Graham, thank you for responding. Of course, I am talking about the example that Giulio provided, but I think I see what you are saying. Does what you suggest “unload” the component, or just simply not load it?

Yes it is a generic ‘Pythonic’ pattern for doing one thing on success or another on failure; I’m afraid I cant help you with the specific issue of loading and unloading components.