# How to tell if code is being run in global scope?

**URL:** https://discourse.julialang.org/t/how-to-tell-if-code-is-being-run-in-global-scope/92982
**Category:** General Usage
**Tags:** macros, scope
**Created:** [January 15, 2023, 5:40am UTC](https://discourse.julialang.org/t/how-to-tell-if-code-is-being-run-in-global-scope/92982 "2023-01-15T05:40:09Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Jollywatt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jollywatt/32/202198_2.png) [@Jollywatt](https://discourse.julialang.org/u/Jollywatt)
#### Post date: [January 15, 2023, 5:40am UTC](https://discourse.julialang.org/t/how-to-tell-if-code-is-being-run-in-global-scope/92982/1 "2023-01-15T05:40:09Z")

</div>

How do you tell if code is being evaluated at top-level, or directly into the REPL?

I have a macro that defines some variables in the current scope. For example:

```julia
macro defs(n)
	assignments = [:($(esc(Symbol("x$i"))) = $i) for i in 1:n]
	quote $(assignments...) end
end

@defs 3
# expands to:
quote
    x1 = 1
    x2 = 2
    x3 = 3
end

```

If this is entered into the REPL, I want to show an informative message like

```julia
julia> @defs 3
[ Info: Defined global variables: x1, x2, x3

```

but I don’t want this message to be shown when used in a local scope, e.g., in a function definition:

```julia
julia> function foo()
           x = 42
           @defs 5
           x + x5
       end
foo (generic function with 1 method)
# no info message

```

Is this possible to do with Julia macros?

_Edit:_ this might be an XY problem, so I’m open to workarounds — I just want to inform the user when something “permanent” happens, like defining variables in global scope.

---

<div class="post-metadata">

### Author: ![marius311](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marius311/32/3953_2.png) [@marius311](https://discourse.julialang.org/u/marius311)
#### Post date: [January 15, 2023, 6:13am UTC](https://discourse.julialang.org/t/how-to-tell-if-code-is-being-run-in-global-scope/92982/2 "2023-01-15T06:13:25Z")

</div>

See [https://discourse.julialang.org/t/is-there-a-way-to-determine-whether-code-is-toplevel](https://discourse.julialang.org/t/is-there-a-way-to-determine-whether-code-is-toplevel) and [https://discourse.julialang.org/t/should-macros-get-an-istoplevel-or-scope-argument](https://discourse.julialang.org/t/should-macros-get-an-istoplevel-or-scope-argument)
