# Defining methods in isolation in \`jldoctest\`s

**URL:** <https://discourse.julialang.org/t/defining-methods-in-isolation-in-jldoctest-s/87263>\
**Category:** Tooling\
**Tags:** package, documentation, documenter\
**Created:** [September 14, 2022, 9:19am UTC](https://discourse.julialang.org/t/defining-methods-in-isolation-in-jldoctest-s/87263 "2022-09-14T09:19:07Z")\
**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:** [September 14, 2022, 9:19am UTC](https://discourse.julialang.org/t/defining-methods-in-isolation-in-jldoctest-s/87263/1 "2022-09-14T09:19:07Z")

</div>

With `Documenter.jl`, each code block evaluates [in its own scope](https://juliadocs.github.io/Documenter.jl/stable/man/doctests/#Preserving-Definitions-Between-Blocks):

> Every doctest block is evaluated inside its own `module` . This means that definitions (types, variables, functions etc.) from a block can _not_ be used in the next block.

Is it possible to define explanatory methods in code blocks so that they don’t leak into the global environment?

For example, how can I achieve the following?

````julia
module MWE

"""
	foo(x)

Example method definition:

```jldoctest
julia> MWE.foo(x::Int) = @info "new method" x

julia> foo(42)
┌ Info: new method
└ x = 42
```
"""
function foo(x)
	@info "fallback method" x
end

"""
	bar(x)

```jldoctest
julia> foo(42)
┌ Info: fallback method
└ x = 42
```
"""
function bar(x) end

end # module MWE

````

Note that fixing the doctests with `Documenter` causes the new method to be used in `bar`’s docstring, instead of the fallback method.

---

<div class="post-metadata">

**Author:** ![mortenpi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mortenpi/32/158_2.png) [@mortenpi](https://discourse.julialang.org/u/mortenpi)\
**Post date:** [September 17, 2022, 5:35am UTC](https://discourse.julialang.org/t/defining-methods-in-isolation-in-jldoctest-s/87263/2 "2022-09-17T05:35:17Z")

</div>

Since we run the doctests in the same Julia session, just different modules, they are bound to leak (defining `MWE.foo(x::Int)` is basically type piracy). However, it might be possible to erase the temporary methods in `DocTestSetup`, similar to how Revise does it?
