[Tutor] How do I do this in python?

Kent Johnson kent37 at tds.net
Thu Jun 11 16:46:26 CEST 2009


On Wed, Jun 10, 2009 at 9:43 PM, Robert Lummis<robert.lummis at gmail.com> wrote:
> I want to write a function that I can use for debugging purposes that
> prints the values of whatever list of object references it is given as
> arguments, without knowing in advance how many object references it
> will be called with or what they might be. For example, the call:
> show(a,b,c) would output the values of the arguments like this:
>
>    a = 3
>    b = 'john'
>    c = 'Monday'
>
> while show (x) would output (for example):
>
>    x = 3.14

Here is a pretty clean solution. It passes names rather than values,
then looks the values up in the caller's stack frame. Written for
Python 2.x but should work for 3.x if you change the prints.

In [1]: import sys
In [11]: def show(names):
   ....:     frame = sys._getframe(1)
   ....:     for name in names.split():
   ....:         if name in frame.f_locals:
   ....:             print name, '=', frame.f_locals[name]
   ....:         else:
   ....:             print name, 'not found'

In [12]: a=1

In [13]: b='foo'

In [14]: c='bar'

In [15]: show('a b c')
a = 1
b = foo
c = bar

In [18]: show('a x')
a = 1
x not found

Kent


More information about the Tutor mailing list