3 ms·
I agree. It's absolutely silly that there's nothing to make statements like something['nested']['blah']['bloop'] some.namespace.with['stuff'] safe wit
by Spivak 4y ago
I agree. It's absolutely silly that there's nothing to make statements like
something['nested']['blah']['bloop']
some.namespace.with['stuff']
safe with None. Your options are using jmespath, your own similar function, or wrap it in a try block. Otherwise the whole syntax is essentially unusable. And because of the quirks of how __getitem__ is evaluated you can't even hack an infinite defaultdict to do the right thing because you can't detect the "last" access to return None so it's only good for when you want to assign to it.
- mjburgess 4y agobut python is simple /s
- baq 4y agosomething.get('nested', {}).get('blah', {}).get('bloop') works just fine but is mighty ugly. ...which is a hint to use something else in this case. dataclass, typed dictionary, deserialize properly, whatever.
- ok_dad 4y agoUltimately there’s some things that are best done with dictionaries, so it would be nice to have a simple tool to do this. Something like ‘x.?y.?z[“something”.?]’ would be nice, where the ? might pass any None through to the end without causing attribute and key errors.