4 ms·
Depending on your perception, x.get is either error recovery (good) or a silent failure (bad). One is not necessarily better than the other; it depends on what
by rand_r 3y ago
Depending on your perception, x.get is either error recovery (good) or a silent failure (bad). One is not necessarily better than the other; it depends on what you want. In my experience, x[] is usually the better choice because failing fast makes debugging easier.
I hope no one is recommending x.get as a general practice, because that is pretty naive.
- orwin 3y agoYou're right, but actually... If you're a very junior sw engineer reading this, who hasn't done a lot of python, use x.get(). Almost always, so for you, always. This doesn't apply if you're a scientist or mostly writing small scripts, but if you are doing SWE, always use x.get(). Once you've understood python you can use x[] in limited cases. Never in your unit or functional tests. I code using x[], but later on I replace a lot of them with getter (around my second refactoring, when I add type hints and tests) especially in library or code that'll be shared.
- CalRobert 3y agoFor what it's worth, I only use x.get when having a missing key is a normal and expected part of the process. If I need to be able to expect a key to be in the dict then I'll use x[] so I can get a useful exception for debugging. Though really, this should only happen with validated inputs, and as Python adopts more type hinting dealing with this should get easier over time.
- Nimitz14 3y agoThis is terrible advice LOL.
- Ancalagon 3y agoCan you explain why? Non-python dev here.
- CalRobert 3y agoI've been around a while and I'm mentoring a junior dev, and one of the things that has come up is to fail as fast and as hard as possible. A silent failure is one of the worst things to have. And this is why I usually won't use .get on data that has presumably already been validated. But I was already rejected so I haven't been able to explain my logic :-). It's still nice to get their feedback, though. Funny enough, in Europe, you _should_ be able to get any written notes on you via GDPR.