[Tutor] How do I do this in python?

A.T.Hofkamp a.t.hofkamp at tue.nl
Thu Jun 11 13:12:02 CEST 2009

Robert Lummis 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
> of course displaying whatever the actual current values are. For a
> collection object it would make sense to output just the first few
> values.

To catch any number of arguments, you could do something like

def show(*args):
   print args

but that gives you just a list of values, like [3, 'john', 'Monday']

Inside a function there is no way of finding out how the values ended up as 
argument (or even whether a value has a name in the first place).

In general, a value may have several names, eg

a = []
b = a

or no names at all like


In other words, what you want is not possible.

> So within the 'show' function definition I have to somehow get a list
> of the literal argument names it was called with and then use the
> names as globals to get the values. How do I do that?

globals is not enough. What if I use show in a function?

If you really insist on using 'show()', you could do

show(('a', a), ('b', b), ('c', c))


def show(*args):
   print '\n'.join(['%s = %s' % a for a in args])

but I think it is too complicated to type, compared to the 'print' statement 

> If this can't be done but there is a completely different way to
> achieve a similar result, what is it?

print "abc=", a, b, c

is what I always use.

> I'm trying to learn python but it's a struggle because the
> documentation is so dispersed. If there is a solution to this

> question, what documentation could I have looked at to find it on my
> own?

Everything is documented at docs.python.org.
(your Python version may be the cause of your problems here though)

> BTW I'm using python 3.01 if it matters.

That version is not ready for real use yet.
For learning Python you better use a 2.X version (2.6 is current).


More information about the Tutor mailing list