JuliaInterop / NBInclude.jl

import code from IJulia Jupyter notebooks into Julia programs
Other
117 stars 17 forks source link

A way to check if code is running in NBInclude #21

Closed knuesel closed 2 years ago

knuesel commented 3 years ago

It would be nice to have a function available in notebooks to check if code is being run by NBInclude. I currently do something like this:

in_nbinclude() = contains(@__FILE__, r".:In\[.*\]$")

# then in later cells:

...
if !in_nbinclude()
    display(...)  # This won't display anything when run with nbinclude
end
...

This is related to #20. However using cell exclusions like in #20 requires setting regex in every @nbinclude call.

stevengj commented 3 years ago

I guess we could add an in_nbinclude() = _in_nbinclude[] function in the NBInclude modue, where we define the global const _in_nbinclude = Ref(false) and then set _in_nbinclude[] = true in the nbinclude function by changing ret = my_include_string(m, s, string(path, ":In[", cellnum, "]"), prev, softscope) to

ret = try
    _in_nbinclude[] = true
    my_include_string(m, s, string(path, ":In[", cellnum, "]"), prev, softscope)
finally
    _in_nbinclude[] = false
end

Do you want to take a crack at a PR?

knuesel commented 3 years ago

That looks good, thanks! I'm happy to make a PR (no time right now but in a few days).

stevengj commented 3 years ago

Thinking about it a bit more, it should probably use task-local storage rather than a single global variable.

stevengj commented 3 years ago

In particular, define:

const _in_nbinclude = :in_nbinclude_0db19996_df87_5ea3_a455_e3a50d440464 # unique symbol based on our UUID4
in_nbinclude() = get(Base.task_local_storage(), _in_nbinclude, false)::Bool

and then do

ret = Base.task_local_storage(_in_nbinclude, true) do
    my_include_string(m, s, string(path, ":In[", cellnum, "]"), prev, softscope)
end
knuesel commented 2 years ago

Thanks! (sorry for the silence, it's a busy time...)