How to understand dynamic scoping using Python cod

2019-08-10 05:37发布

问题:

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 ?

回答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.



标签: python scope