Questions tagged [scoping]

Questions on Mathematica's scoping constructs (Block, Module, With, etc.)

Filter by
Sorted by
Tagged with
257 votes
9 answers
19k views

What are the use cases for different scoping constructs?

Mathematica includes three functions that I know of which can be used to effectively (if not actually) define a variable and give it a value within a local scope: ...
David Z's user avatar
  • 4,911
50 votes
5 answers
3k views

Enforcing correct variable bindings and avoiding renamings for conflicting variables in nested scoping constructs

Using global variables the following turns an "expression" into a Function: expr = 2 x; Function[x, Evaluate[expr]] Of course ...
einbandi's user avatar
  • 4,024
90 votes
6 answers
3k views

How to avoid nested With[]?

With[ {v1 = #}, With[ {v2 = f[v1]}, g[v1, v2] ] ] How to avoid nested With[] like the above? I'd like to use <...
user13253's user avatar
  • 8,666
5 votes
4 answers
620 views

Expressions containing globally undefined symbols inside a function where they are defined

Consider the following code. f[a_,b_]:=x x=a+b; f[1,2] (* a + b *) From a certain viewpoint, one might expect it to return 3 ...
imakhlin's user avatar
  • 167
10 votes
1 answer
664 views

Package functions and symbolic calculations

I'm writing my package (.m) in Mathematica and when I call the function it returns 0 instead of a right output. Here's my code: Package.m ...
Motosega's user avatar
  • 121
51 votes
1 answer
2k views

Local variables in Module leak into the Global context

From the Mathematica documentation on Module: Module allows you to set up local variables with names that are local to the module. But after using ...
owler's user avatar
  • 613
50 votes
1 answer
1k views

What does Internal`InheritedBlock do?

What does the function Internal`InheritedBlock do? How is it different from the regular Block?
Ted Ersek's user avatar
  • 7,124
16 votes
4 answers
3k views

Subscripts - Why do I see the error "only assignments to symbols are allowed" when using a Module and not otherwise?

When I type Remove["Global`*"] foo[] := Module[{Subscript[a, 1] = "x"}, 0]; foo[] I get the expected error "only assignments to symbols are allowed". I ...
Nasser's user avatar
  • 142k
10 votes
4 answers
1k views

How to set Block local variables by code?

I need to create a user-defined Block function where the Block variables' values are defined by code. For example, imagine I ...
Murta's user avatar
  • 26.2k
23 votes
3 answers
985 views

Nested definition: How can I define a function with a passed-in expression?

Here's a simplified version of what I'm trying to do: ...
celtschk's user avatar
  • 19.1k
57 votes
2 answers
2k views

How safe is the use of Block and Internal`InheritedBlock

For many questions on this site answers are given which suggest to use Block and, especially for more advanced topics, ...
Albert Retey's user avatar
  • 23.6k
42 votes
4 answers
3k views

Why modules with no variables?

I was reading some code, in particular, recipe 4.13 on unification pattern-matching in Sal Mangano's Mathematica Cookbook, and there were many instances of Modules with no variables in them, such as ...
Reb.Cabin's user avatar
  • 8,661
32 votes
1 answer
949 views

Is the renaming mechanism of `With` flawed?

I'm confused about the renaming mechanism of With: ...
luyuwuli's user avatar
  • 2,804
14 votes
2 answers
3k views

Scoping in assigning a derivative

While answering another question, I stumbled upon a problem I cannot easily resolve. To assign the derivative of a function to another function, typically one can do this with a ...
freddieknets's user avatar
  • 1,085
8 votes
1 answer
370 views

Creating a Block from a list of rules

How can I create a function which works like Block but takes a list of rules as its first argument, rather than a list of assignments? The function needs to be ...
Simon Woods's user avatar
  • 84.9k
29 votes
1 answer
432 views

Strange behavior with Cases and Position with SetDelayed

I feel like I must be missing something simple and obvious here, but this has me scratching my head. This works as expected: ...
rhennigan's user avatar
  • 1,783
15 votes
1 answer
845 views

Do Table iteration variables need to be localized using Module?

Lets say I define a Module, that internally use iterating in a Table or Do, say something ...
Per Alexandersson's user avatar
9 votes
1 answer
498 views

Where does a package have to be loaded?

I'm trying to solve a very tricky issue in my function. The function needs the NDSolve`FEM` framework. Here is a minimal example: ...
YungHummmma's user avatar
  • 3,022
29 votes
2 answers
810 views

What is the purpose of Internal`LocalizedBlock?

I have come across the (internal) use of the function: Internal`LocalizedBlock I am trying to determine its purpose. It seem to behave like ...
Mr.Wizard's user avatar
  • 271k
18 votes
2 answers
1k views

Syntax highlighter shows error for Manipulate when it's inside a Block or a Module

I'm putting my new copy of Mathematica 10 through its paces and I noticed a weird change in the colouring scheme that I find very annoying, and I'd like to get some insight into why it's happening. ...
Emilio Pisanty's user avatar
16 votes
1 answer
471 views

StringReplace, ReplaceAll and Rule interact in a bizarre way

I have the following pair of things: ClearAll[foo, labeledFoo]; labeledFoo = {"FooBarBazQuux", foo}; This works like you'd expect: ...
Pillsy's user avatar
  • 18.4k
22 votes
2 answers
1k views

I define a variable as local to a module BUT then the module uses its global value! Why?

I have a question about modules and local variables. Here's my example: h = 5; Module[{a, h}, a[h_]= h^2; a[4]] (*Out[2] = 25*) I expected the module to ...
pan_e_gaban's user avatar
13 votes
1 answer
952 views

Context of localised (dynamic) symbols

When you localise a symbol with Module, the created unique symbol is usually in the current context. There seems to be an exception to this which has further ...
halirutan's user avatar
  • 113k
10 votes
4 answers
521 views

Working with DynamicModule: ScheduledTasks with local variables

I have a question - is it possible to run ScheduleTask[] inside DynamicModule[]? What I have tried so far: ...
michelson's user avatar
  • 443
28 votes
4 answers
1k views

SetOptions locally?

Is there a way to SetOptions locally? For example, I have a Module and inside it I am doing a lot of ...
a06e's user avatar
  • 11.3k
21 votes
3 answers
2k views

Variable scope similar to other languages

Mathematica, unlike many other languages, defines the variables in the global scope unless it is explicitly asked to define a variable in a local scope, e.g., using ...
Helium's user avatar
  • 4,049
11 votes
1 answer
482 views

Variable scoping in Module

I don't understand why $a$ and $b$ are not local in the following code: ...
rogerl's user avatar
  • 4,209
3 votes
1 answer
419 views

Call Functions From File Without Modifying Context (Sandbox)

Let's say I have file named test.m containing test[arg1_] := ( Print[arg1];) What is the best technique for calling test like ...
William's user avatar
  • 7,595
17 votes
1 answer
7k views

Returning a value from a Module

In the following simple example MyMod := Module[{i}, Do[ Return[1], {i, 3} ]; Print["test"] ] I expected the module to exit on ...
enzotib's user avatar
  • 1,084
11 votes
0 answers
942 views

Compile recursive function modifying global variables

How to compile recursive formula when it relies on more than a few global variables (global to the topmost compiled function)? It is unreasonable to pass on all such variables to each recursive ...
István Zachar's user avatar
19 votes
4 answers
636 views

Internal DynamicModule steals scope of external DynamicModule

I have two dynamic objects, one nested in the other. Both have their own functions defined, as follows. I have simplified them to the point where they don't make much sense, but can still illustrate ...
István Zachar's user avatar
17 votes
3 answers
2k views

What is the right way to construct DynamicModule

When I'm creating DynamicModules for CDF purposes I'm usualy basing on my experience with that, particular goal and content rather than on deep insight. I want to ...
Kuba's user avatar
  • 137k
13 votes
1 answer
404 views

Is garbage collection broken in version 10.0.0?

Bug introduced in 10.0.0 and fixed in 10.0.1 In version 10.0.0 under Windows I am observing the following behavior: ...
Mr.Wizard's user avatar
  • 271k
11 votes
3 answers
719 views

Find variable name from DumpSave on a scoped variable

I saved an InterpolationFunction in a ".mx" files using DumpSave on a variable that was scoped by a ...
JxB's user avatar
  • 5,091
6 votes
2 answers
2k views

Compute Hessian of function symbolically

This question could equally apply to the computation of other symbolic transformations of a function, but I use the Hessian as an example here. Consider a two-variable function ...
Szabolcs's user avatar
  • 234k
4 votes
1 answer
503 views

ControlType -> None Vs. Module inside Manipulate (i.e. making everything local)

I'm building a program on another one made available in the Wolfram Demonstration Project. I've noticed that in the original code (working flawlessly) many variables were made local inside the ...
Luca M's user avatar
  • 997
32 votes
2 answers
3k views

What are some advanced uses for Block?

I read the answers to this question (What are the use cases for different scoping constructs?) and this one (Condition, Block, Module - which way is the most memory and computationally efficient?). ...
VF1's user avatar
  • 4,702
23 votes
1 answer
477 views

Bug with iterated With: Referring to function arguments invalidates previous definitions

Thank you for your report. I have forwarded your report to the appropriate team for review. - WRI ...
masterxilo's user avatar
  • 5,729
20 votes
3 answers
1k views

How does $CellContext` work?

The only official info about $CellContext` I was able to find is: placeholder for the context of a symbol inside Dynamic ...
Kuba's user avatar
  • 137k
14 votes
4 answers
520 views

Using With to scope over pure functions

Consider this example: given an option for a function func as "x" :> (a&), how can one assign different values to ...
István Zachar's user avatar
11 votes
1 answer
559 views

A smarter nested With?

I often find myself writing code that looks a bit like this: ...
Teake Nutma's user avatar
  • 5,971
11 votes
1 answer
1k views

Treat all variables as local in a module [duplicate]

In most languages, any variable defined inside a function is considered local. ...
tba's user avatar
  • 585
9 votes
3 answers
885 views

How do I avoid scoping collisions of iterator variables?

Yesterday I had an issue that kept for quite a while. My code wasn't producing the right results. Now I know why and I am wondering how to avoid the issue in future. Consider the following code. <...
Volker's user avatar
  • 950
8 votes
2 answers
261 views

Using `With[...]` with a list specification as a variable [duplicate]

If you have some defined function, say f[a_, b_ c_, x], one can initialize this by using With[...] as ...
user27119's user avatar
  • 2,490
6 votes
4 answers
301 views

How to scope `Pattern` labels in rules/set?

Module[{x}, f@x_ = x; p@x_ := x; {x, x_, x_ -> x, x_ :> x} ] ?f ?p gives ...
masterxilo's user avatar
  • 5,729
15 votes
2 answers
338 views

Is anonymous pure function a scoping construct?

In recent thread was raised the question: why anonymous pure functions Function[body] (or body &) do not rename symbols in ...
Alexey Popkov's user avatar
11 votes
2 answers
645 views

Strange results while nesting scope constructs?

I did a handful of tests with Block, With, and Module and had a couple of new surprises. ...
Reb.Cabin's user avatar
  • 8,661
11 votes
2 answers
473 views

Unexpected variable renaming depending on form of a pure function

I encountered unexpected difference in variable renaming behavior depending on whether a pure function with a named parameter, or a pure function with a slot is used: ...
Vladimir Reshetnikov's user avatar
9 votes
6 answers
940 views

How can you give a Module a context and have its local variables and Modules belong to that context?

What would be the best way to give a module its own context and have its local variables and Modules belong to that context?
8 votes
1 answer
348 views

Module variable scoping in Scheduled Tasks?

I ran across a scoping puzzle while experimenting with ScheduledTasks, and I'd be grateful for an explanation from the sages here. I found a workaround by intuitive horse sense, but was unable to ...
Reb.Cabin's user avatar
  • 8,661