How does the __reduce__ function exactly work with the brine module?

I do not understand how a function __reduce__works exactly in the case of a module picklein Python.

Suppose I have the following class:

class Foo(object):
  def __init__(self, file_name = 'file.txt'):
    self.file_name = file_name
    self.f = open(self.file_name, 'w')

It cannot be pickled because the module pickledoes not know how to encode the file descriptor:

foo = Foo()
print(pickle.dumps(foo))

Conclusion:

TypeError: can't pickle file objects

But if I add a function __reduce__, it successfully encodes:

import pickle

class Foo(object):
  def __init__(self, file_name = 'file.txt'):
    self.file_name = file_name
    self.f = open(self.file_name, 'w')

  def __reduce__(self):
    return (self.__class__, (self.file_name, ))

foo = Foo()
print(pickle.dumps(foo))

Conclusion:

c__main__
Foo
p0
(S'file.txt'
p1
tp2
Rp3
.

Is it correct that the function __reduce__simply returns “instructions” for the deconstructor to recreate the original object if the call pickle.dumpsfailed?

This is not clear to me from the documentation.

+4
source share
1 answer

. __reduce__ , () , . , , ..

:

, . ; pickle . , , .

, . None . :

  • , .
  • . , .
  • , , __setstate__() , . , , __dict__.
  • , ( ) . obj.append(item), obj.extend(list_of_items). , , append() extend() . ( append() extend(), , , , .)
  • , ( ), -. obj[key] = value. , , __setitem__().
+1

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


All Articles