Unverified Commit c294d271 authored by lizz's avatar lizz Committed by GitHub
Browse files

Support dot in config.py file (#207)


Signed-off-by: default avatarlizz <lizz@sensetime.com>
parent 24a66f1d
# Copyright (c) Open-MMLab. All rights reserved. # Copyright (c) Open-MMLab. All rights reserved.
import os.path as osp import os.path as osp
import shutil
import sys import sys
import tempfile
from argparse import ArgumentParser from argparse import ArgumentParser
from importlib import import_module from importlib import import_module
...@@ -78,18 +80,17 @@ class Config(object): ...@@ -78,18 +80,17 @@ class Config(object):
filename = osp.abspath(osp.expanduser(filename)) filename = osp.abspath(osp.expanduser(filename))
check_file_exist(filename) check_file_exist(filename)
if filename.endswith('.py'): if filename.endswith('.py'):
module_name = osp.basename(filename)[:-3] with tempfile.TemporaryDirectory() as temp_config_dir:
if '.' in module_name: shutil.copyfile(filename,
raise ValueError('Dots are not allowed in config file path.') osp.join(temp_config_dir, '_tempconfig.py'))
config_dir = osp.dirname(filename) sys.path.insert(0, temp_config_dir)
sys.path.insert(0, config_dir) mod = import_module('_tempconfig')
mod = import_module(module_name) sys.path.pop(0)
sys.path.pop(0) cfg_dict = {
cfg_dict = { name: value
name: value for name, value in mod.__dict__.items()
for name, value in mod.__dict__.items() if not name.startswith('__')
if not name.startswith('__') }
}
elif filename.endswith(('.yml', '.yaml', '.json')): elif filename.endswith(('.yml', '.yaml', '.json')):
import mmcv import mmcv
cfg_dict = mmcv.load(filename) cfg_dict = mmcv.load(filename)
......
item1 = [1, 2]
item2 = {'a': 0}
item3 = True
item4 = 'test'
...@@ -18,7 +18,7 @@ def test_construct(): ...@@ -18,7 +18,7 @@ def test_construct():
def test_fromfile(): def test_fromfile():
for filename in ['a.py', 'b.json', 'c.yaml']: for filename in ['a.py', 'a.b.py', 'b.json', 'c.yaml']:
cfg_file = osp.join(osp.dirname(__file__), 'data/config', filename) cfg_file = osp.join(osp.dirname(__file__), 'data/config', filename)
cfg = Config.fromfile(cfg_file) cfg = Config.fromfile(cfg_file)
assert isinstance(cfg, Config) assert isinstance(cfg, Config)
...@@ -27,8 +27,6 @@ def test_fromfile(): ...@@ -27,8 +27,6 @@ def test_fromfile():
with pytest.raises(FileNotFoundError): with pytest.raises(FileNotFoundError):
Config.fromfile('no_such_file.py') Config.fromfile('no_such_file.py')
with pytest.raises(ValueError):
Config.fromfile(osp.join(osp.dirname(__file__), 'data/config/a.b.py'))
with pytest.raises(IOError): with pytest.raises(IOError):
Config.fromfile(osp.join(osp.dirname(__file__), 'data/color.jpg')) Config.fromfile(osp.join(osp.dirname(__file__), 'data/color.jpg'))
......
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