# Scopes: accessing a global variable hidden by a local of the same name

**URL:** <https://discourse.julialang.org/t/scopes-accessing-a-global-variable-hidden-by-a-local-of-the-same-name/107253>\
**Category:** New to Julia\
**Tags:** question, scope\
**Created:** [December 7, 2023, 5:18am UTC](https://discourse.julialang.org/t/scopes-accessing-a-global-variable-hidden-by-a-local-of-the-same-name/107253 "2023-12-07T05:18:28Z")\
**Posts on this page:** 1\
**Showing post:** 3

<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:** [December 7, 2023, 2:24pm UTC](https://discourse.julialang.org/t/scopes-accessing-a-global-variable-hidden-by-a-local-of-the-same-name/107253/3 "2023-12-07T14:24:16Z")

</div>

> [@ryofurue](#):
>
> By just a guess, I discovered that `Main.x` is accessible. So, is this the “official” way?

That only works if the global variable is in the `Main` module, e.g. if you are running the code in the REPL. It won’t work in any other module. But if you know what module `Foo` the global symbol is defined in, you can reference it as `Foo.x`.

The more common solution is to rename your local variables so that they don’t conflict with any global symbols you want to access. For example, if you want to call the [`sum`](https://docs.julialang.org/en/v1/base/collections/#Base.sum) function, but also have a local variable named `sum`, you can either call `sum(...)` via `Base.sum(...)` or rename your local variable (e.g. to `s`).

If you are getting these local variables by code generation / metaprogramming (which you should [rarely do](https://discourse.julialang.org/t/how-to-warn-new-users-away-from-metaprogramming/35022/22)), then you need to be careful of [“hygiene”](https://en.wikipedia.org/wiki/Hygienic_macro) — don’t generate variable names like `x`, but instead use [`gensym()`](https://docs.julialang.org/en/v1/base/base/#Base.gensym) or similar to generate unique local-variable names. If the generated local-variable names come from an external source pass them through `gensym` to hygienize them. (A Julia `macro` does this for you automatically.)

> [@ryofurue](#):
>
> But, I have a legitimate use for this, but to describe it would double the length of this message.

By not including this context, you have probably doubled the work of the people trying to respond to you, because now we have to guess at things like “where does the conflict come from?”, “why can’t you just rename your local variable?”, and “do you know the module where the global symbol is defined?” in order to answer your question in several different scenarios.

---

_[View the full topic](https://discourse.julialang.org/t/scopes-accessing-a-global-variable-hidden-by-a-local-of-the-same-name/107253)._
