# Accessing Variable Values Dynamically in Julia

**URL:** <https://discourse.julialang.org/t/accessing-variable-values-dynamically-in-julia/116136>\
**Category:** New to Julia\
**Created:** [June 24, 2024, 10:51am UTC](https://discourse.julialang.org/t/accessing-variable-values-dynamically-in-julia/116136 "2024-06-24T10:51:57Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)\
**Post date:** [June 24, 2024, 3:25pm UTC](https://discourse.julialang.org/t/accessing-variable-values-dynamically-in-julia/116136/12 "2024-06-24T15:25:26Z")

</div>

> [@Pablo\_Marchant](#):
>
> Just returning a tuple with the values of interest is far faster.

In particular, a friendly, idiomatic, and performant way to go about it would be to return a [named tuple](https://docs.julialang.org/en/v1/manual/functions/#Named-Tuples):

```julia
function do_stuff2(x)
    a = x^2
    b = a*cos(x)
    c = b*exp(x) + a
    return (; a, b, c)
end

```

makes it easy for the caller to extract any variables they want. e.g. if the caller wants `a` and `c`, they can do:

```julia
julia> (; a, c) = do_stuff2(3.7);

julia> a
13.690000000000001

julia> c
-455.92299991101584

```

In general, I would say that you are fighting with the language by using `Base.@locals` and arrays of symbols here. You can get something that works, but it will be slow (e.g. type-unstable and allocating), fragile, and hard for other Julia programmers to understand. Better to learn how to write idiomatic code, use appropriate data structures, and think carefully about the useful inputs/outputs of your functions (your API) rather than trying to give the caller blanket access to all local variables.

[Don’t reach for “metaprogramming”](https://discourse.julialang.org/t/how-to-warn-new-users-away-from-metaprogramming/35022) (e.g. generated lists of variable names, code introspection, passing code as strings) as your first resort.

---

_[View the full topic](https://discourse.julialang.org/t/accessing-variable-values-dynamically-in-julia/116136)._
