# Dynamically Naming Expressions and Constraints in JuMP

**URL:** <https://discourse.julialang.org/t/dynamically-naming-expressions-and-constraints-in-jump/110181>\
**Category:** Optimization (Mathematical)\
**Tags:** jump, optimization\
**Created:** [February 13, 2024, 11:24pm UTC](https://discourse.julialang.org/t/dynamically-naming-expressions-and-constraints-in-jump/110181 "2024-02-13T23:24:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lemma](https://avatars.discourse-cdn.com/v4/letter/l/e0b2c6/32.png) [@Lemma](https://discourse.julialang.org/u/Lemma)\
**Post date:** [February 13, 2024, 11:24pm UTC](https://discourse.julialang.org/t/dynamically-naming-expressions-and-constraints-in-jump/110181/1 "2024-02-13T23:24:48Z")

</div>

In JuMP, it appears that expressions, constraints, and variables cannot be dynamically named using string interpolation (i.e., the `$` symbol) directly within the identifiers of the `@variable` or `@expression` macros. Given this limitation, I am curious about the best approach to dynamically generate names for expressions and constraints within a loop.

Currently, my workaround involves defining an empty dictionary outside the loop, which is then populated with expressions and constraints as follows:

```julia
exp = Dict()
for s in 1:S
    exp[s] = @expression(model, sum(a[i] * x[i] for i in 1:n))
    # Additional code follows
end

```

Is this approach considered the recommended practice for naming expressions and constraints dynamically?

---

<div class="post-metadata">

**Author:** ![odow](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/odow/32/28685_2.png) [@odow](https://discourse.julialang.org/u/odow)\
**Post date:** [February 13, 2024, 11:48pm UTC](https://discourse.julialang.org/t/dynamically-naming-expressions-and-constraints-in-jump/110181/2 "2024-02-13T23:48:43Z")

</div>

> Currently, my workaround involves defining an empty dictionary outside the loop, which is then populated with expressions and constraints as follows:

Yes, this is a good approach.

JuMP variables and expressions are just regular Julia types. They are not special. The JuMP macros provide some convenient constructors, like `@expression(model, exp[s in 1:S], ...)`, but you don’t need to use them. Use whatever data structures are most convenient for your problem.

See also, parts of the docs like this [Variables · JuMP](https://jump.dev/JuMP.jl/stable/manual/variables/#User-defined-containers), or tutorials like [The network multi-commodity flow problem · JuMP](https://jump.dev/JuMP.jl/stable/tutorials/linear/multi_commodity_network/).
