3 ms·
I would write: def safe_navigation(obj: Any, *path: str, default: Any = None, strict: bool = False) -> Any: sentinel = object() if strict else None
by o11c 3y ago
I would write:
def safe_navigation(obj: Any, *path: str, default: Any = None, strict: bool = False) -> Any:
sentinel = object() if strict else None
for key in path:
obj = obj.get(key, sentinel)
if obj is sentinel:
return default
return obj
The only new disadvantage of this is that it only works on mappings and no longer works on sequences.
But I really don't like having this much `Any`; it's generally a sign of poor design.
- ddejohn 3y agoI wouldn't call a function that mutates the input "safe navigation", personally :)
- o11c 3y agoEr, it doesn't? `.get()` (or `[]` in the original) doesn't change the object, and `obj =` only changes which object the local variable refers to? This isn't like C++ with its intrusive `=`.
- ddejohn 3y agoYou're right. Python is pass by reference and it's the reference being changed, not the object. This is what happens when you read code on the internet after drinks.