Python 3.9:IsoCalendarDate数据的取消勾选返回一个元组

2024-09-30 06:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python 3.9中考虑下面的讨论/特性: https://bugs.python.org/issue24416

简言之,决定将datetime.date.isocalendar的结果改为namedtuple而不是tuple

现在,我可以看到这样做的好处,但他们也决定将新对象(datetime.IsoCalendarDate)作为元组“pickle”:
https://github.com/python/cpython/commit/1b97b9b0ad9a2ff8eb5c8f2e2e7c2aec1d13a330#diff-2a8962dcecb109859cedd81ddc5729bea57d156e0947cb8413f99781a0860fd1R1214

所以我的问题是,为什么他们要直接创建对象,以及“pickle and unpickle”对象需要稍微不同的流

例如:

import datetime
from pathlib import Path
import pickle



RESULTS_CACHE_PICKLE = Path('cache.pickle')


if RESULTS_CACHE_PICKLE.is_file():
    with open(RESULTS_CACHE_PICKLE, 'rb') as f:
        icd = pickle.load(f)
else:
    icd = datetime.date(2019, 1, 1).isocalendar()
    with open(RESULTS_CACHE_PICKLE, 'wb') as f:
        pickle.dump(icd, f)
        
        
print(icd.year)

结果:

$ python icd_test.py
2019
$ python icd_test.py
Traceback (most recent call last):
  File "icd_test.py", line 19, in <module>
    print(icd.year)
AttributeError: 'tuple' object has no attribute 'year'

这种不一致在我看来是不稳定的。这种情况在语言的其他地方发生过吗


Tags: 对象pyhttpstestimportcachedatetimedate
1条回答
网友
1楼 · 发布于 2024-09-30 06:24:47

我猜,正如蝙蝠侠在this answer中的评论所建议的那样:

One is that namedtuple isn't a class, it's a class factory that returns a class, which you in turn use to make instances. (...)

不幸的是,这正是我们在IsoCalendarDate(tuple)类代码中可以看到的情况(有意地!):

def __reduce__(self):
    # This code is intended to pickle the object without making the
    # class public. See https://bugs.python.org/msg352381
    return (tuple, (tuple(self),))

因此,对于some reason,似乎故意采用了不合理的方法,但我不知道(m)Python代码中有任何类似的情况

我想你可以把它当作虫子来养。也许从pickle的角度来看,保持IsoCalendarDate私有化的理由应该重新考虑

相关问题 更多 >

    热门问题