What is the purpose of Internal`LocalizedBlock?

Internal`LocalizedBlock behaves the same as Block, but it can localize non-Symbols (e.g. f[1], Subscript[x, 0], etc.).

For example,

Internal`LocalizedBlock[{Subscript[x, 0]}, Subscript[x, 0] = 1]
(* 1 *)

Compare this to

Block[{Subscript[x, 0]}, Subscript[x, 0] = 1]
(* During evaluation of In[79]:= Block::lvsym: Local variable specification {Subscript[x, 0]} contains Subscript[x, 0], which is not a symbol or an assignment to a symbol. >> *)
(* Block[{Subscript[x, 0]}, Subscript[x, 0] = 1] *)

It's also worth noting that one cannot assign values in the first argument of Internal`LocalizedBlock


Disclaimer: these are all guesses, believe at your own risk.

As the first argument, you specify a list of patterns to localize. For example, {x}, {x[2]}, {x[][2]}, or x[2]/;True

This creates a dynamic environment around the second argument inside which the following happens:

  • Changes to those patterns' own/down/subvalues while in the environment aren't kept after its execution.
  • If the pattern is

    • a symbol (e.g x, f):

      works like block, and all of the symbol's definitions don't apply inside the localized block

    • a non-pattern pattern that doesn't have a downvalue/subvalue outside the environment: (by non-pattern pattern I just mean a pattern that don't have conditions, pattern tests, blanks, etc. such as x[2]] or x[][5]. I wonder if there's a standard name in the community for these)

      does nothing

    • any other pattern patt:

      Temporarily set the definition patt:=System`Private`$Localized. This is a definition that makes the whole downvalue/subvalue lookup fail to find a match. Here is a usage example;

Low importance note: this changes seem to be applied in order of appearance, so if the first argument is {x, x[2]/;True}, then the definition x[2]/;True:=SystemPrivate$Localized will be added, while it won't be with the order reversed to x[2]/;True, x}

Summary

You can use it to

  • Change specific down/sub/ownvalues of a symbol while in a dynamic environment without it affecting the outside, but allowing all other definitions changes to leak.
  • Work with the outside definitions of the symbol but making some particular pattern behave as undefined.