0

Can a Python (3) function "know" the literal value of a parameter passed to it?

In the following example, I want the function listProcessor to be able to print the name of the list passed to it:

list01 = [1, 3, 5]
list02 = [2, 4, 6]

def listProcessor(listName):
    """
    Function begins by printing the literal value of the name of the list passed to it
    """

listProcessor(list01)  # listProcessor prints "list01", then operates on the list.
listProcessor(list02)  # listProcessor prints "list02", then operates on the list.
listProcessor(anyListName) # listProcessor prints "anyListName", et cetera…

I've only recently resumed coding (Python 3). So far everything I've tried "interprets" the parameter and prints the list rather than its name. So I suspect I'm overlooking some very simple way to "capture" the literal value of parameters passed to a Python function.

Also, in this example I've used a list's name as the parameter but really want to understand how to capture any type of parameter's literal value.

RBV
  • 1,367
  • 1
  • 14
  • 33
  • `list01` is no more the "name" of your list than "Mr. Secretary-General" is the name of Ban Ki-moon. Why do you need this information? – jscs May 18 '14 at 18:44
  • There is no real way to do that. Functions don't have access to the namespaces of their callers. However, see the duplicate question for a "fake" way to do it. (The reason it's fake is that, as noted in the answer, it is easy to break it.) – BrenBarn May 18 '14 at 18:44
  • Duplicate of: http://stackoverflow.com/questions/544919/can-i-print-original-variables-name-in-python – plocks May 18 '14 at 18:45

1 Answers1

0

while there is something called introspection, which can be used to obtain names of variables in some cases, you're probably looking for a different data structure. if you put your data in a dict, you can have the "labels" in the keys and the "lists" in the values:

d = { "list01": [1, 3, 5],
      "list02": [2, 4, 6] }


def listProcessor(data, key):
    print key
    print data[key]

listProcessor(d, "list01")
Pavel
  • 7,436
  • 2
  • 29
  • 42