[Python-Dev] bytes / unicode
M.-A. Lemburg
mal at egenix.com
Wed Jun 23 11:18:23 CEST 2010
Nick Coghlan wrote:
> On Wed, Jun 23, 2010 at 4:09 AM, M.-A. Lemburg <mal at egenix.com> wrote:
>> It would be great if we could have something like the above as
>> builtin method:
>>
>> x.split('&'.as(x))
>
> As per my other message, another possible (and reasonably intuitive)
> spelling would be:
>
> x.split(x.coerce('&'))
You are right: there are two ways to adapt one object to another.
You can either adapt object 1 to object 2 or object 2 to object 1.
This is what the Python2 coercion protocol does for operators.
I just wanted to avoid using that term, since Python3 removes
the coercion protocol.
> Writing it as a helper function is also possible, although it be
> trickier to remember the correct argument ordering:
>
> def coerce_to(target, obj, encoding=None, errors='surrogateescape'):
> if isinstance(obj, type(target)):
> return obj
> if encoding is None:
> encoding = sys.getdefaultencoding()
> try::
> convert = obj.decode
> except AttributeError:
> convert = obj.encode
> return convert(encoding, errors)
>
> x.split(coerce_to(x, '&'))
>
>> Perhaps something to discuss on the language summit at EuroPython.
>>
>> Too bad we can't add such porting enhancements to Python2 anymore.
>
> Well, we can if we really want to, it just entails convincing Benjamin
> to reschedule the 2.7 final release. Given the UserDict/ABC/old-style
> classes issue, there's a fair chance there's going to be at least one
> more 2.7 RC anyway.
>
> That said, since this kind of coercion can be done in a helper
> function, that should be adequate for the 2.x to 3.x conversion case
> (for 2.x, the helper function can be defined to just return the second
> argument since bytes and str are the same type, while the 3.x version
> would look something like the code above)
True.
Note that the point of using a builtin method was to get
better performance. Such type adaptions are often needed in
loops, so adding a few extra Python function calls just to
convert a str object to a bytes object or vice-versa is a
bit much overhead.
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Jun 23 2010)
>>> Python/Zope Consulting and Support ... http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________
2010-07-19: EuroPython 2010, Birmingham, UK 25 days to go
::: Try our new mxODBC.Connect Python Database Interface for free ! ::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
http://www.egenix.com/company/contact/
More information about the Python-Dev
mailing list