0

I would like to know what would be the most suited method to dump an object content?

So I can have any kind of objects. The example below is just an example and it is derived from io.Bytes just to have something to dump that are bytes.

I am clearly wondering whether repurposing the __str__ method is a good idea or not. Choosing between to_bytes or dump is more a consensual question and I think to_bytes would be more understandable.

Use __str__:

def Foo(io.Bytes):
   def __str__(self):
      self.seek(0)
      return self.read()

foo = Foo()
content = bytes(foo)

Use method to_bytes

def Foo(io.Bytes):
   def to_bytes(self):
      self.seek(0)
      return self.read()

foo = Foo()
content = foo.to_bytes()

Same as above, but with method dump

foo = Foo()
content = foo.dump()
nowox
  • 25,978
  • 39
  • 143
  • 293
  • @martineau I don't understand how the [question](http://stackoverflow.com/questions/4529815/saving-an-object-data-persistence-in-python) answers my question.This is not a duplicate. – nowox Nov 09 '16 at 11:41
  • OK, but your question is very unclear. – martineau Nov 09 '16 at 11:47
  • I propose 3 methods, I ask you to choose one. What is it unclear? – nowox Nov 09 '16 at 11:48
  • I could have asked the question differently: is it bad to use `bytes(foo)` to get the bytes content of an object as `__bytes__` does not exists? – nowox Nov 09 '16 at 11:49
  • Why do the `__str__` and `to_bytes` methods _read_ and return data? – martineau Nov 09 '16 at 11:51
  • What I didn't say is that my object has a binary content. It can be for example a `wave` sound, a `zip-file`, a serialized data written in `xml` or any content that can be dumped into bytes. I would like to know what is the most common name/method to get the binary content out of the object. – nowox Nov 09 '16 at 11:54
  • There is no common name or method. – martineau Nov 09 '16 at 11:55
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127709/discussion-between-nowox-and-martineau). – nowox Nov 09 '16 at 11:56
  • I don't have time (or interest) to dwell any further on your question. Another thing I don't understand is why your sample classes are derived from `io.Bytes`, as that makes little sense (_if_ I have any understanding of your question at all). Aside from that, you might want to name the method of your classes `to_bytes()` as that is what [something vaguely similar](https://docs.python.org/3/library/stdtypes.html#int.to_bytes) is called for the built-in `int` class in Python 3.2+. Repurposing the `__str__` method name to do what you want is not a good idea, IMO. – martineau Nov 09 '16 at 17:00

0 Answers0