Just to clarify... There is 100% use cases for the global keyword. I don't mean to say you should NEVER use it. My basic reasoning behind making this video is many people (especially beginners) use the global keyword all the time and with no understanding of how it works! I wanted to show in detail how it works and some of the pitfalls of using it. Hopefully you learned something :)
I understood a lot from this video, thankyou for uploading this. I think you need to upload more super-specific videos like this so people can know more than what they already know about something. cheers!
Yeah, it is clear that if something is added to a language, it is done for a reason, but things just should not be used inappropriately. By the way, there is a topic that I do not understand why it is almost not explained on RUclips. Why don't you try to make a video on async/await and what is the difference between this and threading or multiprocessing. It confuses many. Anyway, thank you!)
Hey Tim! I learned a lot about context management from this during my lunch break, but a couple of things struck out to me. I understand that the 'global' keyword has its niche, but as for "why not to use it" wasn't clear. But here is what I think: The global keyword can be used for modifying a global variable without passing it by reference. For example, if there is a 'points' variable and I would like to add points to it (say, points + 1) using a function [add_points(points)], I would much rather reference 'points' by its location in memory, rather than creating a local copy in the function, caused by passing the variable into the function. So instead, by calling 'add_points()' and removing the argument from the function definition, I can access the 'points' variable by calling 'global points', and adding to it that way. It should be clear that for the scope of operation for the 'points' variable, it's used explicitly within functions to modify its value. What IS clear is that 'global' isn't used for creating a global variable. It's just telling the interpreter that the global keyword's argument should be referred by its global value, as opposed to creating a second variable that will be local to its scope. Thanks, man!
It's not something all languages support. Although with anonymous functions a lot of languages now support it. Python supports both named and anonymous functions.
Thanks Tim I watched another video before and read a article but I was still a bit confused, this video was perfect for a beginner like me and I’m sure I’ll still get a ton of value from all your videos all the way up to mastery👏🏽🔥 you gained a student and a fan
@Raghav Negi Bruh. All programmers RUclipsrs are great, there's no competition, all programming youtubers want to work with the community and give information :)
@@uhmmm2110 Ok bro. Tim does a lotta tutorials, for example, the python & django one. Also, the best place to learn programming for beginners is RUclips(at least in my experience). And, yes, all programming youtubers just want to give quality information, except for some channels like TechLead. And finally, he might want a like from Tim, but Tim is a great programming RUclipsr.
Hi, Great video. I just want to point out that you mentioning "you know it's confusing" makes it much more puzzling since I didn't find it confusing at all, but you saying that made me wonder whether I got everything right. Aside from that, I thought your explanation was excellent!
I use global all the time since I typically like to initialize certain values that will be needed through the program inside a function. You definitely don’t want to mess with it unless you understand what it does and if you get confused by scopes. But other than that it is a very useful keyword
There are definitely ways of doing it without using global. You can create an object with those variables, pass it into your function, and modify object inside that function. This way you'll achieve the same, but it will be explicit and unit-testable.
LOVE this. I handed off a program once, and it came back with a UI function accepting user inputs and assigning them to global variables which could already be referenced and assigned earlier through a different UI. It was very poor practice and introduced bugs.
What to do instead: 1. Closures Let's say you are implementing random function. Instead of doing it like seed = 1337 def random(): global seed seed = some_math(seed) return seed You can do this: def create_random_func(): seed = 1337 def random(): nonlocal seed seed = some_math(seed) return seed return random random = make_random_func() This way you accomplished the same, without messing up with global scope. Plus you can create two instances of random() function, that don't interfere with one another, which might be helpful to test this function without changing the random state. 2. Objects. Create class RNG that contains seed. Now use def random(rng): rng.seed = some_math(rng.seed) return rng.seed rng1 = RNG() number = random(rng1) This way you achieved all of the above + explicitness.
Tq as always Tim. But some of the problems you legitimately mentioned can be nullified by good variable name management. E.g. prefix all globals prefixed with 'Glob' moniker, e.g. Glob_x = ... Hence that a a global is called/modified is obvious would instantly make you consider if it's used in some imported module. I use a global boolean as an event driven trigger to break out of various loops. Simple uses of them are of course less likely to cause issues. Given that python supports globals, it would be nice to hear from it's scripter what they had in mind for its use.
Tim, great video! I remember when u discouraged the use of Global variables in your hangman pygame. That hangman game was actually my first ever python project and I have since started developing a small pygame mini game collection, I’ve been trying to figure it out for a while now how to integrate the hangman code into the program. I’d love if you made a small follow up explaining how to make the game run, and resettable to play multiple times with something like a menu, I know you teased it in the video but I cannot figure it out haha
Thanks Tim for your time. hope you can make a video about how "constractor & this keyword " works and their importance in python. Thanks again keep going .
Great video. As someone working through the CS50 course and just starting on Python, I found this initially confusing. So thanks. Funnily enough I suspect that throughout most of my C language coding for the course so far, I've been relying on global variables too much and not enough on returning from functions! So a doubly-good learning.
Interesting discovery (not covered here): x = 7 def foo(): x = 5 def bar(): global x x = 3 print ("in bar, x(defined as global) =", x) bar() print ("in foo, x =", x) print ("outside, x =", x) RESULTS: in bar, x(defined as global) = 3 in foo, x = 5 outside, x = 3 Note that declaring global x inside bar() did NOT make the x in foo() global. Only the x outside was affected by the assignment in bar().
"better" for *what* though? There's a "horses for courses" aspect to this: strictly typed languages are better for complex/mission-critical programs, because they catch a lot of common errors at compile time. The extra effort of having to declare absolutely everything pays off. Untyped ones are usually better for short scripts: fewer places for typos and inappropriate variable reuses to hide, so declarations become an expense with poor ROI. I agree that Python could have done it better: I think there shouldn't be "automatic" inheritance. And only one "global" context. If you're inheriting from a parent, declare it as "from_parent xx" or somesuch.
i mean like if you change a lot of stuff you could store all these in an array and always pass the array and return it, but then you are confused while debugging what those values represent, so i think for large programs it is easier for a human to keep track of all the individual variables, but its of course not the "cleanest" way
I'm surprised you didn't go into the idea that if you have a bunch of global variables that need to be modified, there's a class hiding somewhere in there, or a few. Great video though, keep up the good work, thanks for all the great tutorials!
Hi Sir, I have a doubt plz assist me on the code : x=10 def f(): x='hello' print(x) global x x=x+20 print(x) f() print(x) In side function f() I have a local variable with the same name of global variable, I need to print local variable value and want edit global variable and print that global variable .Please tell me is it a valid approach, kindly assist me on this.
Hey Tim I have problem with my game. It breaks with message Process finished with exit code -1073740791 (0xC0000409) . What could be a problem that makes this happens?
Lol 11:55 onwards for a couple of minutes... since when is making a copy of a function in another file “re-using” a function. The great thing about functions is you have one copy in one place and re-use the one version. If you want it to be portable then stick it in a library where it’s nice and safe and unlikely to produce unexpected side effects. Globals are perfectly safe if you use them appropriately. Importantly... don’t use variable names that are likely to overlap. Variables names like x and y should be used locally only, inside loops for example.
You are right. But, I have a script where I keep track of an ID and I don't want to pass in that ID to the ton of methods. At first, I used the global keyword. But, now I use a dumb hack, which I call a hack, where I use a mutable type list[int] ... This hack saves me from having to pass in this ID to 13 / 14 procedures and having to return the updated ID. Also, a few of these methods update the value in the middle of the function. Could I use global()['whatever'] ... maybe ... and I might.
well, in general, you just need to make a variable that returns a value, then reassing the value you wanted to change to x = do_something(x) which is way better to change variables, more readable and it will work with different variables. After all, if you're making a function, it means you want to reuse it. y = do_something(y)
use a class, and have the two functions(now methods) inside the class, you will be able to manipulate any of the class variables from within any methods
wait what's the difference between multithreading and multiprocessing? a thread is just like a virtual cpu core right? and multiprocessing uses actual cpu cores? does multiprocessing and multithreading work like parallel processing in a gpu? or is everything I said totally wrong?
@@mastershooter64 Ummmm - I think that threading just looks like it, multiprocessing actually is, but I found threading s lot easier and had some problems with multiprocessing (which I can't remember now)
Would you say that calling the globals() from a function to check on its value and then make the return changes is also bad practice? like in your example: def add_7(x): result = globals()['result'] return result + 7 result = 65 print(add_7(result))
Hi, Brother, I'm a freelancer! Experienced with web scraping but I want to switch to web development. I don't have a college degree, I have a little knowledge about Django, Flask, Celery, and React. Should I go for Backend with Python or Frontend with React or something else? Can you consider to recommend a path for me?
I agree that 'global' should be avoided. But I wouldn't go so far as to say it should never be used. Why global should be avoided: (1) All the reasons mentioned by Tim are true. (2) 'global' breaks the rules of Functional Programming, where every function must always return the same result when called with the same arguments--i.e., no side effects. HOWEVER: Sometimes you write functions to refactor code because it's growing and getting out of control. Also, most programmers seldom use nested functions (if they even know about them). And, I think it should be stressed that functions should not be called from outside the current program, unless the current program is intended to be used as a library. Otherwise, if the current program is deleted or its functions are modified in the future, it could break other programs using those functions. (I would say this is even more important that using 'global'.) So, if you know your function is strictly limited to the current program, and its purpose is to facilitate readability of complex code, then using 'global' is probably acceptable, as the alternative (functions defined with long parameter lists) can quickly become unwieldy and error-prone. Of course, the best practice would be to refactor the program to avoid both 'global' and long parameter lists. Packaging data in a container (class, dict, list, etc.) might be the best approach.
Nothing confusing in it, the global variable is often useful when you have multiple function performing multiple operation and you have to keep updating the variable accordingly.
I feel like an alien right now, how is it possible that it doesn't work to me? If I try to print the variable inside my function, I get "local variable 'active_soundtrack' referenced before assignment"
What if I have a socket server script that I want to bury in root but I want users to be able to run a "setup" script that allows them to input IP addresses of clients and it sets them as Global variables? That way the main Socket Server script can pull in the IP addresses but still be "hidden" from sight. Would this work and would it be an acceptable use of Global?
Could you explain why this is interesting from a C++ perspective? I don't know C++. I do see the global variable often in robotics (and C++ is also often used in robotics) so I am curious :)
I have a question: If the program looks for the variable in the local scope and doesnt find it then it looks A) to the scope the function is definened in Or B) to the scope the function was called from For example what is the result here: X = 3 Def fx_a(): X = 5 fx_b() Def fx_b(): print(X) fx_a() Thanks
3 would be the result Since x = 5 is only local to fx_a, fx_b function isn’t able to access that value since it is only existent within fx_a so it finds x elsewhere as defined globally and then prints that
I have 2 questions how do you get the information about the code jam on discord and how do you deploy a music bot to Heroku. Because you have to use some dependices like FFMpeg that are local to your computer. Love Your videos and thank you for the support👏❤
Hey Tim, maybe you should explain that Python has no global variables. Python has module level scoope, but the variables at the module level are not global in any sense of the word. Scoping rules are very misleading and usually quite misunderstood. Examples usually are so simplistic that they do not resemble anything in reality. I know you can do better,...
Amazing videos Tim! I once even showed one of your tutorials in class and it helped us all! so thanks so so much. Would you mind making a video about automatically measuring heights in ar? I think it would be cool. Don't worry if you don't have time or have a different video idea. Thank you so much again and please please please keep up the awesome content!!
@Saketh p you can't use incrementation in this lambda bc it gives the num new value (instead of returning it) and that leads to an error. Thanks for trying though
What about while making something using tkinter? I made a simple calculator app but it required me to modify some value outside my function using a button. Even the tutorial for tkinter from freecodecamp told to use globals
Exactly, if something is created, it definitely has a use for it. The problem with people is that if they think something is in some way, they have to rub their thoughts on others and the others just accept it without putting in much thought. Global is one of my favorite keywords in python. All the points that he had said in the video are false. The functions reusability depends on you, just if you don't import a function into other scripts doesn't negate the functions reusability. If you have a counter function in a script specifically created for that script, importing that is just silly. Also debugging the code even with these statements is really easy with pycharm and vscode as they have step into function where they can take you into different scripts. Tim should have done more research before coming here. He is fooling himself and thousands of people.
Hey code ranger! Totally understand your comment and appreciate it. Maybe I should have looked into the tkinter example, wasn’t aware that global was used in an official tutorial. The point of this video was really more for beginners that use the global keyword all the time, rather than learning the other and usually better ways to do things. Global definitely has a use but I want people that use it to understand exactly how it works and why they’re using it :)
To be honest you can avoid using global variables there also just build your calculator app with class instead just using functions it will make it better Also if you want to build a bigger tk inter program you will need to use classes anyway so why not start early it is a better practice
tkinter is an exception in this case i think, because when i was beginner in python i too made a calc using tkinter and i was forced to use global vars
@@TechWithTim yeah tim, a little more research would have been great, you agree with your flaws thats why you are my favorite python youtuber. Tkinter is not the only example, therr are many instances like kivy app development. I use it when I want to particular global variable, I just don't name it x or y, I just name it in all caps then change it in global space, so even if I import that function I'll not face anymore functions.
If a person wanted to use the global keyword to ensure that they are able to define all of their variables, couldn't they just set their variables as immutable tuples instead, ensuring that the variable definition would never change within the scope of the file? That would perhaps be best. Then again, I'm a first-year software engineering student who's green as Hell and doesn't know what he's talking about - Lol. I did, however, try to override the a tuple using the global keyword, and that didn't work.
Just to clarify... There is 100% use cases for the global keyword. I don't mean to say you should NEVER use it. My basic reasoning behind making this video is many people (especially beginners) use the global keyword all the time and with no understanding of how it works! I wanted to show in detail how it works and some of the pitfalls of using it. Hopefully you learned something :)
Ahhh ok
Nice, I am new to code and programming. I was completely confused about global myself. So thanks man.
Bro I can't join twt code jam can please help me
I understood a lot from this video, thankyou for uploading this. I think you need to upload more super-specific videos like this so people can know more than what they already know about something. cheers!
Yeah, it is clear that if something is added to a language, it is done for a reason, but things just should not be used inappropriately. By the way, there is a topic that I do not understand why it is almost not explained on RUclips. Why don't you try to make a video on async/await and what is the difference between this and threading or multiprocessing. It confuses many. Anyway, thank you!)
This guy never gets tired.
Dude its just a 15min video
Hey Tim! I learned a lot about context management from this during my lunch break, but a couple of things struck out to me. I understand that the 'global' keyword has its niche, but as for "why not to use it" wasn't clear. But here is what I think:
The global keyword can be used for modifying a global variable without passing it by reference. For example, if there is a 'points' variable and I would like to add points to it (say, points + 1) using a function [add_points(points)], I would much rather reference 'points' by its location in memory, rather than creating a local copy in the function, caused by passing the variable into the function. So instead, by calling 'add_points()' and removing the argument from the function definition, I can access the 'points' variable by calling 'global points', and adding to it that way.
It should be clear that for the scope of operation for the 'points' variable, it's used explicitly within functions to modify its value.
What IS clear is that 'global' isn't used for creating a global variable. It's just telling the interpreter that the global keyword's argument should be referred by its global value, as opposed to creating a second variable that will be local to its scope.
Thanks, man!
This is a Python tutorial, but it just helped me understand a JavaScript thing. Thank you!
Tim: *defines a function inside a function*
Me who didn't know you can do that: "wait that's illegal"
I haven't seen that used much often.
if you imagine the foo is not a function, but a class,it makes more sense,right? :)
Actually I also got to know about it recently 😅
Lol
It's not something all languages support. Although with anonymous functions a lot of languages now support it. Python supports both named and anonymous functions.
It’s more common in other languages
Thanks Tim I watched another video before and read a article but I was still a bit confused, this video was perfect for a beginner like me and I’m sure I’ll still get a ton of value from all your videos all the way up to mastery👏🏽🔥 you gained a student and a fan
Tim is literally the best RUclipsr I have seen
YES
@Raghav Negi Bruh. All programmers RUclipsrs are great, there's no competition, all programming youtubers want to work with the community and give information :)
@@ayaanp
💯
@@ayaanp ⬆️
@@uhmmm2110 Ok bro. Tim does a lotta tutorials, for example, the python & django one. Also, the best place to learn programming for beginners is RUclips(at least in my experience). And, yes, all programming youtubers just want to give quality information, except for some channels like TechLead. And finally, he might want a like from Tim, but Tim is a great programming RUclipsr.
Hi, Great video. I just want to point out that you mentioning "you know it's confusing" makes it much more puzzling since I didn't find it confusing at all, but you saying that made me wonder whether I got everything right. Aside from that, I thought your explanation was excellent!
I use global all the time since I typically like to initialize certain values that will be needed through the program inside a function. You definitely don’t want to mess with it unless you understand what it does and if you get confused by scopes. But other than that it is a very useful keyword
There are definitely ways of doing it without using global. You can create an object with those variables, pass it into your function, and modify object inside that function. This way you'll achieve the same, but it will be explicit and unit-testable.
Great tutorial. At 15:08, a case in which you will certainly not see the problem is if you imported the add_7 function from another script
Just learned about this in your beginner course. The timing.
LOVE this. I handed off a program once, and it came back with a UI function accepting user inputs and assigning them to global variables which could already be referenced and assigned earlier through a different UI. It was very poor practice and introduced bugs.
If you're just looking for an answer skip to 11:35
What to do instead:
1. Closures
Let's say you are implementing random function. Instead of doing it like
seed = 1337
def random():
global seed
seed = some_math(seed)
return seed
You can do this:
def create_random_func():
seed = 1337
def random():
nonlocal seed
seed = some_math(seed)
return seed
return random
random = make_random_func()
This way you accomplished the same, without messing up with global scope. Plus you can create two instances of random() function, that don't interfere with one another, which might be helpful to test this function without changing the random state.
2. Objects.
Create class RNG that contains seed.
Now use
def random(rng):
rng.seed = some_math(rng.seed)
return rng.seed
rng1 = RNG()
number = random(rng1)
This way you achieved all of the above + explicitness.
Just when i was thinking of using this variable in my project lol
It’s useful in certain situations and if you understand how it works then it should be no problem.
Tq as always Tim.
But some of the problems you legitimately mentioned can be nullified by good variable name management. E.g. prefix all globals prefixed with 'Glob' moniker, e.g. Glob_x = ... Hence that a a global is called/modified is obvious would instantly make you consider if it's used in some imported module. I use a global boolean as an event driven trigger to break out of various loops. Simple uses of them are of course less likely to cause issues.
Given that python supports globals, it would be nice to hear from it's scripter what they had in mind for its use.
yea this is what i got out of this video globals are just bad if you cant remember your one variable names
Tim, great video! I remember when u discouraged the use of Global variables in your hangman pygame. That hangman game was actually my first ever python project and I have since started developing a small pygame mini game collection, I’ve been trying to figure it out for a while now how to integrate the hangman code into the program. I’d love if you made a small follow up explaining how to make the game run, and resettable to play multiple times with something like a menu, I know you teased it in the video but I cannot figure it out haha
16:00 such good advice! Great video Tim!
Thanks Tim for your time.
hope you can make a video about how "constractor & this keyword " works and their importance in python.
Thanks again keep going .
Great video. As someone working through the CS50 course and just starting on Python, I found this initially confusing. So thanks.
Funnily enough I suspect that throughout most of my C language coding for the course so far, I've been relying on global variables too much and not enough on returning from functions! So a doubly-good learning.
Welp, time to change my whole game code which has around 30 global variables, distributed in 6 different files...
The video was really helpful. Thank you. If possible please bring a series on react native and node js. It is confusing. Love from India.
Interesting discovery (not covered here):
x = 7
def foo():
x = 5
def bar():
global x
x = 3
print ("in bar, x(defined as global) =", x)
bar()
print ("in foo, x =", x)
print ("outside, x =", x)
RESULTS:
in bar, x(defined as global) = 3
in foo, x = 5
outside, x = 3
Note that declaring global x inside bar() did NOT make the x in foo() global. Only the x outside was affected by the assignment in bar().
One of the few cases where Python got it wrong. I really wish this wasn't like this. C++, and other languages, do variables much better.
"better" for *what* though? There's a "horses for courses" aspect to this: strictly typed languages are better for complex/mission-critical programs, because they catch a lot of common errors at compile time. The extra effort of having to declare absolutely everything pays off. Untyped ones are usually better for short scripts: fewer places for typos and inappropriate variable reuses to hide, so declarations become an expense with poor ROI.
I agree that Python could have done it better: I think there shouldn't be "automatic" inheritance. And only one "global" context. If you're inheriting from a parent, declare it as "from_parent xx" or somesuch.
i mean like if you change a lot of stuff you could store all these in an array and always pass the array and return it, but then you are confused while debugging what those values represent, so i think for large programs it is easier for a human to keep track of all the individual variables, but its of course not the "cleanest" way
I'm surprised you didn't go into the idea that if you have a bunch of global variables that need to be modified, there's a class hiding somewhere in there, or a few. Great video though, keep up the good work, thanks for all the great tutorials!
Hi Sir,
I have a doubt plz assist me on the code :
x=10
def f():
x='hello'
print(x)
global x
x=x+20
print(x)
f()
print(x)
In side function f() I have a local variable with the same name of global variable, I need to print local variable value and want edit global variable and print that global variable .Please tell me is it a valid approach, kindly assist me on this.
thanks Tim, you cleared my doubt on global variable💞
I use the global keyword all the time. It's useful and doesn't break anything if you name things appropiately.
yea this is what i got out of this video globals are just bad if you cant remember your one variable names
Thanks man for cool videos, you great 👍)
Thank you so much Tim you have been a real source of inspiration for me
Me three years ago wanting to pass multiple parameters to a function:
Global variables: This looks like a job for me
Very well explained! Thanks Tim!
Hey Tim I have problem with my game. It breaks with message Process finished with exit code -1073740791 (0xC0000409)
. What could be a problem that makes this happens?
Lol 11:55 onwards for a couple of minutes... since when is making a copy of a function in another file “re-using” a function. The great thing about functions is you have one copy in one place and re-use the one version. If you want it to be portable then stick it in a library where it’s nice and safe and unlikely to produce unexpected side effects. Globals are perfectly safe if you use them appropriately. Importantly... don’t use variable names that are likely to overlap. Variables names like x and y should be used locally only, inside loops for example.
You are right. But, I have a script where I keep track of an ID and I don't want to pass in that ID to the ton of methods. At first, I used the global keyword. But, now I use a dumb hack, which I call a hack, where I use a mutable type list[int] ... This hack saves me from having to pass in this ID to 13 / 14 procedures and having to return the updated ID. Also, a few of these methods update the value in the middle of the function. Could I use global()['whatever'] ... maybe ... and I might.
It's really helpful!! Thank you
Great video, the only thing iI was bummed about was that you did not suggest other alternatives :(
well, in general, you just need to make a variable that returns a value, then reassing the value you wanted to change to
x = do_something(x)
which is way better to change variables, more readable and it will work with different variables. After all, if you're making a function, it means you want to reuse it.
y = do_something(y)
Great demo. Thanks
thanks it is one of the biggest confusion among the python coders
Ummm so I use multithreading - how else can I change a value in a function from a different function (they're running at the same time)
use a class, and have the two functions(now methods) inside the class, you will be able to manipulate any of the class variables from within any methods
@@aidendoig4542 ahh so I use self.variable for the variable - that could actually work thanks 🙃
wait what's the difference between multithreading and multiprocessing? a thread is just like a virtual cpu core right? and multiprocessing uses actual cpu cores? does multiprocessing and multithreading work like parallel processing in a gpu? or is everything I said totally wrong?
@@mastershooter64 Ummmm - I think that threading just looks like it, multiprocessing actually is, but I found threading s lot easier and had some problems with multiprocessing (which I can't remember now)
4th :) I also don''t use global keyword, but I didn't know why that is...until now!
Same
Would you say that calling the globals() from a function to check on its value and then make the return changes is also bad practice?
like in your example:
def add_7(x):
result = globals()['result']
return result + 7
result = 65
print(add_7(result))
You are the best guy i ever seen you have a brillian brain
Great explanation the video was very helpful I learned alot from it
Hi, Brother,
I'm a freelancer! Experienced with web scraping but I want to switch to web development. I don't have a college degree, I have a little knowledge about Django, Flask, Celery, and React.
Should I go for Backend with Python or Frontend with React or something else? Can you consider to recommend a path for me?
Good point. Thanks!
It works! Thank you!
awesome tutorial, can you make a tutorial explaining what does: '*' do ?
Nice video Tim! 😁👍🏽
Yo! I have a video suggestion, can you make a video talking about return vs global for beginners?
Great video, very clear.
Tim was really spitting bar()s on this one.
very useful. thanks tim. have a good day
I agree that 'global' should be avoided. But I wouldn't go so far as to say it should never be used.
Why global should be avoided: (1) All the reasons mentioned by Tim are true. (2) 'global' breaks the rules of Functional Programming, where every function must always return the same result when called with the same arguments--i.e., no side effects.
HOWEVER: Sometimes you write functions to refactor code because it's growing and getting out of control. Also, most programmers seldom use nested functions (if they even know about them). And, I think it should be stressed that functions should not be called from outside the current program, unless the current program is intended to be used as a library. Otherwise, if the current program is deleted or its functions are modified in the future, it could break other programs using those functions. (I would say this is even more important that using 'global'.)
So, if you know your function is strictly limited to the current program, and its purpose is to facilitate readability of complex code, then using 'global' is probably acceptable, as the alternative (functions defined with long parameter lists) can quickly become unwieldy and error-prone. Of course, the best practice would be to refactor the program to avoid both 'global' and long parameter lists. Packaging data in a container (class, dict, list, etc.) might be the best approach.
Tim, please make more videos on python
Nothing confusing in it, the global variable is often useful when you have multiple function performing multiple operation and you have to keep updating the variable accordingly.
i like the new intro
Thx for clearing this up, Tim :)
Great explanation thank you!
great videos!! keep going
love your content!!
thanks!
I feel like an alien right now, how is it possible that it doesn't work to me? If I try to print the variable inside my function, I get "local variable 'active_soundtrack' referenced before assignment"
What if I have a socket server script that I want to bury in root but I want users to be able to run a "setup" script that allows them to input IP addresses of clients and it sets them as Global variables? That way the main Socket Server script can pull in the IP addresses but still be "hidden" from sight. Would this work and would it be an acceptable use of Global?
me who use c++ literally everytime
watching this video::: Interesting
Exactly!!!
Could you explain why this is interesting from a C++ perspective? I don't know C++. I do see the global variable often in robotics (and C++ is also often used in robotics) so I am curious :)
@@satyajeetjena6758 ah, thanks :)
the person who creates your video thumbnails must be a very cool person.. !
Global Variables create so many issues especially in larger programs, hence don't use them at all if possible.
I have a question:
If the program looks for the variable in the local scope and doesnt find it then it looks
A) to the scope the function is definened in
Or
B) to the scope the function was called from
For example what is the result here:
X = 3
Def fx_a():
X = 5
fx_b()
Def fx_b():
print(X)
fx_a()
Thanks
@@leobozkir5425 so result is 3? I watched it but he defined it IN the other func
@@michmart9261 It will return 3, the 5 is only in fx_a. fx_b is at the same level as fx_a.
3 would be the result
Since x = 5 is only local to fx_a, fx_b function isn’t able to access that value since it is only existent within fx_a so it finds x elsewhere as defined globally and then prints that
I have 2 questions how do you get the information about the code jam on discord and how do you deploy a music bot to Heroku. Because you have to use some dependices like FFMpeg that are local to your computer. Love Your videos and thank you for the support👏❤
Damn it.. i just used global variable in my voice assistant to do some automation 😂
lol I've used it lots in my voice assistant - gotta change it now I guess
@@BeardBarians 😂 making the variable unique will do the job why waste time rewriting better create something else😀
@@sumanmitra202 lol 😂 - let's just forget variables altogher, it's not like we need them right?....
Me who doesn't even know what global variable is: "interesting"
Lmao
why this gives error:
x = 6
def aaa():
print(x)
x = 88
print(x)
aaa()
I think global statement is useful.
Just don't reuse or import the file.
Use it for small projects.
Hey Tim, maybe you should explain that Python has no global variables. Python has module level scoope, but the variables at the module level are not global in any sense of the word. Scoping rules are very misleading and usually quite misunderstood. Examples usually are so simplistic that they do not resemble anything in reality. I know you can do better,...
This helped me, thank you.
What would the result be of the last print statement in this code:
X = 4
Def Foo():
print(X)
X=5
print(X)
4 bcs the other x is in local scope
4
Amazing videos Tim! I once even showed one of your tutorials in class and it helped us all! so thanks so so much. Would you mind making a video about automatically measuring heights in ar? I think it would be cool.
Don't worry if you don't have time or have a different video idea. Thank you so much again and please please please keep up the awesome content!!
But how do i avoid using global keyword even in basic click counter with tkinter GUI?
@Saketh p you can't use incrementation in this lambda bc it gives the num new value (instead of returning it) and that leads to an error. Thanks for trying though
Bro I can't join twt code jam can you help me please
I hated this function in the 80`s on the ZX Spectrum. :(
Me who uses R: "Crazy how Python works aye"
No one:
Absolutely no one:
R: let’s start index at 1
@@dwartenb89 hahaha it took me so long to get used to that, fkn R and Matlab 🤣
@@dwartenb89 Lua does that too
What about while making something using tkinter? I made a simple calculator app but it required me to modify some value outside my function using a button.
Even the tutorial for tkinter from freecodecamp told to use globals
Exactly, if something is created, it definitely has a use for it. The problem with people is that if they think something is in some way, they have to rub their thoughts on others and the others just accept it without putting in much thought. Global is one of my favorite keywords in python. All the points that he had said in the video are false. The functions reusability depends on you, just if you don't import a function into other scripts doesn't negate the functions reusability. If you have a counter function in a script specifically created for that script, importing that is just silly. Also debugging the code even with these statements is really easy with pycharm and vscode as they have step into function where they can take you into different scripts. Tim should have done more research before coming here. He is fooling himself and thousands of people.
Hey code ranger! Totally understand your comment and appreciate it. Maybe I should have looked into the tkinter example, wasn’t aware that global was used in an official tutorial. The point of this video was really more for beginners that use the global keyword all the time, rather than learning the other and usually better ways to do things. Global definitely has a use but I want people that use it to understand exactly how it works and why they’re using it :)
To be honest you can avoid using global variables there also just build your calculator app with class instead just using functions it will make it better
Also if you want to build a bigger tk inter program you will need to use classes anyway so why not start early it is a better practice
tkinter is an exception in this case i think, because when i was beginner in python i too made a calc using tkinter and i was forced to use global vars
@@TechWithTim yeah tim, a little more research would have been great, you agree with your flaws thats why you are my favorite python youtuber. Tkinter is not the only example, therr are many instances like kivy app development. I use it when I want to particular global variable, I just don't name it x or y, I just name it in all caps then change it in global space, so even if I import that function I'll not face anymore functions.
A request, Can you please bring a series on React Native. It is a bit confusing. Any way love from India.
Yeah please
This function is local to dysfunction. Sorry, tut is greeeat!
can you make tutorial on activatypub python
bro make a video on algorithim in python plz.....
does this apply to if statements?
Thank you!
If a person wanted to use the global keyword to ensure that they are able to define all of their variables, couldn't they just set their variables as immutable tuples instead, ensuring that the variable definition would never change within the scope of the file? That would perhaps be best. Then again, I'm a first-year software engineering student who's green as Hell and doesn't know what he's talking about - Lol. I did, however, try to override the a tuple using the global keyword, and that didn't work.
Oh come on ! My friends are telling me not to use globals, and now you are also telling me not to ! Let me use my globals T_T
why are you using x variable multiple times , that will really confuse it more likely haha
Damn I just got done using global with every variables in the school project 💀💀
XD thanks was about to ask the same question in your discord
Ay tim got a cherry mx blue keyboard finally
hierarchical system that take nearest assignment if you dont set global value.
pretty damn good video
It was a nice video, keep up the good work :thumbsup:
crystal clear
IMO the issue is not about using the global keyword but a global variable
Tim says not use global , pray to Odin and the slain soldiers of Valhalla you don't use it
Hello! came here after video was uploaded 12 seconds ago lol
thx