3 ms·
There's certainly humor in a function called "safe navigation" mutating the data structure I'm supposedly safely navigating through :D
by ddejohn 3y ago
There's certainly humor in a function called "safe navigation" mutating the data structure I'm supposedly safely navigating through :D
- wodenokoto 3y agoI did type it on my phone, so I’m sure it needs a little correction (particularly the choice of exceptions is not optimal, I think) but feel free to run it in any recent python interpreter and return back with any mutation you see.
- wodenokoto 3y ago$ python3 Python 3.11.6 (main, Oct 2 2023, 20:46:14) [Clang 14.0.3 (clang-1403.0.22.14.1)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from typing import List >>> def safe_navigation(obj, path: List[str], default=None): ... try: ... for key in path: ... obj = obj[key] ... return obj ... except KeyError: ... return default ... >>> obj = {1: {1: {1: 2}}} >>> safe_navigation(obj, [1,1,1]) 2 >>> obj {1: {1: {1: 2}}}
- dmr_92 3y agoI don't think this is correct . The name obj gets rebound, but the dictionary being traversed isn't mutated in any way.