1

I'm working with a "bunch-class" just to save attributes.

class Args:pass
args = Args()
args.test = "test"
args.bla = [...]

Then I pass args as data to other functions (data=args). I think my problem is that only a reference is given to data: data = <__main__.Args object at 0x09E41050>

Im trying to use Pickle, but this error apears: pickle.PicklingError: Can't pickle <class '__main__.Args'>: it's not found as __main__.Args.

I dont know exactly if the problem is caused by the reference, but I think its probably.

Hubschr
  • 1,285
  • 6
  • 18
  • 35
  • 1
    This has nothing to do with references. This has everything to do with Pickle not being able to restore the class for you. `Args.__module__` says it is living in `__main__` but pickle cannot find it back there, and that means you cannot later unpickle the instance. – Martijn Pieters May 15 '14 at 08:05
  • 1
    I think you'd have better luck implementing a method for `Args` which serialises it's data somehow and pickles that onto disk. Then implement a `load` constructor method which can unpickle and create a new `Args` object with the deserialised data. – Noufal Ibrahim May 15 '14 at 08:08

2 Answers2

1

The solution is here: Answer from Martijn on other question

I was "creating" my bunch class inside a function. That was the problem. Sorry for the duplicate, should have searched better. Thanks anyways!

Community
  • 1
  • 1
Hubschr
  • 1,285
  • 6
  • 18
  • 35
1

What's the problem? If you use dill, instead of pickle, dill can correctly identify the class definition and correctly associate the class instance with it… hence an instance can be pickled without issue.

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill as pickle
>>> class Args: pass
... 
>>> args = Args()
>>> args.test = 'test'
>>> args.bla = ['foo']
>>> 
>>> _args = pickle.dumps(args)
>>> __args = pickle.loads(_args)
>>> __args
<__main__.Args instance at 0x101bf3560>
>>> __args.test
'test'
>>> __args.bla
['foo']
>>> 

This works in dill, because dill can pickle the class source instead of needing to pickle the class by name reference (as pickle does).

Get dill here: https://github.com/uqfoundation

Mike McKerns
  • 33,715
  • 8
  • 119
  • 139