What is the the proper way to define a function from an expression?
Sorry, I was too hasty in comments:
With[{expr = expr}, SetDelayed @@ Hold[f[x_], Expand[expr]]]
SetDelayed @@ Hold
is needed because of: Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs
(f[x_] := Expand@#) &@expr
Here are a couple more possibilities. Using Block
:
Clear[f]
Block[{Expand}, f[x_] = Expand[expr]];
Definition[f]
f[x_]=Expand[(1+x)^2]
Using With
:
Clear[f]
With[{expr = expr, lhs = f[x_]},
lhs := Expand[expr]
];
Definition[f]
f[x_]:=Expand[(1+x)^2]