Page 1 of 1

How to check and raise error if an attribute does not exists

Unread postPosted: Fri Nov 03, 2017 3:00 am
by xenas19
I am trying to check if selections has a certain attribute, if it does not have it, it will print/raise an error.

For example,
Code: Select all
current_sel = ix.selection
for sel in current_sel:
    sel_filename = sel.attrs.filename
    if not sel_filename:
        print Selection does not have the filename attribute''


While I am testing this on an object that does not have the "filename" attribute, instead of getting that print statement, I got
Code: Select all
error: TypeErrorerror: : error: 'NoneType' object has no attribute '__getitem__'error:


In pythonic terms, the code should have worked. Any ideas?

Re: How to check and raise error if an attribute does not ex

Unread postPosted: Fri Nov 03, 2017 10:29 am
by dboude
Hello,

You can achieve this with this code

Code: Select all
sel = ix.selection[0]
attrList = []
for i in range(sel.get_attribute_count()):
    attrList.append(sel.get_attribute(i).get_name())
if not "filename" in attrList:
    print "Selection does not have the filename attribute"


Cheers ;)

Re: How to check and raise error if an attribute does not ex

Unread postPosted: Fri Nov 03, 2017 8:02 pm
by sam
There's a simpler way by using OfObject::attribute_exists method:

ix.selection[0].attribute_exists("foobar")

If it exists it will return the attribute matching the name, otherwise it returns None. Check the API/SDK documentation

Cheers,

Re: How to check and raise error if an attribute does not ex

Unread postPosted: Sat Nov 04, 2017 12:24 am
by xenas19
Many thanks for the resolution, Sam and dboude!
Both works like a charm :D