modifier_apply not working when objects created in a specific order Is something wrong with my code?
I intended to do programmatic CSG modelling,
like in POV or OpenSCAD.
But when I change the order of lines:

cyl1=make_cylinder()
c2=make_cube()


The modifier application fails. The same happens with c1 and s1.
Why do the order of object creation is affecting the results?

import bpy
from bpy import data as D
from bpy import context as C
from mathutils import *
from math import *

S=C.scene

def make_cube():
    bpy.ops.mesh.primitive_cube_add(location=(0,0,0))
    return S.objects.active

def make_material(obj,rgb=(1.0,1.0,1.0)):
    mat=bpy.data.materials.new("mat")
    obj.data.materials.append(mat)
    mat.diffuse_color=Color(rgb)
    return mat

def make_sphere():
    bpy.ops.mesh.primitive_uv_sphere_add(location=(0,0,0), size=1.2)
    return S.objects.active

def make_cylinder():
    bpy.ops.mesh.primitive_cylinder_add(location=(0,0,0), radius=0.7, depth=2.5)
    return S.objects.active

def oper(obj1,obj2,kind='INTERSECT'):
    bpy.ops.object.select_all(action='DESELECT')
    obj1.select=True
    m=obj1.modifiers.new('Bool','BOOLEAN')
    m.operation= kind
    m.object= obj2
    bpy.ops.object.modifier_apply(modifier=m.name)
    bpy.ops.object.select_all(action='DESELECT')
    obj2.select=True
    bpy.ops.object.delete()
    # D.objects.remove(obj2)
    return obj1


def inter(obj1,obj2):
    return oper(obj1,obj2,'INTERSECT')

def union(obj1,obj2):
    return oper(obj1,obj2, 'UNION')

def diff(ob1,obj2):
    return oper(ob1,obj2,'DIFFERENCE')

def scale(obj,sx,sy,sz):
    bpy.ops.object.select_all(action='DESELECT')
    obj.select=True
    bpy.ops.transform.resize(value=(sx,sy,sz))    

def move(obj,sx,sy,sz):
    bpy.ops.object.select_all(action='DESELECT')
    obj.select=True
    bpy.ops.transform.translate(value=(sx,sy,sz))    

def main():
    c1=make_cube()
    s1=make_sphere()
    scale(s1,1.3,1.3,1.3)
    i1=inter(s1,c1)
    move(i1,3,3,0)
    make_material(i1,(1,1,0))
    cyl1=make_cylinder()
    c2=make_cube()
    d1=diff(c2,cyl1)
    make_material(d1,(0.5,0.5,1.0))

main()
In oper() when you call bpy.ops.object.modifier_apply() it works on the active object, which is the last object you created - the cylinder.

After you select obj1 in oper() also make obj1 the active object and you will get the result you want.

obj1.select=True
S.objects.active = obj1