How to throw warnings with Hops?

Hey there !

I can’t find my way to throw warning or messages at the component level (cpython)…
Does anyone have an idea?

Something like this on GH_python

w = gh.GH_RuntimeMessageLevel.Warning
ghenv.Component.AddRuntimeMessage(w, 'this is a warning!')

Thanks !

In CPython, you can use the warnings module (cf. docs):

import warnings

warnings.warn("This is a warning!")

Messages can simply be printed and you can raise exceptions for various errors.

I see, thanks ! :slight_smile:

But the goal is to have the warning displayed in the usual Grasshopper bubble like so
image

I don’t know enough about the inner workings of Hops and how the component communicates with CPython, but maybe catching exceptions could work for your case?

Generally, you can for instance raise exceptions in a function or method and catch them somewhere else where the function or method gets called. Once a certain exception is caught, it can trigger an event, like for example producing a GH_RuntimeMessageLevel.Warning.

In your CPython script you could try something like this:

def foo(s):
    if not isinstance(s, str):
        raise ValueError("{} is not a string".format(str(s))
    return s.upper()

Then in the Hops component, where you call foo, you can use try and except to catch the error:

if __name__ == "__main__":
    try:
        foo(14)
    except ValueError as e:
        ghenv.Component.AddRuntimeMessage(
            gh.GH_RuntimeMessageLevel.Warning, e
        )

There are many default exception types (ValueError, RuntimeError, IOError, TypeError, etc.) that should be used according to their purpose. I maybe should have used a TypeError above, instead of the ValueError.
And you can define your own project-specific, custom exceptions by inheriting yours form the mother of exceptions Exception, from whom all other exceptions inherit from.

One word of caution though! Be specific, because you can easily obfuscate exceptions and thus make debugging really hard. A good rule of thumb is to never raise Exception, because it will catch each and every exception.

The problem is that I don’t know how to access the component…

image

Maybe I’m missing a step, but that works just fine in GH_python… just not through Hops.

funnily enough, it’s the 332 line that create an error (line 333 was removed for the test)