Skip to content

Replace all Module's and Block's with ModuleScope and Scope #460

Closed
@daneelsan

Description

The problem

Benefits of using ModuleScope and Scope (instead of Module and Block):

  • Not necessary to add new variables at the top of the block, i.e. Module[{variables...}, ...] (especially annoying in large functions).
  • Changing variable names is simpler (again because you don't have to rename the names at the top).
  • Merging and splitting functions is easier as it is not necessary to merge and split their argument lists.
  • No performance cost as these functions are (macro) expanded at definition time.

However, as @maxitg said:

... we still want to use Module in pattern rules (e.g., {{a_, b_}} :> Module[{c}, {{a, c}, {c, b}}]). ModuleScope is undocumented so we cannot expose it to users.

Examples

You can use MacroExpand to see what these functions do:

In[] := MacroExpand[foo[] := ModuleScope[
   a = 1;
   b = 2;
   c = 3;
]]

image

In[] := MacroExpand[bar[] := Scope[
   a = 1;
   b = 2;
   c = 3;
]]

image

Comment

It is not simply a matter of replacing all Module's with ModuleScope's. See:

In[] := MacroExpand[{x_, y_} :> ModuleScope[{x, y + 1, z}]]

image

You can use ScopeVariable to "cause particular variables to be localized":

In[] := MacroExpand[{x_, y_} :> ModuleScope[ScopeVariable[z]; {x, y + z}]]

image
But it may not be worth replacing them in these cases.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

refactorDoes not change functionality, but makes the code better organized or more readablewolfram languageRequires Wolfram Language implementation

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions