Proper use of foreach_set

foreach_set is a convenient wrapper in the Blender Python API for quickly setting the desired value for each element of the bpy_prop_collection type. However, when using this function, script developers sometimes run into an error.

For example, let’s switch all the polygons in the mesh to smooth shading. To achieve this, the “use_smooth” property of each mesh polygon must be set to True.

With common Python syntax, we can write the following code:

If we want to use the foreach_set functional, it seems logical to write the following:

however, calling this function in this way will result in an error:

couldn’t access the py sequence

This occurs because the second parameter in the foreach_set function should not be the value itself, which we want to set for the “use_smooth” property, but a list of values ​​for each of the polygons.

Instead of

we need to use:

The length of the list must correspond to the number of elements for which the foreach_set function is called, in our case – the number of polygons.

So, to properly use the foreach_set function, first we need to create a list of values ​​by the number of mesh polygons:

and next pass it as the second parameter to the function:

Or all in one string:

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments