Problem with mixing doctest with gettext _()

Peter Otten __peter__ at web.de
Fri Feb 27 22:31:24 CET 2004


Pierre Rouleau wrote:

> Peter Otten wrote:
>> Pierre Rouleau wrote:
>> 
>> 
>>>It worked, BUT only for a simple function, it fails if I add a another
>>>simple function:
>> 
>> 
>> Haven't read your post completely, but judging from the error message,
>> it's just a minor glitch in mydisplayhook(). Try the following instead:
>> 
>> 
>> 
>>>>>def mydisplayhook(a):
>> 
>> ...     if a is not None:
>> ...             sys.stdout.write("%r\n" % (a,))
>> ...
>> 
>> That should be able to cope with tuples as commandline results.
>> 
>> Peter
> 
> 
> You're right!  It does work. I must admit, that I don't see why though.
>   (a,) makes a tuple out of the `a` argument.  Does the %r conversion
> require a tuple?

The formatting operator behaves differently depending on whether the
righthand argument is a tuple or something else. 

formatstr % tuple

ensures that there is a corresponding format expression - e.g. "%s" or "%d"
- for every item in the tuple, whereas

formatstr % nontuple 

expects exactly one format expression. Therefore

"%r\n" % a

raises an exception when a is a tuple with more or less than one item and
wrongly prints the item's representation instead of the tuple's for
one-tuples.
Wrapping it like so (a,) fixes the problem because now we have always a
tuple with one item - where this item is sometimes a tuple.

An alternative approach would be to ensure that the righthand side is always
a nontuple:

"%s\n" % repr(a)

Peter






More information about the Python-list mailing list