Search code examples
pythonformatlocals

Manipulate value before inserting it with format(**locals()) in python


Is it possible to manipulate a local variable before using it in .format() with **locals() without making a new variable? So something that has the same effect as this:

medium="image"
size_name="double"
width=200
height=100
width2=width*2
height2=height*2
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals())

But more elegant, without creating the width2 and height2 variables. I tried this:

medium="image"
size_name="double"
width=200
height=100
print "A {size_name} sized {medium} is {width2} by {height2}".format(**locals(),height2=height*2,width2=width*2)

But it throws an error "SyntaxError: invalid syntax" at the first comma after locals().


Solution

  • Just change the order:

    print "A {size_name} sized {medium} is {width2} by {height2}".format(height2=height*2,width2=width*2,**locals())
    

    Star arguments always come after normal ones.

    To make this answer less trivial, this is what I have in my standard repertoire:

    import string
    
    def f(s, *args, **kwargs):
        """Kinda "variable interpolation". NB: cpython-specific!"""
        frame = sys._getframe(1)
        d = {}
        d.update(frame.f_globals)
        d.update(frame.f_locals)    
        d.update(kwargs)
        return string.Formatter().vformat(s, args, d)    
    

    It can be applied to your example like this:

     print f("A {size_name} sized {medium} is {0} by {1}", width*2, height*2)
    

    local (and global) variables are passed in automatically, expressions use numeric placeholders.