Python: unable to detect module object errors

I am trying to decompose a large class and get "TypeError: cannot sort module objects". despite the fact that I’m watching over the network, I can’t understand exactly what this means. and I'm not sure which "module object" is causing problems. is there any way to find the culprit? stack trace does not indicate anything.

+10
source share
3 answers

I can reproduce the error message as follows:

import cPickle

class Foo(object):
    def __init__(self):
        self.mod=cPickle

foo=Foo()
with file('/tmp/test.out', 'w') as f:
    cPickle.dump(foo, f) 

# TypeError: can't pickle module objects

Do you have a class attribute that refers to a module?

+9
source

Python . ? . Python / . Python, dill.

Python 3.2.5 (default, May 19 2013, 14:25:55) 
[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
>>> import os
>>> dill.dumps(os)
b'\x80\x03cdill.dill\n_import_module\nq\x00X\x02\x00\x00\x00osq\x01\x85q\x02Rq\x03.'
>>>
>>>
>>> # and for parlor tricks...
>>> class Foo(object):
...   x = 100
...   def __call__(self, f):
...     def bar(y):
...       return f(self.x) + y
...     return bar
... 
>>> @Foo()
... def do_thing(x):
...   return x
... 
>>> do_thing(3)
103 
>>> dill.loads(dill.dumps(do_thing))(3)
103
>>> 

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

+9

:

?

:

  • None, True, False

  • , ,

  • strings, bytes, bytearrays

  • , , ,

  • , ( def, )

  • ,

  • ,

  • , __dict__ __getstate__() ( . " ").

, . , deepcopy, pickle, deepcopy:

, , , , , , , , . "" ( ), ; , .

- @property . , :

    import numpy as np
    import pickle

    class Foo():
        @property
        def module():
            return np

    foo = Foo()
    with open('test.out', 'wb') as f:
        pickle.dump(foo, f)
0
source

Source: https://habr.com/ru/post/1744548/


All Articles