Python automate Assign parent relation and keep transform I have automated the task of parenting in Blender with Python.
The code affects the relation parent according to the two last characters of the names of the objects.
example:

obj1.name = Cube.01
obj2.name = Suzanne.01


If obj1 is in the group "children" and obj2 is not in the group "children" : obj2 is the parent of obj1.
My code works, but without keeping children's transformation.
How can I do to keep the children's transformation?

import bpy

for obj1 in bpy.context.selected_objects:    
    if obj1.name in  bpy.data.groups["Children"].objects:
    a = obj1.name[-2:]

    for obj2 in bpy.context.selected_objects:
            if obj2.name not in  bpy.data.groups["Children"].objects:
                b = obj2.name[-2:]
                if a == b:                       
                   obj1.parent= obj2
You have to set the inverse matrix  of the child to clear the initial transformation of the parent at parenting moment :

obj1.parent= obj2
obj1.matrix_parent_inverse = obj2.matrix_world.inverted()