string interpolation mystery in Python 2.6

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Sep 11 21:42:30 EDT 2009


On Fri, 11 Sep 2009 15:19:05 -0700, Chris Rebert wrote:

> On Fri, Sep 11, 2009 at 3:12 PM, Alan G Isaac <alan.isaac at gmail.com>
> wrote:
>> Michael Foord came up with a much simpler illustration.  With Python
>> 2.6::

[snip]

> Sounds like IOError or one of its ancestors defines both __str__() and
> __unicode__ () special methods but has them produce different output.


That's what it looks like to me too, which I wouldn't call either a bug 
or a feature. I don't think Python makes any promises regarding exception 
messages. 

However, I must admit I'm perplexed why the original example is calling 
__unicode__() in the first place! Given the line:

raise self.severe('Problems with "%s" directive path:\n%s: %s.'
    % (self.name, error.__class__.__name__, error))

it looks to me like it should be calling error.__str__() not 
error.__unicode(). Making the suggested edit:

raise self.severe('Problems with "%s" directive path:\n%s: %s.'
    % (self.name, error.__class__.__name__, str(error)))

should have no effect. But it (apparently) does. This brings us back to 
Alan's original question:

"MYSTERY: how can "%s"%error be different from "%s"%str(error) in Python 
2.6?"



-- 
Steven



More information about the Python-list mailing list