Python tutorial: Variable Scopes & Namespaces - global/local/nonlocal | Explained with animations
ฝัง
- เผยแพร่เมื่อ 16 ธ.ค. 2024
- The variables you define in your Python code has a lexical scope where they are valid. These scopes are categorized as local, enclosing, global and built-in scopes.
Python language also provides a few keywords like global and nonlocal to modify the behaviour of its variable name resolution.
This video tries to explain how scopes and namespaces work in different scenarios.
How variables work in Python: • How variables work in ...
Credits: The contents of this video are mostly from my notes on Dr. Fred Baptiste's course www.udemy.com/...
This is the best video explaining variable scope of Python.
I was having trouble understanding this concept before, but the way you explained it visually really helped me! Thank you for this video.
These videos are for serious learners, who wants to become professional programmers. Cannot think of anything better. Thanks and sincere gratitude for your rigorous scholarship that you have shared with us.
Thank you so much! I hope TH-cam recommends your channel more to more people!
This is so clear explaining that it's hard to not understand!
Everyone should watch this. This is the Python that's just thrown at you without an explanation of how it works.
Simply brilliant. First time learning about built-in scope and nonlocal keyword
You are a genius. I at last understand global , local , nonlocal .. being a visual person. Your method of VISUAL teaching is UNIQUE. Do you have plans to produce full tutorials even on a paid plan. I would definately subscribe. Your work is simply EXELLENT. The best explanations i have come across so far. Thanks
Very good, thanks for your work producing this video. Taught me some new things and reminded me of some old things. I found the voice-over a little fast for easy comprehension so I switched the playback to 0.75 speed which, for me, worked better. Thanks again.
finally, I understood the concept. thank you so much for explaining the 'local assignment entry masks the global namespace'. it makes a lot sense. Ta~~'
Brilliant animation.
Thanks for this video and your efforts. I wish One day you'll obviously success for video
5:46 good lecture thx.
I have a question, at this point I think that outet function's namespace cannot have a value for "x" because outer function is not called(executed)
You are the best, i will be more than happy to purchase your training if you make one.
brilliant, love the way you tell things.
thanks a lot sreekanth.. i referred other materials as well. but your video explanations made the pint clear in one go.
hey! what does print is masked by print? at 2:22
Simply Great!
2:15 Do you mean you code will use the "masking" function (your custom `print` function)? The native `print` is masked by your custom `print`. So your custom `print` is "masking the native `print`. The custom `print` is a "masking function". The native `print` is a "masked function" .
The complier creates a "Code Object" for every "Code Block" in a program. A code block is a piece of code that is executed as a single unit (e.g a function , or a module, or a class).To execute a "code object" , Cpyhton creates a state of execution for it called .....
YES ANOTHER FREAKING OBJECT , the "Frame Object". Compiled code objects are inserted into the frame object along with the other fields for builtin, global , local etc etc. It is a C struct and has the following fields and many ->
| -----------------Field--------------------Type-----------------------Purpose----------|
f_builtins PyObject*(dict) Symbol Table for builtin module
f_globals PyObject*(dict) Global Symbol Table (PyDictObject)
f_locals PyObject* Local Symbol Table
f_code PyCodeObject* Code object to be executed (the one i was jus talking about)
!! YOUR ANSWER IS BELOW!!!
{{{{{ If the name of the variable is not in local scope (f_locals), the VM looks up the value in the global scope (f_globals). And if the name is not in f_globals either, the VM looks up the value in (f_builtins). The f_builtins field of a frame object points to the dictionary of the builtins module, which contains built-in types, functions, exceptions and constants. If the name is not there, the VM gives up and sets the "NameError "exception.The way this search happens essentially hides the built-in reference within the current scope. .If a function in the global scope is named "print" the VM will find it there and will not to go and look in the builtins.This affects name resolution in Python but doesn't alter the memory or underlying storage of the built-in name itself .
Think of it like this ->If your dog has the same name as you , he wont become you but ,if someone calls out your name from a distance you cant hear... but your dog most certainly can (well because he is a dog) , he will respond first and you never will.
You are Builtin , The Dog is Global , and the rest is Python :) }}}}}}}}}
Hope this helps , you can reply if you have more questions
You mention at the end that nonlocal cannot be chained to global. I wish to ask about how nonlocal chain to each other.
In code below, why is outer's x finally printed to be 2 and not 1? outer's x seems to know inner2 (2 levels inside) has updated x too.
Does this mean inner1's nonlocal points to x in outer, and inner2's nonlocal points to inner1, therefore causing inner2's nonlocal to also point to outer, so all 3 scopes see the same x value that the address of x resolves to?
(I can see they are pointing to same id() if using mutables like list for x)
def outer():
x=0
def inner1():
nonlocal x
x+=1
def inner2():
nonlocal x
x+=1
inner2()
inner1()
print('x after:',x) # why is this not 1
outer()
You already got it. The same id confirms a single object has been created, and all non-local x points to the same object. With each level's execution, the value of the object is updated; Sequence is 0, 1, 2.
The concepts are explained in a beutiful manner ... I was just wondering what the rush was all about ?
Hi Sreekanth your Python tutorials are indepth and awesome, keep it going. Please can you recommend any python book which teachs indepth python concepts.
"Fluent Python" is the only book I've read. Mostly, I just read blogs or watch talks by James Powell and Raymond Hettinger. I'm not a Python programmer, at work I use Go. I was re-learning Python with my knowledge in other programming languages.
@@sreekanthpr I appreciate your quick and helpful response. It is strange that you are not python programmer but still you have got indepth knowledge of Python. Keep up the good work!!!
Perfect , i Couldn'tt understand it before thx
love you channel, please not leave us, we want more videos
It helps alot, can't afford patreon or donation, put some ads in, we are okay with that
Great videos, thanks a lot! Great material to improve our "under the hood" understanding.
One part that surprised me was that with using the global keyword in a local scope the variable gets created in the global scope if it doesn't exist there yet (th-cam.com/video/WYZrLtFNDVI/w-d-xo.html), while with the nonlocal keyword the variable doesn't get created in an outer non-global environment if it doesn't exist there yet (th-cam.com/video/WYZrLtFNDVI/w-d-xo.html).
Do you know if this was a conscious implementation decision by the Cpython community? I can imagine it being decided like this because it would be a bit ambiguous in which outer scope the variable should be created (while with the global keyword there's explicitly 1 scope we're targeting).
ty!
I love the illustrations and information. Although I'd really prefer this be explained by a human tho...
U talk so fast. This is not done.
Go to the right-hand upper corner, click at..., find play speed. Set to 0.75. That should be. If you still cannot follow, this class level is not suitable for you. Sorry
I think you just rephrased and summarized what are taught from Fred Baptiste's courses on Python Deep Dive series in Udemy. Not only this video but many others from you. You should credit him, refer to his courses and say what you did to create these videos.
For audiences, as this channel gets the most materials from paid courses (they are very cheap, though) and summarizes them (sometimes not adequately), I suggest you should go to the original course to understand even more about Python which is excellently taught by Dr. Fred Baptiste.
Updated description of all Python videos. Wasn't sure since its a paid course.