Why You Shouldn't Use the Global Keyword in Python

  Рет қаралды 47,301

Tech With Tim

Tech With Tim

Күн бұрын

In this Python lesson, I'll be going over why you should never use the 'global' keyword in your code. Often times, you'll hear me and others say you shouldn't use the global keyword, but you never really hear why. I'll be demystifying the global keyword and explaining why you shouldn't use the global keyword in Python and why it's generally recommended you do not use it.
💻 AlgoExpert is the coding interview prep platform that I used to ace my Microsoft and Shopify interviews. Check it out and get a discount on the platform using the code "techwithtim" algoexpert.io/techwithtim
⭐️ Chapters ⭐️
0:00 | Intro
0:48 | Global vs local variables
08:15 | Using the global keyword
16:41 | Why you shouldn't use the global keyword
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
💰 Courses & Merch 💰
💻 The Fundamentals of Programming w/ Python: tech-with-tim.teachable.com/p...
👕 Merchandise: teespring.com/stores/tech-wit...
🔗 Social Medias 🔗
📸 Instagram: / tech_with_tim
📱 Twitter: / techwithtimm
⭐ Discord: / discord
📝 LinkedIn: / tim-ruscica-82631b179
🌎 Website: techwithtim.net
📂 GitHub: github.com/techwithtim
🔊 Podcast: anchor.fm/tech-with-tim
🎬 My KZbin Gear 🎬
🎥 Main Camera (EOS Canon 90D): amzn.to/3cY23y9
🎥 Secondary Camera (Panasonic Lumix G7): amzn.to/3fl2iEV
📹 Main Lens (EFS 24mm f/2.8): amzn.to/2Yuol5r
🕹 Tripod: amzn.to/3hpSprv
🎤 Main Microphone (Rode NT1): amzn.to/2HrZxXc
🎤 Secondary Microphone (Synco Wireless Lapel System): amzn.to/3e07Swl
🎤 Third Microphone (Rode NTG4+): amzn.to/3oi0v8Z
☀️ Lights: amzn.to/2ApeiXr
⌨ Keyboard (Daskeyboard 4Q): amzn.to/2YpN5vm
🖱 Mouse (Logitech MX Master): amzn.to/2HsmRDN
📸 Webcam (Logitech 1080p Pro): amzn.to/2B2IXcQ
📢 Speaker (Beats Pill): amzn.to/2XYc5ef
🎧 Headphones (Bose Quiet Comfort 35): amzn.to/2MWbl3e
🌞 Lamp (BenQ E-reading Lamp): amzn.to/3e0UCr8
🌞 Secondary Lamp (BenQ Screenbar Plus): amzn.to/30Dtafi
💻 Monitor (BenQ EX2780Q): amzn.to/2HsmUPZ
💻 Monitor (LG Ultrawide 34WN750): amzn.to/3dSD7tS
🎙 Mic Boom Arm (Rode PSA 1): amzn.to/30EZw9m
🎚 Audio Interface (Focusrite Scarlet 4i4): amzn.to/2TjXsih
💸 Donations 💸
💵 One-Time Donations: www.paypal.com/donate?hosted_...
💰 Patreon: / techwithtim
◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️◼️
⭐️ Tags ⭐️
- Python lesson
- Global keyword
⭐️ Hashtags ⭐️
#PythonLesson #GlobalKeyword

