Enumerating formatting strings

Peter Otten __peter__ at web.de
Wed Apr 20 03:14:40 EDT 2005


Greg Ewing wrote:

> Steve Holden wrote:
> 
>> I've been wondering whether it's possible to perform a similar analysis
>> on non-mapping-type format strings, so as to know how long a tuple to
>> provide,
> 
> I just tried an experiment, and it doesn't seem to be possible.
> 
> The problem seems to be that it expects the arguments to be
> in the form of a tuple, and if you give it something else,
> it wraps it up in a 1-element tuple and uses that instead.
> 
> This seems to happen even with a custom subclass of tuple,
> so it must be doing an exact type check.

No, it doesn't do an exact type check, but always calls the tuple method:

>>> class Tuple(tuple):
...     def __getitem__(self, index):
...             return 42
...
>>> "%r %r" % Tuple("ab") # would raise an exception if wrapped
"'a' 'b'"

> So it looks like you'll have to parse the format string.
 
Indeed.

Peter



More information about the Python-list mailing list