在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'
这种不一致在我看来是不稳定的。这种情况在语言的其他地方发生过吗
我猜,正如蝙蝠侠在this answer中的评论所建议的那样:
不幸的是,这正是我们在
IsoCalendarDate(tuple)
类代码中可以看到的情况(有意地!):因此,对于some reason,似乎故意采用了不合理的方法,但我不知道(m)Python代码中有任何类似的情况
我想你可以把它当作虫子来养。也许从
pickle
的角度来看,保持IsoCalendarDate
私有化的理由应该重新考虑相关问题 更多 >
编程相关推荐