Skip to content Skip to sidebar Skip to footer

How To Understand Dynamic Scoping Using Python Code?

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 exa

Solution 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.

Post a Comment for "How To Understand Dynamic Scoping Using Python Code?"