# Julia JuMP model scope

**URL:** <https://discourse.julialang.org/t/julia-jump-model-scope/121400>\
**Category:** Optimization (Mathematical)\
**Tags:** jump\
**Created:** [October 16, 2024, 8:04pm UTC](https://discourse.julialang.org/t/julia-jump-model-scope/121400 "2024-10-16T20:04:04Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![cby](https://avatars.discourse-cdn.com/v4/letter/c/df705f/32.png) [@cby](https://discourse.julialang.org/u/cby)\
**Post date:** [October 16, 2024, 8:04pm UTC](https://discourse.julialang.org/t/julia-jump-model-scope/121400/1 "2024-10-16T20:04:04Z")

</div>

I want to define a function that creates a JuMP model that then calls a function to add a set of additional constraints to that model. That set of constraints would be the same across a number of different models.

The following example gives the error: “VariableNotOwned{VariableRef}(x): the variable x cannot be used in this model because it belongs to a different model.”

```julia
function f()
    m = Model(Gurobi.Optimizer)
    @variable(m, x ≥ 0)
    @objective(m, Min, 5*x)
    g(m)
    return m
end
function g(m)
    @constraint(m, eqcon, 2*x-3 == 0)
    return m
end
mod = f()

```

The following modification works, but seems a bit tedious for large numbers of variables. Is there a better way to do this?

```julia
function g(m)
    @constraint(m, eqcon, 2*m[:x]-3 == 0)
    return m
end

```

---

<div class="post-metadata">

**Author:** ![slwu89](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/slwu89/32/217323_2.png) [@slwu89](https://discourse.julialang.org/u/slwu89)\
**Post date:** [October 16, 2024, 8:13pm UTC](https://discourse.julialang.org/t/julia-jump-model-scope/121400/2 "2024-10-16T20:13:07Z")

</div>

You can “index” a JuMP model to pull out the variable ref:

```julia
function g(m)
    x = m[:x]
    @constraint(m, eqcon, 2*x-3 == 0)
    return m
end

```

[EDIT]: sorry, I did not see the bottom “The following modification works…”

---

<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:** [October 16, 2024, 11:29pm UTC](https://discourse.julialang.org/t/julia-jump-model-scope/121400/3 "2024-10-16T23:29:43Z")

</div>

Hi @cby, take a read of this tutorial: [Design patterns for larger models · JuMP](https://jump.dev/JuMP.jl/stable/tutorials/getting_started/design_patterns_for_larger_models/)

Another approach would be

```Julia
function f()
    model = Model(Gurobi.Optimizer)
    @variable(model, x >= 0)
    @objective(model, Min, 5 * x)
    g(model, x)
    return model
end
function g(model, x)
    @constraint(model, eqcon, 2 * x - 3 == 0)
    return model
end
mod = f()

```
