[Python-Dev] new buffer in python2.7

Lennart Regebro regebro at gmail.com
Mon Nov 8 12:08:24 CET 2010


On Wed, Oct 27, 2010 at 12:36, Antoine Pitrou <solipsis at pitrou.net> wrote:
> On 2010年10月27日 10:13:12 +0800
> Kristján Valur Jónsson <kristjan at ccpgames.com> wrote:
>> Although 2.7 has the new buffer interface and memoryview
>> objects, these are widely not accepted in the built in modules.
>> That's true, and slightly unfortunate. It could be a reason for
> switching to 3.1/3.2 :-)

It's rather a reason against it, as it makes supporting both Python 2
and Python 3 harder.
However, fixing this in 2.7 just means that you need to support 2.7x
or later only, so it's not a good solution.
I think using compatibility types is a better solution. I suggested
something like that for inclusion in "six", but it was softly
rejected. :-)
Something like this, for example. It's a str in Python2 and a Bytes in
Python3, but it extends both classes with a consistent interface.
Improvements, comments and ideas are welcome.
bites.py:
--------------------
import sys
if sys.version < '3':
 class Bites(str):
 def __new__(cls, value):
 if isinstance(value[0], int):
 # It's a list of integers
 value = ''.join([chr(x) for x in value])
 return super(Bites, cls).__new__(cls, value)
 def itemint(self, index):
 return ord(self[index])
 def iterint(self):
 for x in self:
 yield ord(x)
else:
 class Bites(bytes):
 def __new__(cls, value):
 if isinstance(value, str):
 # It's a unicode string:
 value = value.encode('ISO-8859-1')
 return super(Bites, cls).__new__(cls, value)
 def itemint(self, x):
 return self[x]
 def iterint(self):
 for x in self:
 yield x
--------------------
-- 
Lennart Regebro: http://regebro.wordpress.com/
Python 3 Porting: http://python3porting.com/
+33 661 58 14 64


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /