[Python-Dev] String coercion

Paul Prescod paul@prescod.net
Sat, 08 Jul 2000 08:32:03 -0500


Thomas Wouters wrote:
> 
> ...
> 
> The right hand side of the operation determines what the result is ? 

No, either side determines what the result is. This is not magic. It's
just like floating point coercion or complex number coercion.

> Somehow
> I find that confusing and counter-intuitive, but perhaps I'm too used to
> __add__ vs. __radd__ ;) 

This can be easily defined in terms of add and radd:

class PaulsString:
	def __init__( self, str ):
		self.str=str
	def __add__( self, foo ):
		return self.str  + str( foo )
	
	def __radd__( self, bar ):
		return str( bar ) + self.str

print PaulsString("abcdef")+5
print open+PaulsString("ghijkl")

abcdef5
<built-in function open>ghijkl

Here's an even simpler definition:

class PaulsString:
	def __init__( self, str ):
		self.str=str
	def __coerce__( self, other ):
		return (self.str, str( other ))

Ping says:
> As it stands, with both 8-bit strings and Unicode strings, i think
> this would result in too much hidden complexity -- thinking about this
> can wait until we have only one string type. 

I don't see any hidden complexity. Python has features specifically
designed to allow this sort of thing on a per-type basis.

-- 
 Paul Prescod - Not encumbered by corporate consensus
Pop stars come and pop stars go, but amid all this change there is one
eternal truth: Whenever Bob Dylan writes a song about a guy, the guy is
guilty as sin.
	- http://www.nj.com/page1/ledger/e2efc7.html