I have a naive question. Is there a general method to use some codes like this
ex:=A C+B C-A D-B D; factor_in(_,$A,B$);
to obtain $(A+B)(C-D)$?
You can use sympy.factor, e.g.
sympy.factor
ex:= A C + B C - A D - B D; ex=Ex(sympy.factor(ex).__str__())
(I should probably add automatic conversion from sympy objects to Ex, so that you can avoid the __str__()).
Ex
__str__()