I was looking to orient an object to a selected active face of another object in Blender 3.2.
Already found other similar questions, but none worked:
Align to face normal vector (took code from here)
Align Object A to Object B to their respective active faces with python
Python script get face normal, then set it as another object's orientation (Z-axis) accordingly
The code so far(thanks to batFinger, slightly changed, since multiplication of vectors and matrices is now performed with a @, swince Blender 2.8+):
import bpy
from mathutils import Matrix, Vector
import bmesh
context = bpy.context
obj = context.edit_object
mw = obj.matrix_world.copy()
bm = bmesh.from_edit_mesh(obj.data)
# for this example jmake a face active
face = bm.select_history.active
o = face.calc_center_median()
# calculate the axis dif in local coords
axis_src = face.normal
# local z-axis
axis_dst = Vector((0, 0, 1))
matrix_rotate = mw.to_3x3()
matrix_rotate = matrix_rotate * axis_src.rotation_difference(axis_dst).to_matrix()
matrix_translation = Matrix.Translation(mw * o)
obj2 = context.scene.objects.get("Cube.001")
obj2.matrix_world = matrix_translation * matrix_rotate.to_4x4()
The script expects a second object called Cube.001.