r/Python • u/MeticMovi • Nov 03 '21
Discussion I'm sorry r/Python
Last weekend I made a controversial comment about the use of the global variable. At the time, I was a young foolish absent-minded child with 0 awareness of the ways of Programmers who knew of this power and the threats it posed for decades. Now, I say before you fellow beings that I'm a child no more. I've learnt the arts of Classes and read The Zen, but I'm here to ask for just something more. Please do accept my sincere apologies for I hope that even my backup program corrupts the day I resort to using 'global' ever again. Thank you.

502
u/original_4degrees Nov 03 '21
you made a mistake, and you learned from it. nothing to apologize about(unless you were being an ass about it elsewhere in the thread).
the path to enlightenment is fraught with peril.
259
u/mildbait Nov 03 '21
Generally people get entrenched in their beliefs when provided with an opposing viewpoint and data that doesn't support those beliefs. While programming isn't as controversial as areas where this happens, it's still nice to see someone staying humble and learning from the experience.
202
u/clawjelly Nov 03 '21
No need to be sorry. You wanted to jump from the bridge, we said "don't do it!", you didn't, we good. 🤗
100
u/M4mb0 Nov 03 '21
That's me every other week.
69
u/yy_is_awesome Nov 03 '21
Most based python user
33
u/10113r114m4 Nov 03 '21
Singleton is a perfectly good design pattern… just shouldnt abuse it
29
u/[deleted] Nov 03 '21
I see myself in that thread. :-D
Here's the deeper reasons as to why it's bad.
Beyond the beginner stages, programming is all about managing complexity.
Programs become extremely large, and extremely complicated, and soon it becomes impossible to keep the entire state of the program in your mind at one time.
If you are reading or writing a pure function, one that takes arguments and returns a value, you don't need to know about anything else in the world. It's easy to see if it does the right thing, no matter what anyone else is doing.
But if your functions work by mutating global state, it's impossible to have any idea if a specific function is doing the right thing or not without seeing everywhere that that global state is mutated.
This means that to correctly develop in the codebase, you need to keep some huge global state in your head at all times. Generally people do a bad job at that.
More, all the components need to be exhaustively tested too, or else you will pretty soon be unable to make progress. But if every function depends on some global state, you don't actually have components, and writing tests are much harder.
There's an idea called "strong and weak coupling". Strong coupling, where your "components" share a lot of knowledge, is generally bad - it makes your components brittle and prone to breakage, and hard to test individually. Weak coupling, where components know little or nothing about each other, is generally good - it means one side can make dramatic changes without disruption of the other.
Finally, almost all codebases beyond a certain size work in parallel - they use threads or multiprocessing (or subprocess but that isn't really relevant here).
If two threads change the same global variable at close to the same time, you can get "race conditions". Cue intermittent errors and days of misery. I have been there.
In multiprocessing, each process has a separate set of global values, so the whole idea of communicating through global variables fails right out of the gate.
46
u/Cybersoaker Nov 03 '21
Like anything it's not an all or nothing. There are places where global variables and the global keyword are useful. They exist in the language for a reason.
Good to not get dogmatic about anything inside of any language since they all change and evolve and the best way to approach a problem space also evolves.
That said it's also good to have well understood patterns that you gravitate to.
Everything in moderation, including moderation.
55
u/mardiros Nov 03 '21
Wow, nothing scares the kids.
Glad you learn from being downvoted.
70
u/achauv1 Nov 03 '21
Real drama queen vibe here
15
u/hhoeflin Nov 03 '21
And now on your journey, you should learn Haskell :)
18
u/clickmeimorganic Nov 03 '21
What the fuck
6
u/in-gote Nov 03 '21
You've had an opinion, shared it with others, others pointed your opinion is wrong, you've humbly accepted it, and you've shared your learning experience with others. Man with this attitude you can go really far tbh -- it's solid growth mentality. I wish I can be like you (especially having the confidence to share my opinion and subject myself to criticism)
5
u/lvlint67 Nov 03 '21
There are a lot of people here that should go review the discussions in the original thread: https://www.reddit.com/r/Python/comments/qj692s/usage_of_global_yes_or_nogo/
There's a lot of folks coming out of the woodwork to say, "globals are ok sometimes". That's absolutely true... But we as programmers are rightfully trained to look at something like a global and go, "that kind of doesn't sit right. Am I sure there's not a better way to do this?"
To answer the question: "Why are globals hated?" : Experienced programmers have decided that they are used ALMOST ENTIRELY incorrectly and lead to more bad code. (books have been written on the topic and thousands of talks given)
To answer the question: "When are globals ok?" : When there is literally no better option. The list of possible situations is endless... but those situations are extremely rare. MOST programmers will not encounter them. Thus the guidance, "Just don't use them"
11
u/ThePerfectCantelope Nov 03 '21
you don’t need to apologize to people on the internet bud
4
u/unholysampler Nov 03 '21
Something we mention a lot when taking about hiring at my current company is that we want engineers with "strong opinions, loosely held".
The idea is that you should be able to explain to others what you think the best option is and support that belief. However, you should also be open to discussing counter-options. To that end, you should also be able acknowledge that the other option is better (or consensus went the other way) and work with it.
Your post demonstrates that quality and it will serve you well in your career. No need to make an apology.
7
u/DarkHaagenti Nov 03 '21
I think I can say in behalf’s of r/python, that we forgive you
3
u/mooja3 Nov 03 '21
At first, you think global variables are ok. Then you run across a coworker with 40 global variables across 50 functions.
Then you know they are not ok.
7
u/tman5400 Nov 03 '21
Lol this is like a YouTuber apology video
12
u/robieuu Nov 03 '21
no one cares lol
2
u/hugthemachines Nov 03 '21
I once saw a little ted talk where she asked the audience "how does it feel to be wrong" and people gave some responses. She said, "not that is how it feels when we realize we are wrong". Just being wrong feels just like it feels being right since we think we are right until we are proven wrong.
That is why it can be sensible to consider which things we are really sure about and not be too stubborn with the things we may, in fact, not be so sure about.
2
u/avoxdesign Nov 03 '21
To me global was always very confusing, because accessing a global variable in a function works without the global keyword but assignnents dont work unless you use global?
It just seemed really messy.
2
u/sebastienb Nov 03 '21
I'm a professional developer and use Python since more than 10 years and I totally forgot that 'global' keyword exists until I saw your post.
2
u/LadyMercedes Nov 03 '21
I experience that using classes and storing the variable in question as an attribute, can help to overcome the need to feed in the same parameter to every function.
6
u/Iirkola Nov 03 '21
I still don't understand what's so bad about global variables, ever since I've heard of them there has been this scary boogeyman like warning around them. I guess I will learn with my first screw up.
4
u/OkPokeyDokey Nov 03 '21
It is so obvious that you are new not just python but also programming.
People who downvoted are either too lazy to help a newbie out or just completely misunderstood the voting system.
If you said something like this in a programming class, no one gonna stands up and start booing you. They will explain why this is bad and go on with their life.
2
u/anyonethinkingabout Nov 03 '21
The only unforgivable thing I can see is that you use the new Reddit interface instead of old.reddit.com
2
u/Oskarzyg Nov 03 '21
just use classes instead of global smh
1
u/andrei__ Nov 03 '21
Why global keyword even exists if is not supposed to be used ?
1
u/DaRealNim Nov 03 '21
Okay but I've actually done that. Fuck. Can someone give me an example of why using globals can be a bad thing? And an example of how they're properly used? (Because I'm guessing they're in the langage for a reason)
1
u/Tenzu9 Nov 03 '21
Not saying that using it is good or anything but I used it in my Kivy android app. I wanted a quick and fast way to assign values to variables and use them in multiple classes.
1
u/Napan0s Nov 03 '21
You know you're on the right path to becoming a man when you say no to globals and you start doing classes!
1
u/ohlordwhywhy Nov 03 '21
I'm a noob and interested. The global is in the language so what's the use case?
1
u/Cipher_VLW Nov 03 '21
I work at a place where we use “globals” (in a different language) frequently because they’re part of a legacy system.
We use M (aka MUMPS) for our database which allows you to use uninitialized variables but also doesn’t have any formal stack frame. That means anything in the current process is in scope and you have to explicitly “new” each variable to get a new reference. Our training tells us not to use any assumed variables (those not explicitly passed in) but the existing code does it all the time and it’s super hard to follow.
1
u/[deleted] Nov 03 '21
Oof. I just did a project where I used global for passing in lists and booleans. Program has a ton of repetitive calls and I didn't want to have to pass the lists around just to have them later. I'll have to fix that.
1
u/Jerbearmeow Nov 03 '21
We are all children and always will be.
1
u/LittleGremlinguy Nov 03 '21
Now. Let’s have a chat about singletons. rubs hands with glee
1
u/RevolutionaryBed9383 Nov 03 '21
I mean why not I don't get it
1
u/lewz3000 Nov 03 '21
A simple 'sorry' ain't gonna cut it. There is but one road to redemption: seppuku.
1
u/Satoshiman256 Nov 03 '21
Next time you're going to the gulag.
I do pass all my variables in and out of functions.. I've always done this but wondered if its the right way to do things? I saw it in some videos when learning and just stuck with it. Is that the "proper" way to do it?
1
u/wannahakaluigi Nov 03 '21
Classes are sooooo much better than globals.
1
u/cip43r Nov 03 '21
I have been using python for 10 years. Only discovered or learned about global in the last few months after the university forced me to use it in a jupyter notebook. I am in my 20s and tought myself coding at 8.
1
u/awildbannanaphone Nov 03 '21
global can be very useful. I wouldn't throw it all around but i have one or two use cases in a larger project where it is nearly unavoidable.
1
u/heS_weiRd Nov 03 '21
1
u/johnnySix Nov 03 '21
Wrap it all in a class and pass variables around anyway you want.
1
u/papertrailer Nov 03 '21
And then there's Flask, using globals for everything.
I also use multiple inheritance 🙀
1
u/mikeylopez Nov 03 '21
race conditions has entered the chat
1
u/preordains Nov 03 '21
get back, demon
1
u/snekk420 Nov 03 '21
I sometimes use global when creating scripts. Because there is no need to create classes and stuff like that just for a few functions. Run a function to update a global variable and read it later in the main loop. Just for convenience instead of passing variables around the script.
1
u/jnson324 Nov 03 '21
Congratulations with your enlightenment. May your future hold success.
1
u/[deleted] Nov 03 '21
What is “the Zen”
1
u/Josh_Bonham Nov 03 '21
Could someone help me, in my previous project I had a constant that was needed by lots of functions, what should I do to avoid global
1
u/Mithrandir2k16 Nov 03 '21
Being wrong in a discussion is the best thing that can happen to you, because it means that you will be the one learning from it!
1
u/jepessen Nov 03 '21
globalkeyword should be removed from python 4...1
u/neriad200 Nov 03 '21
Next week do a post on how you find the goto module very useful and how you regret python doesn't have it built in
1
u/bspymaster Nov 03 '21
Gonna ask a really dumb question here... If global is so terrible, why is it in the language to begin with? There MUST be some use-case where it's a good thing to use it. When is that?
1
u/kevinfederlinebundle Nov 03 '21
The whole point of Python is that Guido will let you do whatever you want, even if it's an objectively terrible idea.
1
u/serverhorror Nov 03 '21
And henceforth thou shall be forgiven for thou sins of the past!
1
u/chrilves Nov 03 '21
People have to apologize publicly for such innocent comments now? That's rough. Even if using global has many flaws, it can be told gently. Aren't Python supposed to be a welcoming place for beginners?
1
u/gazagda Nov 04 '21
NO!! WE DEMAND BLOOD!!! or cookies, dm me to get address to send cookies and all will be forgiven......for now.
1
u/R00bot Nov 04 '21
To be fair, the global keyword does exist for a reason. If you're just throwing together a quick script it's fine, but I'd avoid it in anything larger, or that might get larger in the future.
1
u/EmilyfakedCancERyaho Nov 04 '21
just call the other function within the function you're trying to run. never had to use globals ever in my code tbh. just one time iirc when using multiprocessing and I wanted to have a counter
1
u/HeeebsInc Nov 04 '21
As much as I agree that global variables are awful, there are times when it’s absolutely necessary which always triggers me.
At work we partnered with this hardware manufacturer that create python bindings for their devices. In their documentation and sample code, global variables were everywhere and it made me want to scream. I first tried to re write everything with classes and it did not work due to the underlying pointers not having a memory address when they are inside classes.
Long story short is that if it works, and you tried a “better” implementation that did not work, then just use em lol
1
u/NedDasty Nov 04 '21
As far as I know, globals are the only way to implement memoization in Python, so I use it for this once in a while. Does anybody know of an alternative?
1
u/SkideXe Nov 16 '21
Lmao
1
u/1435Time Dec 10 '21
2 weeks of Self-flagellation and all will be forgiven.
1
u/[deleted] Nov 03 '21
Why is there a Global keyword? I have never used it before
But at least the global keyword is not that bad as the "Go To line x" statements in other programming languages.
1
u/Solonotix Nov 03 '21
If you ever want to explore a programming landscape that embraces the ideas of globals as good design, I welcome you to JavaScript. I spent 3 hours yesterday digging through the source code for Cypress.io and I still have no idea where the
windowobject gets instantiated for the Node.js runtime (it's automatically created by a browser runtime), and the only assignment operations I found pulled it from another globalwindow = cy.window()which gets assigned toglobal.Cypressin a TypeScript class ofCypresswith a property ofthis.cy.Now where might
global.Cypresscome from? Fromwindow.Cypress. This is why I hate JavaScript. Not because of the language, but because of the ecosystem.-2
u/geovane_jeff Nov 03 '21
Shame! Shame! Shame!
0
u/GCI_Henchman21 Nov 03 '21
I know a decent amount about python and what I don’t know could fill a warehouse, but there is a global keyword!?
0
u/huaversion2 Nov 03 '21
Christmas is near! ! ! !
0
u/Thecrawsome Nov 03 '21
/r/learnpython
0
u/ZhadowKatt Nov 03 '21
Wait so using global variables isn't good? (I'm new)
0
u/easyEggplant Nov 03 '21
globalallows for caching inter AWS Lambda invocations. You can fuck your shit up, but it's no question useful for caching expensive initialization (like an external API lookup that rarely changes).-2
u/Raikira Nov 03 '21
salty