问题描述
如果由于惰性求值导致包未知,我如何在 R 中高效调试.我想保留基本的 browser()
功能,因为它很好用 - 即使使用 testthat 包
.如以下帖子中所述,--with-keep.source
在项目选项 => 构建工具"中为我的项目设置.
How can I debug efficiently in R if packages are unknown due to lazy evaluation. I would like to keep the basic browser()
functionality as it works great - even with the testthat package
. As explained in the following post, --with-keep.source
is set for my project in "project options => Build Tools".
要重现该行为,请创建一个包含
To reproduce the behavior, create a package TestDebug
containing
myfun <- function(a,b) {return(a+b)}
和脚本 example.R
{
browser()
TestDebug::myfun(1,2)
}
编辑:TestDebug::myfun(1,2)
调用otherpackage::myfun2(1,2)
的情况应该是也覆盖.我认为这种情况应该出现在每个真实"的包裹中?
Edit: The situation where TestDebug::myfun(1,2)
calls otherpackage::myfun2(1,2)
should be also covered. I think the situation should occur in every "real" package?
推荐答案
以下对我有用.
我有我的包 TestDebug
和我的函数
I have my package TestDebug
with my function
myfun <- function(a,b) {return(a+b)}
如果我运行脚本
debug(TestDebug::myfun)
TestDebug::myfun(1,2)
调试器直接进入 TestDebug::myfun()
的源代码,而不是像放置 browser() 时那样进入
在调用 ::
函数TestDebug::myfun(1,2)
之前.
The debugger steps right into the source of TestDebug::myfun()
not into the ::
function as it does when you place a browser()
before the call to TestDebug::myfun(1,2)
.
正如您在问题中提到的:在现实生活中,TestDebug::myfun(1,2)
经常调用 otherpackage::myfun2(1,2)
.如果您尝试进入 otherpackage::myfun2(1,2)
,您将再次进入 ::
函数.
As you mention in your question: in real-life situations TestDebug::myfun(1,2)
often calls otherpackage::myfun2(1,2)
. If you try to step into otherpackage::myfun2(1,2)
you will end up inside the ::
function again.
为了防止这种情况,我将在其他函数中调用的这个函数即时添加到 debug
索引中:
To prevent this I add this functions called inside other functions to the debug
index on the fly:
只要您在 TestDebug::myfun()
内的线路上,其中 otherpackage::myfun2(1,2)
被称为我运行 debug(otherpackage::myfun2(1,2))
在控制台中.之后,我可以毫无问题地进入 otherpackage::myfun2(1,2)
并最终进入 otherpackage::myfun2(1,2)
的源代码.(..并且不在 ::
的源代码中)
As soon as you are on the line inside TestDebug::myfun()
where otherpackage::myfun2(1,2)
is called I run debug(otherpackage::myfun2(1,2))
in the console. After that I can step into otherpackage::myfun2(1,2)
without problems and end up in the source code of otherpackage::myfun2(1,2)
. (..and not in the source code of ::
)
在确定您的问题不在 otherpackage::myfun2(1,2) 内之后,不要忘记调用
以防止调试器在下次调用时跳转到 undebug(otherpackage::myfun2(1,2))
)otherpackage::myfun2(1,2)
.
Don't forget to call undebug(otherpackage::myfun2(1,2))
after you're sure that your problem is not inside otherpackage::myfun2(1,2)
to prevent the debugger to jump into otherpackage::myfun2(1,2)
the next time it is called.
如果你愿意,你也可以使用 debugonce(otherpackage::myfun(1,2))
(而不是 debug(..)
)来只调试一个函数一次.
If you prefer you can also use debugonce(otherpackage::myfun(1,2))
(instead of debug(..)
) to only debug a function once.
这篇关于调试 package::function() 虽然使用了惰性求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!