如何防止包重新加载?
考虑以下情况
Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];
当我第二次执行它时,速度快了 10 倍,并且不会打印兼容性警告。
- Mathematica 如何知道这个包已经被加载了?
- 在从
$ContextPath
加载和删除包时,避免重新加载包的好方法是什么?
我依赖 Combinatorica 来实现一些图形算法,但每次加载时我都需要重新定义 Element
,所以我试图将重新加载保持在最低限度
Consider the following
Needs["Combinatorica`"];
$ContextPath = DeleteCases[$ContextPath, "Combinatorica`"];
When I execute it the second time, it's 10 times faster and it doesn't print the compatibility warning.
- How does Mathematica know this package has been loaded already?
- What's a good way to avoid reloading the package when it's been loaded and removed from
$ContextPath
?
I'm relying on Combinatorica for some graph algorithms, but I need to redefine Element
every time it is loaded, so I'm trying to keep reloading to minimum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自需求的使用消息:
您是否与其他人共享您的代码,或者您可以编辑您的 Combinatorica 副本以不添加有问题的 Element 定义吗? (可能应该验证 Combinatorica 没有以会导致问题的方式在内部使用它。)
From the usage message for Needs:
Are you sharing your code with anyone else, or could you just edit your copy of Combinatorica to not add the problematic definition for Element? (Should probably verify that Combinatorica isn't using it internally in a way that would cause problems.)
您可能想查看
$Packages
变量。第一次加载时,您的上下文会附加到其中。第二次,它根本没有加载,因为它已经在$Packages
中,所以第二次什么也没有发生(除了将上下文带回到$Packages
中) >$ContextPath,但你还是删除它)。您可以使用On[Get]
验证Get
是否未被第二次调用。由于第二次没有实际重新加载,因此您无需执行任何操作。但这也意味着如果你想真正重新加载包,你必须首先从
$Packages
中删除它的上下文,否则调用Needs
除了将您的上下文返回到$ContextPath
上之外,不会执行任何操作。You probably want to look at
$Packages
variable. The first time you load, your context gets appended to it. The second time, it is not loaded at all, since it is already in$Packages
, so nothing is happening thesecond time (apart from bringing the context back on the$ContextPath
, but you delete it anyway). You can verify thatGet
is not invoked the second time by usingOn[Get]
.Since there is no actual reloading happening the second time, you don't have to do anything. But this also means that if you want to really reload the package, you have to first delete its context from
$Packages
, otherwise the call toNeeds
will do nothing except returning your context back on the$ContextPath
.