`collections.Mapping`s: `.get(x)` v.s. `.__getitem__(x)`

Consider the following code:

from typing import assert_type, Mapping

def my_function(some_map: Mapping[str, object]):
    match some_map:
        case {"count": int()}:
            from_get = some_map.get('count')
            from_getitem = some_map['count']
            assert_type(from_get, int)
            assert_type(from_getitem, int)

Pyright, ty, and mypy don’t narrow some_map here. If a type checker did support narrowing on structural pattern matching, should it still show warnings for the second assertion? At runtime, the match/case statement checks that "count" in some_map and isinstance(some_map.get("count", None), int).

I ask because i am working on a PR for ty, and I’d like to make this assumption:

For any collections.Mapping, and any key, if key in mapping is True, then mapping.get(key, None) should be interchangeable with mapping[key].

1 Like

Your stated assumption seems correct and is, I think, confirmed by code like this:

from typing import TypedDict, assert_type

class D(TypedDict):
    count: int

def f(d: D) -> None:
    assert_type(d.get("count"), int)
    assert_type(d["count"], int)

but is there a reason you don’t simply write

from typing import assert_type, Mapping

def my_function(some_map: Mapping[str, object]):
    match some_map:
        case {"count": int(from_match)}:
            assert_type(from_match, int)

?

is there a reason you don’t simply write […] case {"count": int(from_match)} ?

For a single item, no. Capturing the value is the cleaner solution.

My actual use case is to take a returned dict[object, object], and use structural pattern matching to coerce it into a specific TypedDict (really, a Protocol with overloads for __getitem__, for variance reasons). If the match fails, I return None.

That assumption sounds right to me, unless I’m forgetting something. For a dictionary of type dict[K, V] the only difference between dict[...] and dict.get(...) is the former always returns V (raising KeyError on a missing item) and the latter returns V | D, where D is the type of the default given to .get() (which is None by default). So in this case where you can definitively say some_map has a key 'count' which is at least a subclass of int, I have no reason to believe either would ever give you two different values.

I think the assumption is fine for well-behaved mappings, but it’s possible for users to write a class that extends Mapping and overrides __getitem__ to behave differently.

A contrived example

class C(dict[str, object]):
    def __getitem__(self, key: str) -> object:
        return str(super().__getitem__(key))
1 Like

The type checker would need to differentiate between Mapping and MutableMapping, since it isn’t immediately known if the subject has undergone mutation between the pattern match and the item access.

Contrived example to illustrate this:

from collections.abc import Mapping, MutableMapping
from typing import assert_type

def my_function(some_map: Mapping[str, object]):
    match some_map:
        case {"count": int()}:
            if isinstance(some_map, MutableMapping):
                some_map.clear()
            from_get = some_map.get('count')
            from_getitem = some_map['count']
            assert_type(from_get, int)
            assert_type(from_getitem, int)