Directing Objects According to Their Types

Hello everyone,

I’m trying to direct 3 objects to different outputs in a GHPython component in Grasshopper.
If it is srf or polysrf, I want it to go to output a;
If it is a mesh, I want it to go to output b.

The problem is that no matter what kind of object I put they are always directed to output a.

Here is my file:
DirectObjectType.gh (10.6 KB)

Can anybody show what’s wrong?

And here is the python code that I use:

import rhinoscriptsyntax as rs

type = rs.ObjectType(x)
print str(type)

if type == 8 or 16:
a = x
elif type == 32:
b = x
else:
print “Unsupported object”

Ever figure this out? I messed with it a little but had the same results. Seems like a scope problem.

Perhaps if you change the thread category to scripting you could get an expert answer.

1 Like

The line “if type == 8 or 16” always evaluates to True.

The reason is that when “type == 8” evaluates to False it continues to the “or” clause which is 16.

16 is a truthy value, and then it will always return True and send your output to a.

A fix for this is “if type in [8, 16]:” or “if type == 8 or type == 16”, which will give you the correct output.

2 Likes

Thank you very much both for your answers. Bendikberg, your answer solved the issue.

Though I didn’t understand how type == 16 may become a truthy value in case of a mesh input (which makes type == 32). I mean, why in that syntax it doesn’t evaluate type == 16 condition as it did for type == 8? (I assume that it doesn’t evaluate it because if it would then it should return a False value, shouldn’t it?)

Python “or” works like this (at least as far as I know):

a or b => a is False => return b
a or b => a is True => return a

Which means that whenever you have a falsy value in the first spot, it will always return the second one. And in your case that means that it will always go to the first statement no matter what.

It never evaluates “type == 16”. The reason is that it tries to do “(type == 8) or 16”. When “type == 8” is False, it goes to the next part of the “or” statement, which is just “16”, not “type == 16”. And since the if statement thinks everything is truthy as long as it is not an empty collection, 0, a None or False it always sends your output to “a”.

To check if type is equal to more than one value you have to do it explicitly several times, or check if it exists in a list like I showed above. What you’re essentially trying to do is “type equal to either 8 or 16”, which is not what it does, but which is what “type in [8, 16]” or “type == 8 or type == 16” does. This solution checks if the value for type exists in the list. If it does it is True, if it doesn’t it is False.

I hope that clears up the confusion. :slight_smile:

1 Like

Hello,

See here for more on the sometimes surprising ways in which Python evaluates values as True or False.

I think if type in (8, 16) is best for clarity

1 Like