Can I name new JuMP constraints in a function using an argument?

I’m trying to define a function that would add a JuMP constraint to a model, and I would like to set the name of the constraint using an argument from the function. When I have tried to do this in the past it just sets the name of the constraint to be the name of the argument instead of the value of the argument. And if I run the function multiple times it will error because the named constraint already exists.

A simplified example function would look like this:

function add_constraint!(model, cons_name, value, array, range)
   @constraint(model, cons_name[r in 1:length(range)], array[r] <= value)


In the code above, I would like the name of the constraint to be whatever get’s passed into the function as the cons_name argument. How can I do that?


Hi there, welcome to the forum.

See this part of the docs: Constraints · JuMP.

If cons_name is a String, you’re probably looking for something like:

function add_constraint!(model, cons_name::String, value, array, range)
    return model[Symbol(cons_name)] = @constraint(
        [r in 1:length(range)],
        array[r] <= value,
        base_name = cons_name,

Thank you! This worked