gpt4 book ai didi

python - 使用 python 缩进命名空间

转载 作者:行者123 更新时间:2023-12-04 17:06:16 24 4
gpt4 key购买 nike

我有一个包含大量路径的配置文件,我想以某种方式组织它们。所以我决定使用 types.SimpleNamespace这样做:

paths = SimpleNamespace()
paths.base = '...'
paths.dataset.encoded = '...'

我得到了:
AttributeError: 'types.SimpleNamespace' object has no attribute 'dataset'

我试图定义 paths.dataset即使我不需要它,它也不起作用:
paths = SimpleNamespace()
paths.base = '...'
paths.dataset = '...'
paths.dataset.encoded = '...'
AttributeError: 'str' object has no attribute 'encoded'

我也试过这个:
_ = {
'base': '...',
'dataset': {
'encoded': '...',
}
}
paths = SimpleNamespace(**_)

结果如下:
>>> paths.dataset.encoded  # Error
AttributeError: 'dict' object has no attribute 'encoded'
>>> paths.dataset['encoded'] # works
'...'

这意味着 SimpleNamespace 仅适用于一层命名空间,对吗?

有其他解决方案吗?我的意思是除了对每个层使用 SimpleNamespace 之外的解决方案,如下所示:
dataset = SimpleNamespace()
dataset.encoded = '...'

paths = SimpleNamespace()
paths.base = '???'
paths.dataset = dataset

>>> paths.base
'???'
>>> paths.dataset.encoded
'...'

有任何想法吗?

最佳答案

我想出了这个解决方案:


def create_namespace(dictionary: dict):
"""Create a namespace of given dictionary

the difference between create_namespace and python's types.SimpleNamespace
is that the former will create name space recursively, but the later will
create the namespace in one layer indentation. See the examples to see the
difference.

Parameters
----------
dictionary : dict
A dict to be converted to a namespace object

Returns
-------
types.SimpleNamespace
A combination of SimpleNamespaces that will have an multilayer
namespace

Examples
--------
>>> dictionary = {
... 'layer1_a': '1a',
... 'layer1_b': {
... 'layer2_a': '2a',
... },
... }

>>> # types.SimpleNamespace
>>> simple = SimpleNamespace(**dictionary)
>>> simple.layer1_a
'1a'
>>> simple.layer1_b.layer2_a
AttributeError: 'dict' object has no attribute 'layer2_a'
# because layer1_b is still a dictionary

>>> # create_namespace
>>> complex = create_namespace(dictionary)
>>> complex.layer1_a
'1a'
>>> complex.layer1_a.layer2_a
'2a'
"""
space = {}
for key, value in dictionary.items():
if isinstance(value, dict):
value = create_namespace(value)
space[key] = value
return SimpleNamespace(**space)

但我认为有一种我没有看到的更好的方法。我很感激对此的任何评论。

关于python - 使用 python 缩进命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57222276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com