[Fix] Support use 'global variable' in config function (#390)
* Support use 'global var' in config function * upload test filepull/405/head
parent
81c3de54b9
commit
f850de71c3
|
@ -406,12 +406,20 @@ class Config:
|
|||
base_cfg_dict.update(_cfg_dict)
|
||||
|
||||
if filename.endswith('.py'):
|
||||
cfg_dict: dict = dict()
|
||||
with open(temp_config_file.name) as f:
|
||||
codes = ast.parse(f.read())
|
||||
codes = RemoveAssignFromAST(BASE_KEY).visit(codes)
|
||||
codeobj = compile(codes, '', mode='exec')
|
||||
eval(codeobj, {'_base_': base_cfg_dict}, cfg_dict)
|
||||
# Support load global variable in nested function of the
|
||||
# config.
|
||||
global_locals_var = {'_base_': base_cfg_dict}
|
||||
ori_keys = set(global_locals_var.keys())
|
||||
eval(codeobj, global_locals_var, global_locals_var)
|
||||
cfg_dict = {
|
||||
key: value
|
||||
for key, value in global_locals_var.items()
|
||||
if (key not in ori_keys and not key.startswith('__'))
|
||||
}
|
||||
elif filename.endswith(('.yml', '.yaml', '.json')):
|
||||
cfg_dict = load(temp_config_file.name)
|
||||
# close temp file
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
# Copyright (c) OpenMMLab. All rights reserved.
|
||||
item1 = 1
|
||||
|
||||
|
||||
def get_item2():
|
||||
return item1 + 1
|
||||
|
||||
|
||||
item2 = get_item2()
|
|
@ -651,6 +651,13 @@ class TestConfig:
|
|||
}]],
|
||||
e=[1, 2])
|
||||
|
||||
# Test use global variable in config function
|
||||
cfg_file = osp.join(self.data_path,
|
||||
'config/py_config/test_py_function_global_var.py')
|
||||
cfg = Config._file2dict(cfg_file)[0]
|
||||
assert cfg['item1'] == 1
|
||||
assert cfg['item2'] == 2
|
||||
|
||||
def _merge_recursive_bases(self):
|
||||
cfg_file = osp.join(self.data_path,
|
||||
'config/py_config/test_merge_recursive_bases.py')
|
||||
|
|
Loading…
Reference in New Issue