Python for loop on adsk.core.ObjectCollection

Python for loop on adsk.core.ObjectCollection

Anonymous
Not applicable
1,412 Views
4 Replies
Message 1 of 5

Python for loop on adsk.core.ObjectCollection

Anonymous
Not applicable

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:
   sketch.sketchPoints.add(pp)
# 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)):
   sketch.sketchPoints.add(points[i])
# 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!

 

Thanks

Luca

 

 

0 Likes
Accepted solutions (1)
1,413 Views
4 Replies
Replies (4)
Message 2 of 5

MichaelT_123
Advisor
Advisor

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.

Regards

MichaelT

MichaelT
0 Likes
Message 3 of 5

Anonymous
Not applicable

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.

0 Likes
Message 4 of 5

KrisKaplan
Autodesk
Autodesk
Accepted solution

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



Kris Kaplan
Message 5 of 5

Anonymous
Not applicable
Thanks for the reply!
0 Likes