So, instead of passing a string which Books.jl
will evaluate, Books.jl
can also obtain the code for a method directly. (Thanks to CodeTracking.@code_string
.) For example, inside our package, we can define the following method:
function my_data()
DataFrame(A = [1, 2], B = [3, 4], C = [5, 6], D = [7, 8])
end
To show code and output (sco) for this method, use the @sco
macro. This macro is exported by Books, so ensure that you have using Books
in your package.
```jl
@sco M.my_data()
```
This gives
function my_data()
DataFrame(A = [1, 2], B = [3, 4], C = [5, 6], D = [7, 8])
end
my_data()
A | B | C | D |
---|---|---|---|
1 | 3 | 5 | 7 |
2 | 4 | 6 | 8 |
To only show the source code, use @sc
:
```jl
@sc M.my_data()
```
resulting in
function my_data()
DataFrame(A = [1, 2], B = [3, 4], C = [5, 6], D = [7, 8])
end
To override options for your output, use the pre
keyword argument of @sco
:
```jl
let
caption = "This caption is set via the pre keyword."
pre(out) = Options(out; caption)
@sco pre=pre my_data()
end
```
which appears to the reader as:
function my_data()
DataFrame(A = [1, 2], B = [3, 4], C = [5, 6], D = [7, 8])
end
my_data()
A | B | C | D |
---|---|---|---|
1 | 3 | 5 | 7 |
2 | 4 | 6 | 8 |
See ?sco
for more information. Since we’re using methods as code blocks, we can use the code shown in one code block in another. For example, to determine the mean of column A:
```jl
@sco M.my_data_mean(my_data())
```
shows as
function my_data_mean(df::DataFrame)
Statistics.mean(df.A)
end
my_data_mean(my_data())
1.5
Or, we can show the output inline, namely 1.5, by using
`jl M.my_data_mean(my_data())`
It is also possible to show methods with parameters. For example,
```jl
@sc M.hello("" )
```
shows
hello(name) = "Hello, $name"
Now, we can show
M.hello("World")
Hello, World
Here, the M
can be a bit confusing for readers. If this is a problem, you can export the method hello
to avoid it. If you are really sure, you can export all symbols in your module with something like this.