Someone has answered... but next time, check the post's flair (right below the title) :). It's a rule on this subreddit to attach a flair indicating the language, so every post must have.
Everyone appreciates when this is done - maybe those of us posting screenshots of text should also take a minute to copy & paste that text into a comment to save them the effort?
Honestly I don't think this is terrible. Of course, it's redundant, but it likely won't make the program run any slower (at least super insignificant) nor does it hurt readability.
Not a good mindset in my opinion. What's the point of trying to close a file twice? The fact that .close() is idempotent does not imply that this is not terrible. It's an indicator of a poor knowledge of the context manager at least.
Or it suggests someone was distracted for 10 seconds. For fucks sake, reading the comments here you would think none of you people wrote code that made you think "what was I doing?" literally tomorrow morning.
Could still easily mean that he just copy pasted the code. But even then, I've seen devs who know what code like this does (in Java and C#, there are same constructs), but they still manually release the resource again "just to be sure". And they are very competent devs, just... people are weird.
It's not a judgement on the coder. Just their code. Obviously everyone is a human, but looking at this snippet, I would assume this person is unaware of how with works. In a code review, I would take the opportunity to teach them. If they already knew, great, it's a refresher. If they didn't, then now they know for next time.
Because I'm a paranoid freak, I look at that and my first question is: did the author override open() with something else that doesn't cooperate with the context manager, and that's why they're explicitly calling close()?
My second question is: what if write() throws an exception, creds goes out of scope, but close() was never called? Will that leave credentials.json in a bad state with the file system / OS?
My last question is: given that they're using with but not understanding how or why, what other disasters are buried in this codebase, and how are they going to screw me?
Because I'm not paranoid enough, my first thought is they went back to old code after learning about context managers, copied that code into the with block, and forgot to delete the close().
Oh it does hurt readability. It adds an unnecessary statement, and anyone debugging that code has to reason about whether it is needed.
In this particular case it doesn't have much effect, but it hints a problems down the line. Imagine instead
with some_proprietary_thing() as out:
out.send(data)
out.close()
Now... My first thought would be that someone messed up the context manager implementation and the explicit .close() is needed. But then, why is there no try/finally? Is that intended?
Small damages to readability accumulate, and end up hurting maintainability. They are also rarely coming alone.
Agreed, things like this really shouldn't become a habit and are likely not the only issues in the whole thing. For me, the explicit close didn't matter as I wasn't aware of context managers before this post, so it didn't intimidate me, but for somebody experienced in python (just like you are I assume), this would be much more confusing, as, like you said, you would assume the close is needed for whatever reason, hurting readability for you.
The with statement in Python indicates that a context handler is used. The are used to handle resources properly. You can define actions that are done if the with block was successfully executed or an error occurred, or in any case.
In this case the context manager will always close the file. So the creds.close() statement is not necessary.
I am new to Python, though years of Delphi/C++ experience in the past, and I am going to check my most recent projects as I suspect I have probably done the same thing
I agree that it could be improved, but this is the equivalent of locking your car with the door lock, then clicking the lock on your keys as you walk away. It's all but harmless (you'd have to really squint to see any problem with it) and probably arose simply out of an honestly decent habit (making sure to close files/clean up after your code).
Hardly bad code, just some unnecessary redundancy. In my opinion it also reads really well, I would question myself if I'm closing the file otherwise (now I know though).
costly
I'm just using Python for scripting, rarely for anything performance based. I really don't care about a small decrease in efficiency if it improves readability in most cases.
According to your link SystemExit is just a subclass of BaseException, which has the same behavior as Exception except they are not caught by except Exception. That means when a SystemExit is thrown, finally blocks and context managers all work normally. sys.exit() is implemented by throwing this exception, so that most cleanups are performed. If you want to exit without cleanups, you need to call os._exit().
About SystemExit and BaseException (and other direct subclasses of SystemExit other than Exception)... They're not subclasses of Exception, unlike other exceptions, that's what makes them different.
Also, when i tested this (on 3.9), the finally block was not executed (you can test it out), only a bare except or one that specifically handles these exceptions can catch them (and then a finally can also run).
As for cleanup on raising SystemExit, you're correct, thanks for that :) (seriously)... but I guess you meant os._exit().
Sure, but this is /r/badcode, not /r/programminghorror. It's still bad code, and it also shows a fundamental lack of understanding what a with clause does.
So you're one those that say "as long as it runs".
if git was written with this mindset, would you hear of it today?... and if it actually happened that it survived, how slow would GitHub (and other hosting sites that use git) be?
I just re-read the comment you replied to and yours again, now I see that I misunderstood your statement... it was a simple but indirect answer to the previous comment.
Except this isn’t git. This doesn’t even look like anything in a production level environment. It’s a harmless mistake, and one where hopefully this individual can learn and improve from it. Better than having someone poke fun at something that just happened to be redundant.
Right, but the context matters, also. A simple program with a harmless mistake is not the same as pushing poorly written code that wasn’t reviewed into production that ends up breaking a website.
What matters is how it is corrected. I get that this subreddit is meant to show “bad” code—and we can find humor in some of it—but let’s not pretend none of us wrote bad code before. Adding to that poking fun at someone for a simple mistake like that, I bet the OP’s coding skills aren’t entirely shit-hot, either.
I'm not sure I get your point. This is a subreddit for bad code. The above is bad code. Therefore, it fits. Have we all written bad code at some point? Yes. Is that fact relevant? Not really, no.
Heck, I have written code I truly and utterly hate which is still in production – you get what you pay for – but I don't see why that would preclude my poking fun at other people's bad code.
It's quite obvious you're not a python programmer or don't know much... I don't mean that offensively, like I said, there's nothing immediately bad about that.
First, it's never "optimized away" by the interpreter... the method will be executed.
Secondly, which of the aspects you mentioned does that call to .close() fulfill... readability, simplicity or efficiency?
I think you do and it shows your immaturity. If you really didn't mean it, don't say it, asshole.
Yes, I ment optimization in the compilation to bytecode, thanks for the reminder. I have no idea if that happens, but I expect it will somewhere if there's redundant code.
I'm just trying to make a point that efficiency wise it might not matter.
On your second point: readability, you can read that ".close" closes the file. Something that you would have to assume if it wasn't there. But it can be argued if it increases readability, for me it initially did. Now it wouldn't.
Sorely a redundant close call is much much better then a faulty "if done: close()" or the like. Failing to close files can lead to some serious security issues.
The reason why you don’t need close is because it is done for you. When you use ‘with’ (open(“filename” w) …)the file is closed at the end of the indentation.
That's the point. What that person said in quotes would be said by the abovementioned boss, who is pedantic about useless shit and knows next to nothing.
Oh, I've had those - Youngish boss: "since when did SQL do THAT?! Is it a new feature? I don't think we should be using untested new stuff.". Me (a greybeard): "1982 I believe...."
Yes, kinda... the context manager (the object referenced/created in the statement header) is actually the one that handles the resource initialization and cleanup but the with statement helps to call the concerned methods of the context manager.
It is not exactly the same. json.dump will smartly buffer the json object. Dumps will render the entire object as a string first and is thus vastly innefficient.
Dumps will take 1G of memory if you dump a 1G json object. Dump should use the same amount of memory no matter the size of what you are dumping.
I know it's a bit pedantic, but it's important to point out for those who are unaware.
144
u/AnonymouX47 __dude__ Aug 17 '21
Found this on Github.
133
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Aug 17 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
80
u/[deleted] Aug 17 '21
Honestly I don't think this is terrible. Of course, it's redundant, but it likely won't make the program run any slower (at least super insignificant) nor does it hurt readability.
185
u/deeepanshu98 Aug 17 '21
I dont understand the problem. 😶
7
u/Few-Adhesiveness7235 Aug 17 '21
Like all mistaken code, it's not a problem unless the boss insists it not be fixed. "Just in case the
withfails", or something.5
u/farmerau Aug 18 '21
Yeah if this is the biggest problem in the codebase, you’re on one hell of a team.
2
u/[deleted] Aug 18 '21
My Python is fairly weak... The with block handles the cleanup of resources I am guessing?
45
u/JohnTheCoolingFan Aug 17 '21
Also could've used dump instead of dumps to write.
3
u/skilledpigeon Aug 17 '21
If this is "bad" code in your code base then the rest best be damn perfect.
4
u/stayclassytally Aug 17 '21
If this is /r/barcode worthy than y’all couldn’t hang on my teams
1
u/[deleted] Aug 17 '21
What is this editor? Looks pretty slick
3
u/new2bay Aug 17 '21
At least they didn't do the whole try/except/finally dance inside the with statement.
5
u/circuit10 Aug 17 '21
What’s this thing that puts it in a Mac OS style window? I see it in lots of places
2
u/rgfz Aug 17 '21
Yeah but now it’s reeaally closed
0
u/[deleted] Aug 18 '21
[deleted] — view deleted comment
0
u/[deleted] Aug 17 '21
[deleted] — view deleted comment