Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

通过值解压的方式实例化得到的不是一个字典对象 #2

Open
2018-11-27 opened this issue Aug 1, 2022 · 1 comment
Open
Assignees
Labels
NotProcess question Further information is requested

Comments

@2018-11-27
Copy link
Member

内置 dict 通过值解压的方式实例化得到的是一个字典对象,而 gdict 通过值解压的方式实例化得到的是一个列表对象。且看下面的代码运行结果:

>>> dict((x, y) for x, y in [('a', 'A'),  ('b', 'B')])
{'a': 'A', 'b': 'B'}

>>> gdict((x, y) for x, y in [('a', 'A'), ('b', 'B')])
[['a', 'A'], ['b', 'B']]

我们希望它们得到同样的结果,无论在任何情况下。gdict 得到列表对象肯定是错误的,这是一个严重的问题,它使我们对 gdict 的理念产生了偏移,我们希望 gdict 在任何时候都有着与 dict 相同的特性。

@2018-11-27 2018-11-27 added the question Further information is requested label Aug 1, 2022
@2018-11-27
Copy link
Member Author

2018-11-27 commented Aug 2, 2022

发现这样的问题我们反思,这在设计之初大意了,我们没有考虑到值解压的方式创建字典。gdict 实例化的核心在于深度转换 dict,将 dict 转换为 gdict,深度的理解是同时会转换 dict 内层的 dict

深度转换dict 与 值解压实例化gdict 是冲突的。

gdict 实例化是一个递归的过程,当传入一个字典以外的容器类对象或 Iterator 对象时,它会分解容器或 Iterator 并依次进入递归层,并在所有递归层结束后返回一个列表对象,且看下面的代码:

def __new__(cls, __data__={}, **kw):
    if isinstance(__data__, (list, tuple, set, frozenset, Iterator)):
        return [cls(v) for v in __data__]

介于此设计,做了深度转换dict,就无法再做值解压实例化 gdict,我们不考虑给 gdict 增加任何流程控制参数。如一定要做值解压实例化 gdict,可通过下面的方式:

>>> gdict(dict((x, y) for x, y in [('a', 'A'), ('b', 'B')]))
{'a': 'A', 'b': 'B'}

@2018-11-27 2018-11-27 self-assigned this Aug 2, 2022
@2018-11-27 2018-11-27 added Pending NotProcess Processed question Further information is requested and removed question Further information is requested Pending Processed labels Aug 2, 2022
@2018-11-27 2018-11-27 pinned this issue Aug 5, 2022
@2018-11-27 2018-11-27 unpinned this issue May 2, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
NotProcess question Further information is requested
Projects
None yet
Development

No branches or pull requests

1 participant