Remix.run Logo
▲ saint-evan 10 hours ago

I don't get it... What's the problem? I too prefer getting None as opposed to a key Error which would prolly necessitate a try..catch as opposed just checking for None. I'm having trouble reasoning up a situation where raising a keyError would make any sense over a None for data structures like dicts that could return a value or no value! Help?

▲beecasthurlbow 10 hours ago | parent | next [-]

KeyError localizes the issue to the lookup (ie “right here this key should be present and it’s not) vs later in the code where it can be hard to trace where the None value came from or how to handle it.

▲saint-evan 9 hours ago | parent [-]

Well... yeah but at the cost of halting your entire program? As opposed to logging?

▲wfn 9 hours ago | parent [-]

Think of it like an assert.

Sometimes you do want some flow to terminate if a schema / data contract is breached, and not have this broken data contract propagate elsewhere / outwards.

And/or, it is a perfectly valid pattern to indeed add try..catch, and contain (hence "localize") the issue there and then. If there is a way to handle this breach - you will need some kind of if check anyway. Catching by matching against the particular KeyError exception is in fact robust - and if you forgot to add an intended catch, then the exception will propagate upstack, yes - which is what you want - and this way you do not need to worry about forgetting an "if None" check.

This sort of approach makes it structurally impossible to "forget" - if exception is not caught, it will abort the cannot-be-null breach continuing with program flow, possibly (e.g.) ending up persisted in some place it shouldn't be, causing problems later.

▲saint-evan 7 hours ago | parent [-]

yes, that makes sense. Thank yu so much!

▲sirsinsalot 5 hours ago | parent | prev [-]

Or you know, test if the key exists before using it. The key could exist and be None, representing a legitimate None at that key. Or the key might not exist and asking for it is a bug.

Use a defaultdict if you must have all keys optional. Using get() everywhere is buggy because it masks illegal key use.