Python custom mapping class **unpacking and 'keys' attribute

老子叫甜甜 提交于 2019-12-10 09:20:56

问题


I'd like to use a SimpleNameSpace which can also act as a mapping so to be able to be used with ** unpacking.

Here is what I've done:

class MySimpleNameSpace(object):
    # my initial attempt subclassed SimpleNameSpace and Mapping, with
    # possibility to use MySimpleNameSpace as a dict as well as a normal SimpleNameSpace.

    def __init__(self, **kw):
        self.__dict__.update(kw)

    def __getitem__(self, item):
        return getattr(self, item)

    def keys(self):
        return self.__dict__.keys()

So far so good:

def f(**kw):
    print(kw)

ns = MySimpleNameSpace(a=42)
f(**ns)

Gives: {'a': 42}

More tricky:

ns.__getitem__ = "what"
ns.__iter__ = "da"
f(**ns)

Now gives:

{'a': 42, '__getitem__': "what", '__iter__', "da" }

But:

ns.keys = "douh"
f(**ns)

Obviously gives:

TypeError: attribute of type 'str' is not callable

Any idea if this would be feasible to have such a custom mapping class but able to use keys as a normal attribute?

I realize that subclassing (Mutable)Mapping makes this actually harder, if at all possible, but I think it's all because the functionality apparently requires the given object to have a keys method, which is unfortunate if we can't find a workaround for that.

As far as I know: iterating (__iter__) a dict gives its keys, then __getitem__ gives the value associated to a given key. As far as I know this would be all enough to implement the functionality?

来源:https://stackoverflow.com/questions/33547061/python-custom-mapping-class-unpacking-and-keys-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!