In JuMP, how to access a named constraint created inside a function

I would like to delete a constraint created inside a function. For example,

function mymodel(a)
    m = Model()
    @variable(model, w[1:n] >= 0)
    @constraint(model, budget, sum(w) == a)
        ...
    return m
end
model = mymodel(1)
delete(model, budget)

throws ERROR: LoadError: UndefVarError: budget not defined
How may I access the constraint budget from outside the function?
Thanks in advance!

@constraint creates a perfectly normal variable inside the scope it is used. You can deal with it as you would with any other variable (for example, returning it from inside the function).

Nevertheless, @constraint also register any named constraint inside the model (as @variable does with variables), so you can access it by using model[:budget] too. I use it all the time, it is a very practical feature. delete will take care of removing budget from this listing too.

4 Likes

Perfect! delete(model, model[:budget]) worked fine. Thank you very much

1 Like