I'm a programmer coming from Python background which typically uses lexical scoping and I want to understand dynamic scope. I've researched it on-line, still unclear to me. For example, I've read this page which made things a lot easier to me, especially the code snippets:
#In Dynamic scoping:
const int b = 5;
int foo()
{
int a = b + 5;
return a;
}
int bar()
{
int b = 2;
return foo();
}
int main()
{
foo(); // returns 10
bar(); // returns 7
return 0;
}
#In lexical scoping:
const int b = 5;
int foo()
{
int a = b + 5;
return a;
}
int bar()
{
int b = 2;
return foo();
}
int main()
{
foo(); // returns 10
bar(); // returns 10
return 0;
}
As I understand and as you can see, in the dynamic scoping, bar
function returns 7 not 10, which means foo
called the b
variable which is defined within bar
, in other words, foo
did not looked for the b
variable that's defined in top of the code (the first b variable) but rather it used the b
variables that's defined in bar
.
Q1: Hence, In dynamic scoping, the function that's being called within another function in this case foo
called in bar
first looks for variables in the caller function in this case bar
and then it looks for top level variables ?
Q2: Could you explain dynamic scoping in Python code ?
-
4Python uses lexical scoping, there is no dynamic scoping. As such we cannot explain dynamic scoping in Python code.Martijn Pieters– Martijn Pieters2015年09月21日 15:49:59 +00:00Commented Sep 21, 2015 at 15:49
-
1The answer for Q1 is: yes.Martijn Pieters– Martijn Pieters2015年09月21日 15:51:49 +00:00Commented Sep 21, 2015 at 15:51
-
@MartijnPieters about Q1 is this what all dynamic scoping boils down to or is there anything else ?GIZ– GIZ2015年09月21日 16:08:45 +00:00Commented Sep 21, 2015 at 16:08
-
That's what it boils down to, yes. Also see Wikipedia.Martijn Pieters– Martijn Pieters2015年09月21日 16:13:00 +00:00Commented Sep 21, 2015 at 16:13
1 Answer 1
There is no dynamic scoping in Python, unless you implement your own stack-based 'namespace'.
And yes, dynamic scoping is that simple; the value of a variable is determined by the closest calling namespace where a value was set. View the calls as a stack, and a value is looked up by searching the current call stack from top to bottom.
So for your dynamic example, the stack is first:
foo
main
globals -> b = 5
finding b = 5
when searching through the stack, and then the stack changes to
foo
bar -> b = 2
main
globals -> b = 5
so b = 2
is found.
11 Comments
main
function if for example b
variable was assigned in main
instead of bar
?main
or any other function outside functions, it'll only look for globals only, correct me if I'm wrong.