Internal`InheritedBlock
I have learned recently the existence of such useful function as Internal`InheritedBlock
, from this message of Daniel Lichtblau in the official newsgroup.
As I understand, Internal`InheritedBlock
allows to pass a copy of an outbound function inside the Block
scope:
In[1]:= Internal`InheritedBlock[{Message},
Print[Attributes[Message]];
Unprotect[Message];
Message[x___]:=Print[{{x},Stack[]}];
Sin[1,1]
]
Sin[1,1]
During evaluation of In[1]:= {HoldFirst,Protected}
During evaluation of In[1]:= {{Sin::argx,Sin,2},{Internal`InheritedBlock,CompoundExpression,Sin,Print,List}}
Out[1]= Sin[1,1]
During evaluation of In[1]:= Sin::argx: Sin called with 2 arguments; 1 argument is expected. >>
Out[2]= Sin[1,1]
I think this function can be very useful for everyone who need to modify built-in functions temporarily!
Comparison with Block
Let us define some function:
a := Print[b]
Now we wish to pass a copy of this function into the Block
scope. The naive trial does not give what we want:
In[2]:= Block[{a = a}, OwnValues[a]]
During evaluation of In[9]:= b
Out[2]= {HoldPattern[a] :> Null}
Now trying to use delayed definition in the first argument of Block
(it is an undocumented feature too):
In[3]:= Block[{a := a}, OwnValues[a]]
Block[{a := a}, a]
Out[3]= {HoldPattern[a] :> a}
During evaluation of In[3]:= b
We see that in this case a
works but we have not got a copy of the original a
inside of the Block
scope.
Now let us try Internal`InheritedBlock
:
In[5]:= Internal`InheritedBlock[{a}, OwnValues[a]]
Out[5]= {HoldPattern[a] :> Print[b]}
We have got a copy of the original definition for a
inside of the Block
scope and we may modify it in the way we want without affecting the global definition for a
!