how to get all the "variables" of a string formating?

Duncan Booth duncan.booth at invalid.invalid
Wed Dec 6 13:33:26 EST 2006


"Calvin Spealman" <ironfroggy at gmail.com> wrote:

> I am not aware of anything in the stdlib to do this easily, but its
> pretty easy to get them. See this example:
> 
> class format_collector(object):
>    def __init__(self):
>       self.names = []
>    def __getitem__(self, name):
>       self.names.append(name)
>       return ''
> 
> collector = format_collector()
> "%(foo)s %(bar)s" % collector
> assert collector.names == ['foo', 'bar']
> 
> Of course, wrapping this functionality into a simple function is
> straightforward and will look better.

You should return a value like 0 instead of ''.

>>> collector = format_collector()
>>> "%(foo)s %(bar)d" % collector

Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    "%(foo)s %(bar)d" % collector
TypeError: int argument required




More information about the Python-list mailing list