是否可以暂时重命名和阻止内置函数? [英] Is it possible to rename and block built-in functions temporarily?
问题描述
我想临时重命名一个内置符号并使用不同的名称,同时阻止该符号的主名称.例如,我希望下面的代码只打印2"而不是1"和3":
I wish to temporarily rename a built-in symbol and use it with different name while block the main name of this symbol. For example, I wish the following code to print only "2" but not "1" and "3":
Block[{print = Print, Print}, Print[1]; print[2]; Print[3];]
实际上,上面的代码没有打印任何内容.
In really the above code prints nothing.
是否可以让 print
在这样的代码中工作而完全阻止符号 Print
?
Is it possible to make print
working inside such code while completely block symbol Print
?
类似的解决方案
With[{Print = f, print = Print}, Print[1]; print[2]; Print[3];]
不适合,因为 Print
在此类代码中并未真正被阻止.
are not suitable since Print
is not really blocked inside such code.
问题出现时思考一种禁用跟踪的方法消息
内部.
The question appeared while thinking on a way to disable tracing of Message
internals.
推荐答案
这不是很干净,但我相信它是有用的.
This is not very clean, but I believe it is serviceable.
Internal`InheritedBlock[{Print},
Unprotect[Print];
Print[x__] := Null /; ! TrueQ[$prn];
print[x__] := Block[{$prn = True}, Print[x]];
Print[1]; print[2]; Print[3];
]
<小时>
如果在返回中将函数替换为 Null
是不可接受的,您可能需要使用类似的东西:
If it is not acceptable to have the function replaced with Null
in the return, you may need to use something like:
func[x__] := Hold[func[x]] /; ! TrueQ[$prn];
在块之后是 ReleaseHold
.
或者:
func[x__] := zz[x] /; ! TrueQ[$prn];
然后跟随块:/.z->函数
这篇关于是否可以暂时重命名和阻止内置函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!