Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes?

Is it normal for python's io.BytesIO.getvalue() to return str instead of bytes?

 Python 2.7.1 (r271:86832, Jun 13 2011, 14:28:51) 
 >>> import io
 >>> a = io.BytesIO()
 >>> a
 <_io.BytesIO object at 0x10f9453b0>
 >>> a.getvalue()
 ''
 >>> print type(a.getvalue())
 <type 'str'>
 >>> 

Should I file a bug?

like image 894
sorin Avatar asked Jun 25 '11 17:06

sorin


People also ask

What does io BytesIO () do?

It takes input POSIX based arguments and returns a file descriptor which represents the opened file. It does not return a file object; the returned value will not have read() or write() functions. Overall, io. open() function is just a wrapper over os.

What does Getvalue do in Python?

getvalue() just returns the entire contents of the stream regardless of current position.

What is a BytesIO object Python?

StringIO and BytesIO are methods that manipulate string and bytes data in memory. StringIO is used for string data and BytesIO is used for binary data. This classes create file like object that operate on string data. The StringIO and BytesIO classes are most useful in scenarios where you need to mimic a normal file.

How do I save a BytesIO file in Python?

First, open a file in binary write mode and then specify the contents to write in the form of bytes. Next, use the write function to write the byte contents to a binary file.


2 Answers

No, this isn't a bug. This is normal behaviour. See this answer: the bytes type in python 2.7 and PEP-358

It basically comes down that the 2.7 bytes is just an alias for str to smoothen the transition to 3.x.

like image 67
orlp Avatar answered Oct 25 '22 13:10

orlp


bytes doesn't exist as a separate kind of datastructure in Python 2.X so yes, it is entirely normal - str are bytestrings in Python 2 (unlike Python 3, where str are unicode strings).

like image 45
Amber Avatar answered Oct 25 '22 14:10

Amber