我有一个模块(module2),其中包含一个函数:
#module2
def get_items():
return {'thing1': 'string_value',
'thing2': 1,
'thing3': 'self.foo1',
'thing4': 'self.foo2.bar',
'thing5': 'self.foo3.bar['some_key']'}
可以看出,字典键是字符串,值包括字符串和整数,还包括属性(即self.foo1
),嵌套属性(即self.foo2.bar
)和嵌套属性中的字典引用(即self.foo3.bar['some_key']
)写为字符串。之所以将它们写为字符串是因为在module2的上下文中没有self,而是我想将此字典导入另一个模块(module1)并引用一些self。
我知道我可以通过getattr(self, value.split('self.')[1]
访问属性。
我设置了一个递归函数来获取嵌套的属性,在下面的代码中将其称为“ rgetattr”。
我唯一不知道的是如何处理嵌套字典。
具体来说,我想要以下行为:
#module2
def get_items():
return {'thing1': 'string_value',
'thing2': 1,
'thing3': 'self.foo1',
'thing4': 'self.foo2.bar',
'thing5': 'self.foo3.bar['some_key']'}
#module1
Class my_class:
def __init__(self, foo):
self.foo = foo # Note that this foo is an object
### The following is how I would like the imported dictionary to look ###
my_desired_dict = {'thing1': 'string_value',
'thing2': 1,
'thing3': self.foo1,
'thing4': self.foo2.bar
'thing5': self.foo3.bar['some_key']}
### The following is how I am attempting to achieve this ###
import module2
item_dict = module2.get_items()
my_desired_dict = {}
for i in item_dict:
if type(item_dict[i])==str and item_dict[i].startswith('self.'):
variable = item_dict[i].split('self.')[1]
this_attr = rgetattr(self, variable)
else:
this_attr = item_dict[i]
my_desired_dict[i] = this_attr
def rgetattr(obj, attr, *args):
def _getattr(obj, attr):
return getattr(obj, attr, *args)
return functools.reduce(_getattr, [obj] + attr.split('.'))
如果有办法在不触发NameError的情况下,我愿意将module2中的“属性引用字符串”更改为self.foo等。