Reputation: 210485
Often I find myself doing something like this when debugging:
print a.foo, b.bar, c.baz
It prints something like
1 3 4
which is correct but not as useful as it could be.
What I ideally want to be printed is something like:
a.foo: 1, b.bar: 3, c.baz: 4
which is easily accomplished via
print 'a.foo:', a.foo, 'b.bar:', b.bar, 'c.baz:', c.baz
but now I'm writing the same thing twice!
Can I use some kind of Python trick like introspection to avoid repeating myself?
I'm imagining a magical printexp
like this:
printexp('a.foo', 'b.bar', 'c.baz')
but I'm not familiar with Python's introspection capabilities so I'm not sure how to go about doing this.
Upvotes: 0
Views: 68
Reputation: 25855
This is not exactly what you asked for, but if you want to do this with "ordinary" objects (by which I mean objects of user-defined classes), you may want to simply do this:
print a.__dict__
Upvotes: 0
Reputation: 210485
I figured it out myself:
>>> def printexp(*exps, **kwargs):
import sys
import inspect
import itertools
locs = dict(inspect.currentframe().f_back.f_locals)
locs.setdefault('_file', kwargs['file'] if 'file' in kwargs else sys.stdout)
exec('print' + ' ' + '>>' + '_file' + ', ' + (', ' + '_file' + '.write(",")' + ' or ').join(map(lambda exp: '"' + exp.replace('"', '\\"') + ':' + '"' + ', ' + exp, exps)) + '', None, locs)
>>> x = 5
>>> printexp('x', 'x')
x: 5, x: 5
Upvotes: 1