Wolfram Research

Function Repository Resource:

BlockProtected

Source Notebook

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

Contributed by: Richard Hennigan (Wolfram Research)

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

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

Examples

Basic Examples

Modify the definition of a protected symbol:

The definition has changed:

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

Scope

Retrieve the ResourceFunction:

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

Retrieve the ResourceObject:

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

Generalizations & Extensions

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

In[4]:=
ResourceFunction["BlockProtected"][{f}, f[0] = Infinity; Abort[]]
Out[4]=
In[5]:=
Definition[f]
Out[5]=
In[6]:=
Catch[
 ResourceFunction["BlockProtected"][{f}, Throw[f[0] = 0]]
 ]
Out[6]=
In[7]:=
Definition[f]
Out[7]=

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

In[8]:=
modifyProtected[f, f[0] = "modified"];
Definition[f]
Out[8]=

However, this does not prevent evaluation interruptions from leaving symbols in an unprotected state:

Out[8]=
Out[8]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information