Jingkang50 / OpenOOD

Benchmarking Generalized Out-of-Distribution Detection
MIT License
858 stars 108 forks source link

Unexpected KeyError in Config Class When Checking for Attribute Existence #183

Closed liujunzhuo closed 1 year ago

liujunzhuo commented 1 year ago

Problem:

When running the command sh scripts/basics/cifar100/train_cifar100.sh, I encountered an unexpected error:

 File "OpenOOD/openood/networks/utils.py", line 45, in get_network
if hasattr(network_config, 'modification') and network_config.modification == 't2fnorm':
  File "OpenOOD/openood/utils/config.py", line 134, in __getattr__
    return self[key]
  File "OpenOOD/openood/utils/config.py", line 145, in __getitem__
    return dict.__getitem__(sub_cfg, sub_key)
KeyError: 'modification'

Analysis:

The root cause of this issue appears to be related to how the Config class handles attribute access via the __getattr__ method. When an attribute (key) is not present in the configuration, it currently raises a KeyError exception, which is unexpected behavior.

I would expect that when using hasattr(network_config, 'modification'), it should return False if the key 'modification' doesn't exist in the configuration, rather than raising a KeyError.

Proposed Solution:

I modify the __getattr__ method in the Config class to handle the case:

def __getattr__(self, key):
    try:
        return self[key]
    except KeyError:
        return None
zjysteven commented 1 year ago

Thank you for such detailed analysis; it makes sense to me. Would you mind opening a pull request for this if possible?

liujunzhuo commented 1 year ago

I've submitted the pull request, and I greatly appreciate your time and effort.

zjysteven commented 1 year ago

Thank you for the contribution! I've merged the pull request.