This rule raises an issue when isinstance(value, dict) guards a branch that only reads from value.
An isinstance check against a concrete mutable mapping type accepts only instances of that type. However, a mapping interface provides
the read-only operations that code commonly needs, such as item access and lookup methods.
When code only reads from the guarded value, requiring the concrete mutable type rejects other values that provide all the required mapping operations. This makes the code less flexible and prevents callers from using compatible mapping values without providing additional safety.
For example, a mapping proxy exposes a read-only mapping API but is not a dict:
from collections.abc import Mapping
from types import MappingProxyType
settings = MappingProxyType({"timeout": 30})
isinstance(settings, dict) # False
isinstance(settings, Mapping) # True
Use the mapping interface when the code only needs mapping reads. Keep a concrete mutable-mapping check when the code mutates the value or relies on behavior that the interface does not guarantee.
An unnecessarily narrow concrete dictionary-type check can reject valid read-only mapping values, including immutable mapping instances. This reduces API compatibility and can cause avoidable failures when callers provide another mapping implementation.
Replace the concrete dict type check with collections.abc.Mapping. This accepts both dictionaries and read-only mappings
while preserving the item-read behavior.
def name_of(value):
if isinstance(value, dict): # Noncompliant
return value["name"]
return None
from collections.abc import Mapping
def name_of(value):
if isinstance(value, Mapping):
return value["name"]
return None