Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Python for loop on adsk.core.ObjectCollection

Message 1 of 5
627 Views, 4 Replies

Python for loop on adsk.core.ObjectCollection

I'm not very used to Python, but as I understand, for loops can easily be performed using a variable as iterator.

I'm wondering why I'm having an error in case of iterations in a adsk.core.ObjectCollection:


# data is an array of 3-elements arrays which contains
# floating 3d points coordinates each
# sketch is a sketch ;-)
points = adsk.core.ObjectCollection.create()
for pt in data:
   points.add(adsk.core.Point3D.create(pt[0], pt[1], pt[2]))

# The previous for loop works just fine and let's say it adds n points
for point in points:
# This second for loops give me the following error:
# Exception has occurred: IndexError
# The index (n) is out of range.
# I solved like this:
for i in range(len(points)):
# but I can't figure out why...


Obviously it's me, I just started using python yesterday (actually yesterday), but I really can't understand the problem!






Tags (2)
Labels (1)
Message 2 of 5
in reply to: Anonymous

Hi LucaBortolotti1984,

Yes, It is you.

Just take it easy, analyse the code. If you will find the problem yourself, more likely bases of it will imprinted in your Python skillset.



Message 3 of 5
in reply to: MichaelT_123

Ok, it's me... But can you just tell me where is the problem?

Is it adsk.core.ObjectCollection.create() indexed differently than a normal python array?

Why with the for "ranged" loop it works?


Thanks for the reply.


PS: typo in my previous message --> point actually was pp.

Message 4 of 5
in reply to: Anonymous

This is caused by the fact that our Python collections do not implement __iter__, but instead just implement __getitem__. So Python's ranged for falls back to use __getitem__ and uses the IndexError exception to terminate the iteration. Normally this behavior is not a problem, but it can get annoying if you set your debugger to break when any exception is raised (not just unhandled). But your script with that loop should run normal (the exception was handled). You can either ignore it and continue, filter out IndexError (if your IDE supports it, I do not believe VSCode does), or only break on unhandled exceptions.


BTW: We have updated the collections with a __iter__ implementation so in the next release this should not be an issue anymore.


Kris Kaplan
Message 5 of 5
in reply to: KrisKaplan

Thanks for the reply!

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Technology Administrators

Autodesk Design & Make Report