# Returning module from a macro: why do we need :toplevel?

**URL:** https://discourse.julialang.org/t/returning-module-from-a-macro-why-do-we-need-toplevel/130346
**Category:** General Usage
**Tags:** macros, metaprogramming
**Created:** [June 30, 2025, 7:45pm UTC](https://discourse.julialang.org/t/returning-module-from-a-macro-why-do-we-need-toplevel/130346 "2025-06-30T19:45:18Z")
**Posts on this page:** 1
**Page:** 1

<div class="post-metadata">

### Author: ![moble](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/moble/32/23535_2.png) [@moble](https://discourse.julialang.org/u/moble)
#### Post date: [June 30, 2025, 7:45pm UTC](https://discourse.julialang.org/t/returning-module-from-a-macro-why-do-we-need-toplevel/130346/1 "2025-06-30T19:45:18Z")

</div>

This [may have worked in the early days](https://github.com/JuliaLang/julia/issues/1200), and as claimed [here](https://discourse.julialang.org/t/module-generation-from-macros/2555/6) worked in Julia 1.4:

```julia
macro mymodule(name)
    modname = esc(name)
    return :(module $modname end)
end
@mymodule MyMod

```

But then it didn’t work in 1.5, and doesn’t work now.

The only way I know to make that work is to wrap the returned `Expr` in a `:toplevel` `Expr`:

```julia
macro mymodule(name)
    modname = esc(name)
    return Expr(:toplevel, :(module $modname end))
end
@mymodule MyMod

```

Why is this? I can `@macroexpand` the original, and it doesn’t appear to be hiding the module in some block or anything. Why isn’t the first version allowed? Is there something better I should be doing?
