News for hackers. Stuff that matters.
Re:What's New in Python 3.12 by ddejohn on Wednesday October 18, 2023 @02:15PM (#37932523)
> Of course this only works at one level and not arbitrarily deeply

It does though, you can chain as many of these as you want:

    some_dict.get("level_1_key", {}).get("level_2_key", {}).get("level_3_key", {})...
edit:

>> but you still need to check for None with this code

> Not sure what you mean here. You only have to check for None if you use `.get("key")` and don't provide a fallback value.

GP was talking about `{"foo": None}` and trying to drill deeper, which I misunderstood. Still, a simple try/except allows you to short-circuit the deeply nested access.

Re:What's New in Python 3.12 by smilliken on Wednesday October 18, 2023 @02:21PM (#37932595)
The issue is if the dictionary has a key defined and the value is None. Your get expression will return None, causing your next access to raise an error.
Re:What's New in Python 3.12 by ddejohn on Wednesday October 18, 2023 @02:32PM (#37932731)
Ah, I see. Still, I'd just catch that exception and move on because it's obvious you won't have anything more deeply nested anyway. Blowing up on `None` is an easy short-circuit.
Re:What's New in Python 3.12 by kh_hk on Wednesday October 18, 2023 @02:27PM (#37932668)

    >>> foo = {"foo": None}
    >>> print(foo.get('foo', {}).get('bar'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'NoneType' object has no attribute 'get'
    >>> print((foo.get('foo') or {}).get('bar'))
    None
Re:What's New in Python 3.12 by ddejohn on Wednesday October 18, 2023 @02:33PM (#37932751)
Right, see my other comment:

> Blowing up on `None` is an easy short-circuit.

The thing being discussed is attempting to access deeply nested values, so short-circuiting here is a win-win. I.e., you wouldn't want to unnecessarily traverse tons of empty dictionaries using the `.get() or {}` trick.