This is expected behavior, even if it might look confusing.
Your expr_miswrote contains variables from model2. But you can “add” it as an expression to model1 because it never actually gets added to the objective or constraints of model1.
We allow it because you can actually add expressions of any type to a model.
This makes some sense as my_expr becomes one of the belongings of model.
But the arg model1 in this anonymous usage becomes pointless.
To build an anonymous expression, it suffices to write expr = JuMP.@build_expression(JuMP.value(x1)x2)
resembling con = JuMP.@build_constraint(expr <= 2), no?
To build an anonymous expression, it suffices to write
I assume you meant this as a potential feature request. Currently @build_expression doesn’t exist.
I don’t plan to make any changes to JuMP related to this issue. Yes, you can create expression in the “wrong” model, but changing this is a breaking change we won’t be doing. We also won’t be adding any new macros just to support anonymous expressions that are not affiliated with a model.