Explode nested block with recursion in python: return individual block instances


Not sure why when I try to make it work recursivelly it doesnt work:

def block_expl(block):
    #initialize the Rhino document to be modified.
    predoc = sc.doc
    sc.doc = Rhino.RhinoDoc.ActiveDoc  
    blocks_expl = []
    if rs.IsBlock(rs.BlockInstanceName(block)):
        if rs.BlockObjectCount(rs.BlockInstanceName(block)) > 1:
            exploded =  rs.ExplodeBlockInstance(obj_baked)
            for blk_exp in exploded:
                if rs.IsBlock(rs.BlockInstanceName(blk_exp)):
                    if rs.BlockObjectCount(rs.BlockInstanceName(blk_exp)) == 1:
                    elif rs.BlockObjectCount(rs.BlockInstanceName(blk_exp)) > 1:
                        block_expl(blk_exp) #RECURSION NOT WORKING... WHY?
                        print rs.BlockInstanceName(blk_exp)
        elif rs.BlockObjectCount(rs.BlockInstanceName(block)) == 1:
            #print rs.BlockInstanceName(block),"igual a 1" 
    return blocks_expl
    #sets the script environment back to grasshopper.
    sc.doc = predoc
test = block_expl(obj_baked)

The idea is that this definition should return the individual block instances inside a block.

Anyone has any clue?


this post has a bunch of info.

I made this the other day but doesn’t go beyond the first level.

import rhinoscriptsyntax as rs
import Rhino

#Select Block
#Get all instances of block
#Explode and get 1st level nested blocks
#place instance of said block at its locations

selBlks = rs.GetObjects("Select Blocks", 4096)

for blk in selBlks:
    blkcpy = []
    name = rs.BlockInstanceName(blk)
    xform = rs.BlockInstanceXform(blk)
    allBlks = rs.BlockInstances(name)
    for bk in allBlks:
        blkObjs = rs.BlockObjects(rs.BlockInstanceName(allBlks[0]))
        for blkblk in blkObjs:
            if rs.IsBlockInstance(blkblk):

    new = rs.CopyObjects(blkcpy)
    rs.TransformObjects(new, xform, False)

The routine I scripted there tries to go for every level of the block instances inside, and only tries recursion when the block contains more than 1 block… I could keep writting it for other levels but Im sure it could be done with recursion…