Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FAQ entry on calling un-patched function inside patch #136

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

kleinschmidt
Copy link

I've added an FAQ entry on how to call the "un-patched" version of a function inside a patch (if you e.g. want to modify the arguments before calling a function).

@omus mentioned that using @mock inside a patch can be useful as well but I couldn't immediately come up with an example off the top of my head, so I just left a short note about that being possible.

I've added an FAQ entry on how to call the "un-patched" version of a function inside a patch (if you e.g. want to modify the arguments before calling a function).

@omus mentioned that using `@mock` inside a patch can be useful as well but I couldn't immediately come up with an example off the top of my head, so I just left a short note about that being possible.
Comment on lines +38 to +57
Simply call the patched function without `@mock`:

```julia
julia> f(x) = x + 1
f (generic function with 1 method)

julia> g(x) = @mock(f(x)) * 2
g (generic function with 1 method)

julia> fp = @patch f(x) = f(-x)
Patch{typeof(f)}(f, var"##f_patch#240")

julia> g(3)
8 # = (3 + 1) * 2

julia> apply(fp) do
g(3)
end
-4 # = (-3 + 1) * 2
```
Copy link
Member

@omus omus Oct 10, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here's probably a more useful example:

Suggested change
Simply call the patched function without `@mock`:
```julia
julia> f(x) = x + 1
f (generic function with 1 method)
julia> g(x) = @mock(f(x)) * 2
g (generic function with 1 method)
julia> fp = @patch f(x) = f(-x)
Patch{typeof(f)}(f, var"##f_patch#240")
julia> g(3)
8 # = (3 + 1) * 2
julia> apply(fp) do
g(3)
end
-4 # = (-3 + 1) * 2
```
Simply call the function without using `@mock` within the patch. For example we can count the number of calls a recursive function does like this:
```julia
function fibonacci(n)
if n <= 1
return n
else
return @mock(fibonacci(n - 1)) + @mock(fibonacci(n - 2))
end
end
calls = Ref(0)
p = @patch function fibonacci(n)
calls[] += 1
return fibonacci(n) # Calls original function
end
apply(p) do
@test @mock(fibonacci(1)) == 1
@test calls[] == 1
calls[] = 0
@test @mock(fibonacci(4)) == 3
@test calls[] == 9
end
```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants