Wolfram Computation Meets Knowledge

BlockProtected

Contributed by: Richard Hennigan (Wolfram Research)

Modify definitions of protected symbols and ensure that their attributes are restored

ResourceFunction["BlockProtected"][{x,y,},expr]

evaluate expr with symbols x,y, unprotected and reprotects them before returning the result.

Examples

Basic Examples

Modify the definition of a protected symbol:

In[1]:=
Unprotect[f]; ClearAll[f];
f[x_] := 1/x;
Protect[f];
In[2]:=
ResourceFunction["BlockProtected"][{f}, f[0] = Infinity];

The definition has changed:

In[3]:=
Definition[f]
Out[3]=

More Examples

Scope

Retrieve the ResourceFunction:

In[4]:=
ResourceFunction["BlockProtected"]
Out[4]=

Retrieve the ResourceObject:

In[5]:=
ResourceObject["BlockProtected"]
Out[5]=

Generalizations & Extensions

BlockProtected will ensure that attributes for symbols are restored even if evaluation is interrupted:

In[6]:=
Unprotect[f]; ClearAll[f];
f[x_] := 1/x;
Protect[f];
In[7]:=
ResourceFunction["BlockProtected"][{f}, f[0] = Infinity; Abort[]]
Out[7]=
In[8]:=
Definition[f]
Out[8]=
In[9]:=
Catch[
 ResourceFunction["BlockProtected"][{f}, Throw[f[0] = 0]]
 ]
Out[9]=
In[10]:=
Definition[f]
Out[10]=

BlockProtected is functionally similar to using Unprotect and Protect around the evaluation:

In[11]:=
modifyProtected // ClearAll;
modifyProtected // Attributes = {HoldAllComplete};
modifyProtected[f_, eval_] :=
  Module[{result},
   Unprotect[f];
   result = eval;
   Protect[f];
   result
   ];
In[12]:=
modifyProtected[f, f[0] = "modified"];
Definition[f]
Out[12]=

However, this doesn't prevent evaluation interruptions from leaving symbols in an unprotected state:

In[13]:=
modifyProtected[f, f[0] = "unprotected"; Abort[]];
Definition[f]
Out[13]=
Out[13]=

Resource History