[Python-ideas] str.format utility function

Terry Reedy tjreedy at udel.edu
Sat May 9 01:52:59 CEST 2009


Dag Moxnes 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())

I see nothing compicated about **. In any case, it is a common idiom 
that Python progrmmers should learn and hopefully become comfortable 
with.  I see nothing gained with
s.easyformat(s, locals()) # over
s.format(**locals)
except a few extra chars to type ;-).

If you were doing that often, you could write

def lform(s): # format caller locals
   l = <locals of caller> # ask on Python list or check python recipies
   return s.format(**l)

> "Instance variable var2 is %(var2)s" % self.__dict__
> 
> vs
> 
> "Instance variable var2 is {var2}" % **self.__dict__\

You meant,
"Instance variable var2 is {var2}".format(**self.__dict__)

Wrapping this seems like a possible method.  For a constant format 
applicable to all instances, override .__str__().

 > def easyformat(s, data):
 >     try:
 >         return s.format(**data)
 >     except TypeError:
 >         return s.format(**data.__dict__)

> Should a function similar to this (maybe with a better name) be
> included in some standard library?

I think not.

Terry Jan Reedy




More information about the Python-ideas mailing list