How to create a lattice and link all objects to it procedurally? I've been trying to do that but have got some problems:


I was not able to retrieve the reference to a recently created object with bpy.ops.object.add().I had to use bpy.ops.lattice.select_all(), but that sounds inelegant.
While I was able to create a lattice for each object with bpy.ops.object.modifier_add(type='LATTICE'), I was not able to link it - mostly because the command to link a lattice modifier to the lattice object won't show on the info window. (Also, this needs the object to be selected...)


What is the proper way to do it?
The proper way is to not use operators:
import bpy

scene = bpy.context.scene

lattice = bpy.data.lattices.new(&quot;Lattice&quot;)
lattice_ob = bpy.data.objects.new(&quot;Lattice&quot;, lattice)
lattice_ob.scale = (5, 5, 5)

for ob in scene.objects:
    if ob.type == 'MESH':
        mod = ob.modifiers.new(&quot;Lattice&quot;, 'LATTICE')
        mod.object = lattice_ob

scene.objects.link(lattice_ob)
scene.update()

The .new() methods return object references to be used for subsequent method calls and property assignments in contrast to operators, which run isolated and only return a status (e.g. {'FINISHED'}). Some methods also take objects (the second parameter of objects.new()), whereas operators don't support objects/pointers, but only references by name (StringProperty).
//update: For Blender 2.8 and above, I believe you would do it like this:
import bpy

collection = bpy.context.collection

lattice = bpy.data.lattices.new(&quot;Lattice&quot;)
lattice_ob = bpy.data.objects.new(&quot;Lattice&quot;, lattice)
lattice_ob.scale = (5, 5, 5)

for ob in collection.objects:
    if ob.type == 'MESH':
        mod = ob.modifiers.new(&quot;Lattice&quot;, 'LATTICE')
        mod.object = lattice_ob

collection.objects.link(lattice_ob)