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

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 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), then you need to be careful of “hygiene” — don’t generate variable names like x, but instead use 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.)

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.

6 Likes