# Conditionally defining a macro

**URL:** https://discourse.julialang.org/t/conditionally-defining-a-macro/70690
**Category:** General Usage
**Created:** [October 31, 2021, 2:50pm UTC](https://discourse.julialang.org/t/conditionally-defining-a-macro/70690 "2021-10-31T14:50:19Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![Mark\_Nahabedian](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mark_nahabedian/32/16562_2.png) [@Mark\_Nahabedian](https://discourse.julialang.org/u/Mark_Nahabedian)
#### Post date: [October 31, 2021, 2:50pm UTC](https://discourse.julialang.org/t/conditionally-defining-a-macro/70690/1 "2021-10-31T14:50:19Z")

</div>

I want to be able to modify a bunch of definitions depending on whether another file is included. In the parlance of Aspect Oriented programming, that file would implement an `aspect` which I could optionally include. I would use a macro to explicityly identify the cutpoints where the aspect has effect.

To minimize the change in my original source file, I’d just wrap each expression to be affected with a macro. That macro would be the identity macro if it has no other definition.

To this end, I want to conditionally define a macro to an identity macro if the macro is not otherwise defined:

```julia
try
    @mymacro()
catch e
    if e isa UndefVarError
        macro mymacro(e)
            e
        end
    end
end

```

but this fails with

```julia
ERROR: syntax: macro definition not allowed inside a local scope

```

In CommonLisp, top levelexpressions are evaluated at both compile time and load time, unless explicity wrapped in EVAL-WHEN. I’ve not seen explicit documentation of Julia’s semantics for top level expressions, but it appears that only certain top level expressions have compile time effect: macro definitions, and possibly `const` declarations. Is my assumption on-track?

What is the right way to conditionally define a macro if it is not yet defined?

Thanks.

---

<div class="post-metadata">

### Author: ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)
#### Post date: [October 31, 2021, 4:37pm UTC](https://discourse.julialang.org/t/conditionally-defining-a-macro/70690/2 "2021-10-31T16:37:20Z")

</div>

Maybe just use `isdefined`:

```julia
julia> module M
           macro m() :() end
       end
Main.M

julia> isdefined(M, Symbol("@m"))
true

```

so:

```julia
if !isdefined(@ __MODULE__ , Symbol("@mymacro"))
    macro mymacro(ex)
        esc(ex)
    end
end
```