Пікірлер: 189
@TechWithTim
@TechWithTim 3 жыл бұрын
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 :)
@BeardBarians
@BeardBarians 3 жыл бұрын
Ahhh ok
@alicemystery5520
@alicemystery5520 3 жыл бұрын
Nice, I am new to code and programming. I was completely confused about global myself. So thanks man.
@tonystark3399
@tonystark3399 3 жыл бұрын
Bro I can't join twt code jam can please help me
@ankithabhayan324
@ankithabhayan324 3 жыл бұрын
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!
@victaiov
@victaiov 3 жыл бұрын
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 KZbin. 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!)
@manojuppala
@manojuppala 3 жыл бұрын
This guy never gets tired.
@lodostic1015
@lodostic1015 3 жыл бұрын
Dude its just a 15min video
@richardjonesiii2856
@richardjonesiii2856 3 жыл бұрын
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!
@johnnyjunior963
@johnnyjunior963 Жыл бұрын
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
@GrumpyStoic
@GrumpyStoic 2 жыл бұрын
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.
@parker5791
@parker5791 3 жыл бұрын
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
@empty3657
@empty3657 3 жыл бұрын
Tim: *defines a function inside a function* Me who didn't know you can do that: "wait that's illegal"
@thinboxdictator6720
@thinboxdictator6720 3 жыл бұрын
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? :)
@manu-singh
@manu-singh 3 жыл бұрын
Actually I also got to know about it recently 😅
@prawnydagrate
@prawnydagrate 3 жыл бұрын
Lol
@vk3fbab
@vk3fbab 3 жыл бұрын
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.
@kensei4237
@kensei4237 3 жыл бұрын
It’s more common in other languages
@agentfifteen
@agentfifteen 2 жыл бұрын
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!
@TechWithSabri
@TechWithSabri 3 жыл бұрын
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 .
@brandonfuerst2977
@brandonfuerst2977 3 жыл бұрын
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.
@EnglishRain
@EnglishRain 3 жыл бұрын
16:00 such good advice! Great video Tim!
@Sam-tg4ii
@Sam-tg4ii Жыл бұрын
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
@stephendouglas9355
@stephendouglas9355 3 жыл бұрын
Very well explained! Thanks Tim!
@asadon1950
@asadon1950 3 жыл бұрын
Just learned about this in your beginner course. The timing.
@ElectronicsHikingandJesusTalk
@ElectronicsHikingandJesusTalk 3 жыл бұрын
This is a Python tutorial, but it just helped me understand a JavaScript thing. Thank you!
@subarnodatta2181
@subarnodatta2181 3 жыл бұрын
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.
@adhamsabry6011
@adhamsabry6011 3 жыл бұрын
Thank you so much Tim you have been a real source of inspiration for me
@zafaris
@zafaris 3 жыл бұрын
Nice video Tim! 😁👍🏽
@richardwhalen1859
@richardwhalen1859 Жыл бұрын
Great demo. Thanks
@frane5173
@frane5173 2 жыл бұрын
It works! Thank you!
@icaryslittle6370
@icaryslittle6370 3 жыл бұрын
Thx for clearing this up, Tim :)
@p.mousumipriyadarshini8677
@p.mousumipriyadarshini8677 3 жыл бұрын
thanks Tim, you cleared my doubt on global variable💞
@priyanshusaraf9495
@priyanshusaraf9495 3 жыл бұрын
Tim is literally the best KZbinr I have seen
@ayaanp
@ayaanp 3 жыл бұрын
YES
@ayaanp
@ayaanp 3 жыл бұрын
@Raghav Negi Bruh. All programmers KZbinrs are great, there's no competition, all programming youtubers want to work with the community and give information :)
@PNCNDNOB
@PNCNDNOB 3 жыл бұрын
@@ayaanp 💯
@kensei4237
@kensei4237 3 жыл бұрын
@@ayaanp ⬆️
@ayaanp
@ayaanp 3 жыл бұрын
@@uhmmm2110 Ok bro. Tim does a lotta tutorials, for example, the python & django one. Also, the best place to learn programming for beginners is KZbin(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 KZbinr.
@devoiddude
@devoiddude 3 жыл бұрын
Great explanation thank you!
@mbmeweg293
@mbmeweg293 3 жыл бұрын
Thanks man for cool videos, you great 👍)
@lisaliang2507
@lisaliang2507 3 жыл бұрын
It's really helpful!! Thank you
@Rubbernecker
@Rubbernecker 2 жыл бұрын
Great video, very clear.
@SimonLam2024
@SimonLam2024 3 жыл бұрын
Good point. Thanks!
@schwischwi8523
@schwischwi8523 3 жыл бұрын
Just when i was thinking of using this variable in my project lol
@abusiness8783
@abusiness8783 3 жыл бұрын
It’s useful in certain situations and if you understand how it works then it should be no problem.
@abusiness8783
@abusiness8783 3 жыл бұрын
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
@luck3949
@luck3949 Жыл бұрын
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.
@suryabhavithperugupalli7041
@suryabhavithperugupalli7041 3 жыл бұрын
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👏❤
@masterhai4924
@masterhai4924 3 жыл бұрын
very useful. thanks tim. have a good day
@JAlpha7
@JAlpha7 2 жыл бұрын
Great explanation the video was very helpful I learned alot from it
@shahzaibali4911
@shahzaibali4911 3 жыл бұрын
XD thanks was about to ask the same question in your discord
@fulviorock
@fulviorock 3 жыл бұрын
Thank you!
@Nedawor
@Nedawor 3 жыл бұрын
Me three years ago wanting to pass multiple parameters to a function: Global variables: This looks like a job for me
@thewadegreen
@thewadegreen 3 жыл бұрын
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!
@crystallarcade3996
@crystallarcade3996 3 жыл бұрын
Welp, time to change my whole game code which has around 30 global variables, distributed in 6 different files...
@belleeun
@belleeun 3 жыл бұрын
awesome tutorial, can you make a tutorial explaining what does: '*' do ?
@Aivin
@Aivin 3 жыл бұрын
Yo! I have a video suggestion, can you make a video talking about return vs global for beginners?
@ankithabhayan324
@ankithabhayan324 3 жыл бұрын
Me who doesn't even know what global variable is: "interesting"
@lodostic1015
@lodostic1015 3 жыл бұрын
Lmao
@Zale370
@Zale370 3 жыл бұрын
Great video, the only thing iI was bummed about was that you did not suggest other alternatives :(
@machibutinenglish1468
@machibutinenglish1468 3 жыл бұрын
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)
@MD-vm7tv
@MD-vm7tv 3 жыл бұрын
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?
@mcplayer6630
@mcplayer6630 2 жыл бұрын
pretty damn good video
@hackzchannel7921
@hackzchannel7921 3 жыл бұрын
You are the best guy i ever seen you have a brillian brain
@dantonddsa
@dantonddsa Жыл бұрын
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))
@rafid_zx
@rafid_zx 3 жыл бұрын
It was a nice video, keep up the good work :thumbsup:
@thomasedison559
@thomasedison559 3 жыл бұрын
great videos!! keep going love your content!!
@TechWithTim
@TechWithTim 3 жыл бұрын
thanks!
@BeardBarians
@BeardBarians 3 жыл бұрын
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)
@aidendoig4542
@aidendoig4542 3 жыл бұрын
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
@BeardBarians
@BeardBarians 3 жыл бұрын
@@aidendoig4542 ahh so I use self.variable for the variable - that could actually work thanks 🙃
@mastershooter64
@mastershooter64 3 жыл бұрын
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?
@BeardBarians
@BeardBarians 3 жыл бұрын
@@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)
@Mike-vj8do
@Mike-vj8do 3 жыл бұрын
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!!
@G_M1112
@G_M1112 3 жыл бұрын
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?
@alejandrocabrera8769
@alejandrocabrera8769 3 жыл бұрын
does this apply to if statements?
@hacklordmonster8780
@hacklordmonster8780 3 жыл бұрын
i like the new intro
@ayaanp
@ayaanp 3 жыл бұрын
4th :) I also don''t use global keyword, but I didn't know why that is...until now!
@rachit6099
@rachit6099 3 жыл бұрын
Same
@doubleu4211
@doubleu4211 Жыл бұрын
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
@subhanshareef939
@subhanshareef939 3 жыл бұрын
me who use c++ literally everytime watching this video::: Interesting
@manu-singh
@manu-singh 3 жыл бұрын
Exactly!!!
@geetarNL
@geetarNL 3 жыл бұрын
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 :)
@geetarNL
@geetarNL 3 жыл бұрын
@@satyajeetjena6758 ah, thanks :)
@skgujar2725
@skgujar2725 3 жыл бұрын
Tim, please make more videos on python
@firelagstats
@firelagstats 3 жыл бұрын
Me who uses R: "Crazy how Python works aye"
@dwartenb89
@dwartenb89 3 жыл бұрын
No one: Absolutely no one: R: let’s start index at 1
@firelagstats
@firelagstats 3 жыл бұрын
@@dwartenb89 hahaha it took me so long to get used to that, fkn R and Matlab 🤣
@rc8s
@rc8s Жыл бұрын
@@dwartenb89 Lua does that too
@tobeypeters
@tobeypeters 2 жыл бұрын
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.
@ThyFeinkoster
@ThyFeinkoster 2 жыл бұрын
If you're just looking for an answer skip to 11:35
@inuyashacoolieo
@inuyashacoolieo Жыл бұрын
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?
@sumanmitra202
@sumanmitra202 3 жыл бұрын
Damn it.. i just used global variable in my voice assistant to do some automation 😂
@BeardBarians
@BeardBarians 3 жыл бұрын
lol I've used it lots in my voice assistant - gotta change it now I guess
@sumanmitra202
@sumanmitra202 3 жыл бұрын
@@BeardBarians 😂 making the variable unique will do the job why waste time rewriting better create something else😀
@BeardBarians
@BeardBarians 3 жыл бұрын
@@sumanmitra202 lol 😂 - let's just forget variables altogher, it's not like we need them right?....
@luck3949
@luck3949 Жыл бұрын
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.
@passord1d493
@passord1d493 3 жыл бұрын
can you make tutorial on activatypub python
@xuanchili
@xuanchili 3 жыл бұрын
crystal clear
@maaaaaass
@maaaaaass 2 жыл бұрын
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.
@tonystark3399
@tonystark3399 3 жыл бұрын
Bro I can't join twt code jam can you help me please
@aquibshaikh8611
@aquibshaikh8611 3 жыл бұрын
the person who creates your video thumbnails must be a very cool person.. !
@rikittu
@rikittu 3 жыл бұрын
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
@coderanger7708
@coderanger7708 3 жыл бұрын
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.
@TechWithTim
@TechWithTim 3 жыл бұрын
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 :)
@tamasfodor2312
@tamasfodor2312 3 жыл бұрын
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
@rachitq1185
@rachitq1185 3 жыл бұрын
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
@coderanger7708
@coderanger7708 3 жыл бұрын
@@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.
@eduard289
@eduard289 2 жыл бұрын
thx
@parthgupta4850
@parthgupta4850 3 жыл бұрын
thanks it is one of the biggest confusion among the python coders
@Stinosko
@Stinosko 3 жыл бұрын
What would the result be of the last print statement in this code: X = 4 Def Foo(): print(X) X=5 print(X)
@michmart9261
@michmart9261 3 жыл бұрын
4 bcs the other x is in local scope
@leobozkir5425
@leobozkir5425 3 жыл бұрын
4
@thapelommakola8208
@thapelommakola8208 2 жыл бұрын
Danke
@FoxRedTail
@FoxRedTail 2 жыл бұрын
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"
@abrarmasumabir3809
@abrarmasumabir3809 3 жыл бұрын
bro make a video on algorithim in python plz.....
@subarnodatta2181
@subarnodatta2181 3 жыл бұрын
A request, Can you please bring a series on React Native. It is a bit confusing. Any way love from India.
@ajay2552
@ajay2552 3 жыл бұрын
Yeah please
@kkkk150984
@kkkk150984 Жыл бұрын
why this gives error: x = 6 def aaa(): print(x) x = 88 print(x) aaa()
@mr_ambivalence
@mr_ambivalence 3 жыл бұрын
But how do i avoid using global keyword even in basic click counter with tkinter GUI?
@mr_ambivalence
@mr_ambivalence 3 жыл бұрын
@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
@m12652
@m12652 3 жыл бұрын
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.
@karldamus5124
@karldamus5124 3 жыл бұрын
I use the global keyword all the time. It's useful and doesn't break anything if you name things appropiately.
@k1lluachan
@k1lluachan Жыл бұрын
yea this is what i got out of this video globals are just bad if you cant remember your one variable names
@kychemclass5850
@kychemclass5850 Жыл бұрын
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.
@k1lluachan
@k1lluachan Жыл бұрын
yea this is what i got out of this video globals are just bad if you cant remember your one variable names
@theyoutubeaccount8499
@theyoutubeaccount8499 3 жыл бұрын
Ay tim got a cherry mx blue keyboard finally
@shalomakolatse537
@shalomakolatse537 3 жыл бұрын
Tim was really spitting bar()s on this one.
@kenhaley4
@kenhaley4 3 жыл бұрын
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().
@whathuh6965
@whathuh6965 Ай бұрын
Global Variables create so many issues especially in larger programs, hence don't use them at all if possible.
@rayankazi6029
@rayankazi6029 3 жыл бұрын
Hello! came here after video was uploaded 12 seconds ago lol
@misteryo2480
@misteryo2480 3 жыл бұрын
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
@kir69420
@kir69420 Жыл бұрын
Damn I just got done using global with every variables in the school project 💀💀
@damianbutterworth2434
@damianbutterworth2434 7 ай бұрын
I hated this function in the 80`s on the ZX Spectrum. :(
@aadhithyansuresh6516
@aadhithyansuresh6516 3 жыл бұрын
damn tim is reading the chats in TWT server
@rachitq1185
@rachitq1185 3 жыл бұрын
yeah, Tim knows everything
@carlabest1257
@carlabest1257 3 жыл бұрын
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,...
@grawss
@grawss Жыл бұрын
This helped me, thank you.
@Amakratacjan
@Amakratacjan 3 жыл бұрын
This function is local to dysfunction. Sorry, tut is greeeat!
@reisaki18
@reisaki18 3 жыл бұрын
I think global statement is useful. Just don't reuse or import the file. Use it for small projects.
@alisanmocadi6762
@alisanmocadi6762 9 ай бұрын
why are you using x variable multiple times , that will really confuse it more likely haha
@Aristocle
@Aristocle 3 жыл бұрын
hierarchical system that take nearest assignment if you dont set global value.
@angryducklinginstitution76
@angryducklinginstitution76 3 жыл бұрын
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.
@thebestnerd4444
@thebestnerd4444 3 жыл бұрын
I think this video is longer than it needed to be.
@michmart9261
@michmart9261 3 жыл бұрын
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
@michmart9261
@michmart9261 3 жыл бұрын
@@leobozkir5425 so result is 3? I watched it but he defined it IN the other func
@HAMpeach
@HAMpeach 3 жыл бұрын
@@michmart9261 It will return 3, the 5 is only in fx_a. fx_b is at the same level as fx_a.
@regularprogrammer5360
@regularprogrammer5360 3 жыл бұрын
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
@kenhaley4
@kenhaley4 3 жыл бұрын
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.
@adarshp6550
@adarshp6550 3 жыл бұрын
Tim says not use global , pray to Odin and the slain soldiers of Valhalla you don't use it
Write Python Code Properly!
25:46
Tech With Tim
Рет қаралды 144 М.
Python Is Weird...
26:29
Tech With Tim
Рет қаралды 109 М.
Secret Experiment Toothpaste Pt.4 😱 #shorts
00:35
Mr DegrEE
Рет қаралды 36 МЛН
Mom's Unique Approach to Teaching Kids Hygiene #shorts
00:16
Fabiosa Stories
Рет қаралды 35 МЛН
Опасность фирменной зарядки Apple
00:57
SuperCrastan
Рет қаралды 11 МЛН
Stop using global variables!
8:20
Jakob Sagatowski
Рет қаралды 10 М.
Please Master These 10 Python Functions…
22:17
Tech With Tim
Рет қаралды 108 М.
Python Asynchronous Programming - AsyncIO & Async/Await
25:57
Tech With Tim
Рет қаралды 421 М.
Problem Solving Techniques - For Programming Problems & Interviews
17:40
What is Scope in Python??
10:25
b001
Рет қаралды 47 М.
The Algorithm Behind Spell Checkers
13:02
b001
Рет қаралды 409 М.
Python Typing - Type Hints & Annotations
24:46
Tech With Tim
Рет қаралды 110 М.
10 Python Shortcuts You Need To Know
27:27
Tech With Tim
Рет қаралды 292 М.
Python Generators Explained
28:37
Tech With Tim
Рет қаралды 149 М.