0

Is there a simple way to get the names of the parameters passed to a Python function, from inside the function?

I'm building an interactive image processing tool that works at the Python command line.

I'd like to be able to do this:

beta = alpha * 2;  # double all pixel values in numpy array  
save(beta)         # save image beta in filename "beta.jpg"  

The alternative is to make the user explicitly type the filename, which is extra typing I'd like to avoid:

beta = alpha * 2;  # double all pixel values in numpy array  
save(beta, "beta") # save image beta in filename "beta.jpg"  
nerdfever.com
  • 1,652
  • 1
  • 20
  • 41

2 Answers2

2

Sadly, you cannot.

How to get the original variable name of variable passed to a function

However, you COULD do something like this

def save(**kwargs):
    for item in kwargs:
        print item #This is the name of the variable you passed in
        print kwargs[item] #This is the value of the variable you passed in.
save(test='toast')

Although, it is probably better practice to do this as such

def save(name,value):
    print name
    print value

save("test","toast")
ollien
  • 4,418
  • 9
  • 35
  • 58
1

You can't get the "name" of a parameter, but you could do something like this to pass the name and the value in a dictionary:

save({"beta": alpha*2})

Now, inside the save() function:

def save(param):
    # assuming Python 2.x
    name  = param.keys()[0]
    # assuming Python 3.x
    name  = next(param.keys())
    value = param[name]

Notice that in general, in a programming language you're not interested in the name of a parameter, that's irrelevant - what matters is its value.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • In 3.x you could just do list(param.keys()). – ollien Aug 18 '14 at 23:38
  • @ollien yep, but that won't return the first (and only) key in the dict. But surely, a solution that works for 2.x and 3.x would be: `list(param.keys())[0]` – Óscar López Aug 18 '14 at 23:40
  • 1
    @ÓscarLópez `next(iter(param))` will work identically on both – Jon Clements Aug 18 '14 at 23:40
  • That might be useful if I were writing a program, but the idea is that the user (non-programmer, but math aware) is at the command line doing math on images. Asking them to deal with dictionary syntax is too much, I think. – nerdfever.com Aug 19 '14 at 00:42
  • @nerdfever.com Then pass two parameters to the function, and forget about trying to obtain the parameter's name (anyway that's a bad idea). Besides, in Python we use dictionaries all the time, the syntax will be familiar to anyone with a minimum of experience with the language. – Óscar López Aug 19 '14 at 00:49