string formatting quirk?

Peter Otten __peter__ at web.de
Fri May 20 07:54:37 EDT 2005


anuraguniyal at yahoo.com wrote:

> ''%([]) doesn't raise exception
> but
> ''%('') does
> 
> Can anyone explain me why??

That is a side-effect of duck-typing. The duck-type of an empty list is
indistinguishable from that of an empty dictionary. Not testing the exact
type here achieves consistency with the behaviour of custom dictionaries,
e. g: 

>>> class List(list):
...     def __getitem__(self, index):
...             return list.__getitem__(self, int(index))
...
>>> "%(0)s" % List([42])
'42'
>>> "%(1)s %(0)s" % List([42, 24])
'24 42'
>>> "" % List([])
''

Peter




More information about the Python-list mailing list