python-configuration icon indicating copy to clipboard operation
python-configuration copied to clipboard

Bug: Equality comparison crashes for non-dicts

Open dargueta opened this issue 2 years ago • 0 comments

Attempting to compare a Configuration to anything that's not mapping-like crashes. This is a particularly nasty surprise when you have a function that returns either a Configuration or None and you need to check against None later.

To reproduce:

c = Configuration({})
c == None
In [23]: c = config.Configuration({})
In [24]: c == None
Traceback (most recent call last):
  File "/Users/diegoargueta/.pyenv/versions/aircraft/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3524, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-24-a6576c780e22>", line 1, in <module>
    c == None
  File "/Users/diegoargueta/.pyenv/versions/3.7.8/envs/aircraft/lib/python3.7/site-packages/config/configuration.py", line 72, in __eq__
    return self.as_dict() == Configuration(other).as_dict()
  File "/Users/diegoargueta/.pyenv/versions/3.7.8/envs/aircraft/lib/python3.7/site-packages/config/configuration.py", line 67, in __init__
    self._config: Dict[str, Any] = self._flatten_dict(config_)
  File "/Users/diegoargueta/.pyenv/versions/3.7.8/envs/aircraft/lib/python3.7/site-packages/config/configuration.py", line 102, in _flatten_dict
    nested = {k for k, v in d.items() if isinstance(v, (dict, Configuration))}
AttributeError: 'NoneType' object has no attribute 'items'

I believe this will fix it:

def __eq__(self, other: Any) -> bool:
    if isinstance(other, Mapping):
        # Do not reverse the order of the operands or you'll get into an infinite loop
        return self.as_dict() == other
    return False

dargueta avatar May 25 '22 18:05 dargueta