[Tutor] How do I do this in python?

Kent Johnson kent37 at tds.net
Thu Jun 11 13:08:13 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
>
> of course displaying whatever the actual current values are. For a
> collection object it would make sense to output just the first few
> values.
>
> 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?

I don't know of a straightforward way to do this. You can use
sys._getframe() to get the caller's context but I don't think it will
tell you what variables were used for the call.

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

You could pass keyword arguments:
def show(**kwargs):
  for k, v in kwargs.items():
    print(k, '=', v)

show(a=a, b=b, c=c)

Kent


More information about the Tutor mailing list