[Python-ideas] str.format utility function

Gerald Britton gerald.britton at gmail.com
Sat May 9 01:27:15 CEST 2009


fwiw:

    one = 'slower'
    two = 'yours'
    "my str is %(one)s than %(two)s" % locals()

is slower than:

    "my str is %(one)s than %(two)s" % {"one":faster, "two":yours}

probably because of the overhead of the function call to locals().
Basically I find using locals() this way is just lazy programming,
since you hope your variables are in there somewhere.  If someone
changes them later, your string expression may fail.  I'd rather be
explicit about what I'm doing.


On Fri, May 8, 2009 at 6:05 PM, Dag Moxnes <dagmoxnes at hotmail.com> wrote:
> Hi list,
>
> I'm sorry if this has been discussed before, but I did not find any
> references. I've been playing abit with the new str.format function. I
> really like the syntax and simplicity.
>
> However, when simply printing named variables in locals() or a class, I
> quite common use-case, I find it a bit too complicated with the **:
>
> "Local variable var1 is %(var1)s" % locals()
>
> vs
>
> "Local variable var1 is {var1}".format(**locals())
>
> and
>
> "Instance variable var2 is %(var2)s" % self.__dict__
>
> vs
>
> "Instance variable var2 is {var2}" % **self.__dict__
>
> Therefore I have made myself a utility funcion:
>
> def easyformat(s, data):
>     try:
>         return s.format(**data)
>     except TypeError:
>         return s.format(**data.__dict__)
>
> so that I can do the following:
>
> "Local variable var1 is {var1}".format(**locals())
>
> and
>
> "Instance variable var2 is %(var2)s" % self
>
> Should a function similar to this (maybe with a better name) be included
> included in some standard library?
>
> -Dag
>
> ________________________________
> En om gangen eller alle på én gang? Få oppdateringer fra vennene dine på ett
> sted.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
>



-- 
Gerald Britton



More information about the Python-ideas mailing list