0

I have not been able to find an answer or solution to what I think must be simple, but I do not know how to do it.

Here is a cut down snip of what I am trying to do:

from array import *

def print_array(args):
    print 'array =', args
    print 'array name =' ?

    for i in range(len(args)):
        print 'index =', i, 'value =', args[i]

my_array = array('i',[1,2,3,4])
print_array(my_array)

I want to be able to print the name of the array (in this case 'my_array') within the function 'print_array' itself. I know I could pass the 'my_array' as a string argument to the 'print_array' function. But there must be a more Pythonic solution to this?

fredtantini
  • 15,966
  • 8
  • 49
  • 55
Doug Gordon
  • 1
  • 1
  • 1
  • Did you *really* read the answers for "how to get a variable name as string in Python" ? Because, as answered here http://stackoverflow.com/a/18425275/41316, it's just not possible (or, more exactly, it doesn't make any sense in Python). – bruno desthuilliers Dec 18 '14 at 13:29
  • 1
    See also http://stackoverflow.com/q/27545684/3001761. This is a bad idea; Python's names are not properties of the object, they are "tags" applied for referencing the object. Read e.g. http://nedbatchelder.com/text/names.html – jonrsharpe Dec 18 '14 at 13:29
  • Its difficult to see the possible usecase of this. What are you trying to achieve? Perhaps you could pass the name of the array as a second parameter of the `print_array`? – Alex Dec 18 '14 at 13:31
  • Hi Alex, the use case was to add the print_array into a general automation module. Users could call the function as a debugging aid and it would print the name of the array then dump it out etc. I did actually resort to having to pass the name of the array as a second argument to print_array (works fine) but it would have needn nicer for the function to be able to work out the name its self. Thank you every one for all your answers, very much appreciated. - Doug – Doug Gordon Dec 18 '14 at 15:16

0 Answers0