Hiding objects with scripting - unpredictable behaviour I have a really weird issue with my script. It is extremely unpredictable and I have no idea why. Sometimes it works, sometimes it kinda works, and sometimes it doesn't work at all. 

Here is what I want to do:


I have an empty parent object that controls the all of its children
I select that parent object, and then only select his children using the SHITFT+G shortcut, then select children
Then I hide all of the children using the H shortcut


This is the script that I wrote:

def makeInvisible(ob):
bpy.ops.object.select_all(action='DESELECT')
ob.select = True
bpy.ops.object.select_grouped(type = 'CHILDREN_RECURSIVE')
for sel in bpy.context.selected_objects:
    sel.hide = True


As you can see, I will pass the the parent object as an argument to the function. The problem is that it doesn't really work, especially when I call it multiple times. 

What am I doing wrong? Is there a better approach to my problem?
I think the problem here is that you do not set the active object for the context on which operators almost always rely. Here is a low-level approach without operators, tested and working. All children (recursive) of the active object are hidden.

import bpy

ob = bpy.context.active_object

def makeInvisible(ob):
    for child in ob.children:
        child.hide = True
        #call the function on the child to catch all its children
        #as there is no ob.children_recursive attribute
        makeInvisible(child)

makeInvisible(ob)


Note that this does not hide the active object itself, only its children. If you want to hide the active object too, just add ob.hide = True right below the function header.