Pre-PEP: Refusing to guess in string formatting operations

Inyeol Lee inyeol.lee at siimage.com
Tue Mar 11 15:46:48 EST 2003


> 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. ;-)

Inyeol...





More information about the Python-list mailing list