scope - How to understand dynamic scoping using Python code? -
i'm programmer coming python background typically uses lexical scoping , want understand dynamic scope. i've researched on-line, still unclear me. example, i've read this page made things lot easier me, code snippets:
#in dynamic scoping: const int b = 5; int foo() { int = 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 = b + 5; return a; } int bar() { int b = 2; return foo(); } int main() { foo(); // returns 10 bar(); // returns 10 return 0; }
as understand , can see, in dynamic scoping, bar
function returns 7 not 10, means foo
called b
variable defined within bar
, in other words, foo
did not looked b
variable that's defined in top of code (the first b variable) rather used b
variables that's defined in bar
.
q1: hence, in dynamic scoping, function that's being called within function in case foo
called in bar
first looks variables in caller function in case bar
, looks top level variables ?
q2: explain dynamic scoping in python code ?
there no dynamic scoping in python, unless implement own stack-based 'namespace'.
and yes, dynamic scoping simple; value of variable determined closest calling namespace value set. view calls stack, , value looked searching current call stack top bottom.
so dynamic example, stack first:
foo main globals -> b = 5
finding b = 5
when searching through stack, , stack changes to
foo bar -> b = 2 main globals -> b = 5
so b = 2
found.
Comments
Post a Comment