Plural macros (e.g. @variables) should return collection of the defined objects

When working on a large model it is extremely useful to be able to manipulate large groups of variables or constraints.

To avoid repeating long lists of variable names or equations, it would be very useful if the the ‘plural macros’ (e.g. @variables and @constraints), returned collections of the newly defined objects.

For example I would like for

vars = @variables model begin
  x
  y[1:2]
end

to be equivalent to writing

@variables model begin
  x
  y[1:2]
end
vars = [x, y]

and

eqs = @NLconstraints model begin
  E_x, x == 1
  E_y[i ∈ 1:2], y[i] == x
end

should be equivalent to writing

@NLconstraints model begin
  E_x, x == 1
  E_y[i ∈ 1:2], y[i] == x
end
eqs = [E_x, E_y]

Note that this is not just a matter of laziness, but that repeating long lists of items is prone to hard-to-debug errors. I.e. spotting which item is missing in a large collection of variables or constraints can take a long time.

Has this feature been discussed before?

1 Like

This seems reasonable.

Want to open an issue with this in the JuMP.jl GitHub repository? https://github.com/jump-dev/JuMP.jl/issues

Absolutely. I was about to open a “feature request” issue yesterday, but the documentation suggested that it might be worth discussing here first.

I have no experience with meta programming in Julia yet, but glancing at the source code it looks pretty manageable as all the plural versions of the macros are already implemented together in one place rather than for each macro.

1 Like

I have opened an issue here: https://github.com/jump-dev/JuMP.jl/issues/2837

This would also serve as a work-around for the issue where list_of_constraint_types and hence all_constraints do not work for non-linear constraints.

1 Like

I added all_nl_constraints which will be in the next JuMP release.