Python 3.9:IsoCalendarDate数据的取消勾选返回一个元组
考虑Python3.9中的以下讨论/功能: 简而言之,决定将Python 3.9:IsoCalendarDate数据的取消勾选返回一个元组,python,pickle,python-datetime,python-3.9,Python,Pickle,Python Datetime,Python 3.9,考虑Python3.9中的以下讨论/功能: 简而言之,决定将datetime.date.isocalendar的结果更改为namedtuple而不是tuple 现在,我看到了这样做的好处,但他们也决定将新对象(datetime.IsoCalendarDate)作为元组“pickle”: 所以我的问题是,为什么他们要直接创建对象,以及“pickle and unpickle”对象需要稍微不同的流 例如: import datetime from pathlib import Path impo
datetime.date.isocalendar
的结果更改为namedtuple
而不是tuple
现在,我看到了这样做的好处,但他们也决定将新对象(datetime.IsoCalendarDate
)作为元组“pickle”:所以我的问题是,为什么他们要直接创建对象,以及“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'
$python icd_test.py
2019
$python icd_test.py
回溯(最近一次呼叫最后一次):
文件“icd_test.py”,第19行,在
打印(icd.年)
AttributeError:“tuple”对象没有属性“year”
这种不一致在我看来是不稳定的。这种情况在语言的其他地方发生过吗?我猜,正如蝙蝠侠在:
一是namedtuple
不是一个类,而是一个类工厂
返回一个类,然后使用该类生成实例。(……)
不幸的是,这正是我们在IsoCalendarDate(tuple)
class的代码中所看到的情况(有意!):
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),))
因此,似乎有意采用这种无关紧要的方法,但我不知道Python代码中有任何类似的情况
我想你可以把它当作虫子来养。也许应该重新审视从pickle
角度保持IsoCalendarDate
私有的基本原理