Version 12.2
In version 12.2, use the new function WithCleanup[]
:
With[{plotOptions = Options[Plot]},
WithCleanup[SetOptions[Plot, PlotStyle -> Green],
Plot[Sin[x], {x, -π, π}],
SetOptions[Plot, plotOptions]]]
which is a direct replacement of the older undocumented function described below.
Older versions
Usual caveats about using undocumented functions aside, here is how one might use Internal`WithLocalSettings[]
:
With[{plotOptions = Options[Plot]},
Internal`WithLocalSettings[SetOptions[Plot, PlotStyle -> Green],
Plot[Sin[x], {x, -π, π}],
SetOptions[Plot, plotOptions]]]
but I do not think this to be any better than Nasser's proposal. As can be surmised from how it was used above, you can think of the three arguments of Internal`WithLocalSettings[]
as three stages: setup, body, and clean-up. Carl notes in a comment below that the advantage of using this function is that any code in the first and third arguments are uninterruptible.
A more usual case for its use would be for localizing changes to system settings that are not easily accessible to SetOptions[]
. Using the Wizard's code from here as an example:
With[{spopt = SystemOptions["SparseArrayOptions"]},
Internal`WithLocalSettings[
SetSystemOptions["SparseArrayOptions" -> {"TreatRepeatedEntries" -> 1}],
ind = {{3, 1}, {3, 3}, {1, 3}, {2, 1}, {3, 2}, {3, 1},
{3, 2}, {3, 3}, {1, 3}, {3, 1}};
val = {1, 1, 3, 0, 3, 4, 3, 1, 1, 1};
SparseArray[ind -> val] // Normal,
SetSystemOptions[spopt]]]
{{0, 0, 4}, {0, 0, 0}, {6, 6, 2}}
(See also this SO thread and this example usage by Oleksandr.)
Internal`InheritedBlock[{Plot}, SetOptions[Plot, Frame -> True]; Plot[x, {x, 0, 1}] ]
like this? $\endgroup$Options[Plot]
, do your custom stuff, and useSetOptions[]
again at the end? $\endgroup$Internal`WithLocalSettings[]
is also a possibility. $\endgroup$