pythonpython-3.xpicklenamedtuple

_pickle.PicklingError: Can't pickle <class '__main___.{CONST} '>: attribute lookupfaileddir_namesmain_on __main__ failed


firstly dir_names works well when pickling

dir_names = collections.namedtuple('dir_names', ['mark', 'category'])
pickle.dump(dir_names, open('tmp.bin', 'wb'))

I want make dir_name a const

DIR_NAMES = collections.namedtuple('dir_names', ['mark', 'category'])
pickle.dump(DIR_NAMES, open('tmp.bin', 'wb'))

but when pickling it, i got this error

Traceback (most recent call last):
  File "/Users/zyq/CC_Cat/warc_process.py", line 376, in <module>
    pickle.dump(DIR_NAMES, open('tmp.bin', 'wb'))
_pickle.PicklingError: Can't pickle <class '__main__.dir_names'>: attribute lookup dir_names on __main__ failed

I wonder why it's goes bad when being a const, and why DIR_NAMES been lowerwised at __main__.dir_names

I tried defaultdict works well

DD = collections.defaultdict(int)
pickle.dump(DD, open('tmp.bin', 'wb'))

Solution

  • It seems pickle needs eexactly the same name in namedtuple("DIR_NAMES", ...) as in variable DIR_NAMES = ...

    DIR_NAMES = collections.namedtuple('DIR_NAMES', ['mark', 'category'])
    pickle.dump(DIR_NAMES, open('tmp.bin', 'wb'))
    

    You can see this problem also in answers: