Pre-PEP: Refusing to guess in string formatting operations

Cherniavsky Biniamin cben at techunix.technion.ac.il
Mon Mar 17 05:23:41 EST 2003


In article <mailman.1047415702.22254.python-list at python.org>, Inyeol Lee wrote:
>> This shorthand is bad because:
>> 
>> 1. When you pass a single object without the singleton tuple around
>>    it, your code will break it the object happens to be a tuple:
>> 
>>    >>> def decorate(obj):
>>    ...     return '-> %s <-' % obj
>>    ...
>>    >>> decorate(1)
>>    '-> 1 <-'
>>    >>> decorate((1,))
>>    '-> 1 <-'           # instead of '-> (1,) <-'
>>    >>> decorate((1,2))
>>    Traceback (most recent call last):
>>      File "<stdin>", line 1, in ?
>>      File "<stdin>", line 2, in decorate
>>    TypeError: not all arguments converted during string formatting
>
>How about this?
>
>>>> def decorate(obj):
>>>> ...     return "-> %s <-" % str(obj)
>>>> ... 
>>>> decorate(1)
>'-> 1 <-'
>>>> decorate((1,))
>'-> (1,) <-'
>>>> decorate((1,2))
>'-> (1, 2) <-'
>>>>
>
>Explicit is better than implicit. ;-)
>
Exactly. ;-) Relying on the guessing is a bad idea, that's why propose to get
rid of it (by first providing alternatives).  You have a point that in many
cases you know it won't ever be a tuple so you are safe but in this case the 
`str()` call was inserted only for ensuring it so this should be better yet 
(except for the arbitrariness of the punctuation)::

    def decorate(obj):
        return '-> %s <-' / obj

-- 
Beni Cherniavsky <cben at tx.technion.ac.il>




More information about the Python-list mailing list