Commit 31e684fc authored by Kai Chen's avatar Kai Chen
Browse files

bug fix: raise exceptions for missing config keys

parent 685e8f99
......@@ -6,6 +6,26 @@ from importlib import import_module
from addict import Dict
from .path import check_file_exist
class ConfigDict(Dict):
def __missing__(self, name):
raise KeyError(name)
def __getattr__(self, name):
try:
value = super(ConfigDict, self).__getattr__(name)
except KeyError:
ex = AttributeError("'{}' object has no attribute '{}'".format(
self.__class__.__name__, name))
except Exception as e:
ex = e
else:
return value
raise ex
def add_args(parser, cfg, prefix=''):
for k, v in cfg.items():
......@@ -55,6 +75,7 @@ class Config(object):
@staticmethod
def fromfile(filename):
filename = osp.abspath(osp.expanduser(filename))
check_file_exist(filename)
if filename.endswith('.py'):
sys.path.append(osp.dirname(filename))
module_name = osp.basename(filename)[:-3]
......@@ -93,7 +114,7 @@ class Config(object):
raise TypeError('cfg_dict must be a dict, but got {}'.format(
type(cfg_dict)))
super(Config, self).__setattr__('_cfg_dict', Dict(cfg_dict))
super(Config, self).__setattr__('_cfg_dict', ConfigDict(cfg_dict))
super(Config, self).__setattr__('_filename', filename)
if filename:
with open(filename, 'r') as f:
......@@ -110,7 +131,7 @@ class Config(object):
return self._text
def __repr__(self):
return 'Config [path: {}]: {}'.format(self.filename,
return 'Config (path: {}): {}'.format(self.filename,
self._cfg_dict.__repr__())
def __len__(self):
......@@ -124,12 +145,12 @@ class Config(object):
def __setattr__(self, name, value):
if isinstance(value, dict):
value = Dict(value)
value = ConfigDict(value)
self._cfg_dict.__setattr__(name, value)
def __setitem__(self, name, value):
if isinstance(value, dict):
value = Dict(value)
value = ConfigDict(value)
self._cfg_dict.__setitem__(name, value)
def __iter__(self):
......
import os.path as osp
import pytest
from mmcv import Config
from mmcv import Config, FileNotFoundError
def test_empty():
......@@ -20,8 +20,10 @@ def test_fromfile():
assert cfg.filename == cfg_file
assert cfg.text == open(cfg_file, 'r').read()
with pytest.raises(FileNotFoundError):
Config.fromfile('no_such_file.py')
with pytest.raises(ValueError):
Config.fromfile('a/b/c.d.py')
Config.fromfile(osp.join(osp.dirname(__file__), 'data/config/a.b.py'))
def test_dict():
......@@ -49,12 +51,18 @@ def test_dict():
assert cfg.item2.a == 0
assert cfg.item3 == cfg_dict['item3']
assert cfg.item4 == cfg_dict['item4']
with pytest.raises(AttributeError):
cfg.not_exist
# field in cfg, cfg[field], cfg.get()
for name in ['item1', 'item2', 'item3', 'item4']:
assert name in cfg
assert cfg[name] == cfg_dict[name]
assert cfg.get(name) == cfg_dict[name]
assert cfg.get('not_exist') is None
assert cfg.get('not_exist', 0) == 0
with pytest.raises(KeyError):
cfg['not_exist']
assert 'item1' in cfg
assert 'not_exist' not in cfg
# cfg.update()
cfg.update(dict(item1=0))
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment