google / google/ml_collections

`isinstance(ConfigDict(...), collections.abc.Mapping)` returns `False`

Open
#47 3 comments 0 reactions 0 assignees View on GitHub
bug
Dominant language
Python
Stars
1k
Forks
49
PR merge metrics
No merged PRs in 30d

Description

**Describe the bug**
`isinstance(config_dict_obj, collections.abc.Mapping)` returns `False` even though it is a "dictionary" type

This is because class `ml_collections.config_dict.ConfigDict` does not inherit Python built-in abstract base class `collections.abc.Mapping`, despite being a "dictionary" type, producing unexpected behavior when using reflection or duck-typing with `isinstance(x, collections.abc.Mapping)`. This is especially problematic for serializing and logging code where it is common to apply different formatting to different collection types.

See PR [https://github.com/google/ml_collections/pull/46](https://github.com/google/ml_collections/pull/46) for proposed solution.

**To Reproduce**
The following code snippet reproduces and illustrates the bug

```python
import collections.abc
from typing import Any
from ml_collections import config_dict

def safe_print(obj: Any):
"""Print object with masked values to avoid leaking API keys in the logs"""
if isinstance(obj, collections.abc.Mapping):
for k, v in obj.items():
print(f"{k}={'*' * len(str(v))}")
elif isinstance(obj, collections.abc.Sequence):
print(f"[ ... ({len(obj)} items)]")
else:
raise ValueError(f"Unsupported type: {type(obj)}")

safe_print({"a": 1})
>>> a=*

conf = config_dict.ConfigDict({"a": 1})
safe_print(conf)
>>> Traceback (most recent call last):
>>> File "", line 1, in
>>> File "", line 8, in safe_print
>>> ValueError: Unsupported type:

```

**Expected behavior**
`isinstance(config_dict_obj, collections.abc.Mapping)` should return `True`

**Environment:**
- OS: Linux (Pop_OS/Ubuntu)
- OS Version: 6.9.3/22.04
- Python: Python 3.10

**Additional context**
Correctly inheriting `collections.abc.Mapping` would also improve Python static type analysis tooling (eg Ruff)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.