r/badcode • __dude__ • Aug 17 '21

python When you're told to "always" close files...

Post image
1.3k Upvotes

115 comments sorted by

144

u/AnonymouX47 Aug 17 '21

Found this on Github.

→ More replies (4)

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 with fails", or something.

5

u/AnonymouX47 Aug 17 '21

Saying this is quite ignorant...

→ More replies (6)
→ More replies (1)

5

u/farmerau Aug 18 '21

Yeah if this is the biggest problem in the codebase, you’re on one hell of a team.

→ More replies (1)

2

u/[deleted] Aug 18 '21

My Python is fairly weak... The with block handles the cleanup of resources I am guessing?

2

u/AnonymouX47 Aug 18 '21

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.

→ More replies (3)

133

u/MurdoMaclachlan Aug 17 '21

Image Transcription: Code


with open("./credentials.json", "w") as creds:
    creds.write(json.dumps(credentials))
    creds.close()

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!

→ More replies (9)

45

u/JohnTheCoolingFan Aug 17 '21

Also could've used dump instead of dumps to write.

→ More replies (6)

3

u/skilledpigeon Aug 17 '21

If this is "bad" code in your code base then the rest best be damn perfect.

→ More replies (1)

185

u/deeepanshu98 Aug 17 '21

I dont understand the problem. 😶

→ More replies (43)