New-style string formatting (Was: Re: Tuple "detection")

Gerrit Holl gerrit at nl.linux.org
Tue May 20 05:43:49 EDT 2003


Hi all,

Is this the right place for this discussion or should this be
on python-dev?

Alexander Semenov schreef op maandag 19 mei om 22:57:37 +0000:
> I propose change % to str.__call__()

Sounds great! Unless we're overlooking something...

> This can clear many questions about precedence of operation and tuple
> packing.

It solves a lot of existing problems:
    * lists not allowed
    * precedence/operation

> In my opinion, this looks great:
> 'Hello %s, you got %d apples.'('Bob', 5)
> or
> 'Hello %(name)s, you got %(number)d apples.'(name='Bob', number=5)

I have here included a class that does exactly that:

#!/usr/bin/python

class MyString(str):
   
    def __call__(self, *args, **kw):
        if args and kw:
            raise TypeError("can't mix %s and %(...)s")
        if args:
            return str.__mod__(self, args)
        if kw:
            return str.__mod__(self, kw)

def test():
    m1 = MyString("Hello %s, you got %d parrots.")
    m2 = MyString("Hello %(name)s, you got %(number)d parrots.")
    l = ("shopkeeper", -3)
    d = {"name": "shopkeeper", "number": -3}
    print m1("Shopkeeper", -3)
    print m1(*l)
    print m2(name="shopkeeper", number=-3)
    print m2(**d)

if __name__ == "__main__":
    test()

I hope the whitespace survives usenet, but if it doesn't the idea is still
clear.

> This maybe done without any impact to current codebase,
> just adding new method to strings.

I think that's true. And even it it would, we can add it to
__future__. Of course, % will stay possible to Python 3.0.72
(as <>). 

> I don't think I have ability to write corresponding pep or patch.
> If somebody can do it it will be great.

I haven't got the ability for a pep either, but maybe we can get
somewhere together?

I will have to wait til next monday at least, because of my exams.
Then I may try to write a PEP.
Any volunteers?

yours,
Gerrit.

-- 
65. If the gardener do not work in the garden and the product fall off,
the gardener shall pay in proportion to other neighboring gardens. 
        -- Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list