0

I would like to print variables values in python. e.g:

a=3
b=5
print 'blah blah: a = {a}, b = {b}'.format(a=a, b=b)

result is:

blah blah: a = 3, b = 5

My question is how to do it in a short elegant and readable manner.

e.g., is there a way to write something like (pseudo code below)

print 'blah blah: {a}, {b}'.format(a,b)

to get the same result?

Thanks! (BTW: i am using python 2.7)

EDIT (clarification): For logging purpose, sometimes i have many variables that i would like to print, so i prefer not doing something like

print 'a={}, b={}, c={},...'.format(a,b,c...) 

because it is a source for bugs (i.e. I just want to specify the varaible name in the string itself and not care about the order of the variables).

e.g., ultimatly, something that looks like

print 'blah blah: {a}, {b}, {c}, {d}, {e}, {f}'.format(c,e,a,f,d,b)

with a result like:

blah blah: a=3, b=5, c=7, d=22, e=2, f=532
Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74
  • It looks like your problem is that you have to repeat `a` and `b` in `a=a, b=b`? – David Robinson Sep 18 '14 at 10:39
  • yes, i find it not elegant to repeat the name of the argument 4 times in order to print its value. – Yuval Atzmon Sep 18 '14 at 10:41
  • 1
    The problem is that the objects themselves don't know what name[s] they are bound to. If you want something like that you have to use a namespace (i.e. dict). – wim Sep 18 '14 at 11:00
  • This reminds me of the MacroPy library, whose [`log`](https://github.com/lihaoyi/macropy#tracing) function seems to do what you want. `log[a]` prints out "a -> 3" (or something similar, I haven't actually tried it myself) – Kevin Sep 18 '14 at 12:32

3 Answers3

3

You can use your second approach with **locals() instead of a, b. locals() returns a dict containing all local variables. ** unpacks it so you can use it in function calls (function(**{'a': 3, 'b': 4, 'c': 14}) is the same as function(a=3, b=4, c=14))

>>> a = 3
>>> b = 4
>>> c = 14
>>> print 'a = {a}, b = {b}'.format(**locals())
a = 3, b = 4

To avoid 'a = {a}' you can do something like

print '{a}, {b}'.format(**{k:'{} = {}'.format(k,v) for (k,v) in locals().iteritems()})
Yuval Atzmon
  • 5,645
  • 3
  • 41
  • 74
semptic
  • 645
  • 4
  • 15
1

If you know the order that a and b will be in, you don't need to pass them as named arguments in your formatting:

a = 3
b = 5

print('blah blah: a = {}, b = {}'.format(a, b))

Alternatively you could store your variables in a dictionary as below and then use **kwargs unpacking when passing the dict to format.

d = dict(a=3, b=5)

print('blah blah: a = {a}, b = {a}'.format(**d))
Community
  • 1
  • 1
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
0
import inspect

class fdict(dict):
    def __init__(self, dct):
        for k, v in dct.items():
            self[k] = "{} = {}".format(k, v)

def flocals():
    frame = inspect.currentframe()
    return fdict(frame.f_back.f_locals)

def localformat(string):
    frame = inspect.currentframe()
    dct = fdict(frame.f_back.f_locals)
    return string.format(**dct)

Then import localformat anywhere you want and use this:

>>> a = 5
>>> b = 6
print(localformat('{a}, {b}'))

or call the flocals() to get a string to pass to format.