Reputation: 1782
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"
Upvotes: 0
Views: 79
Reputation: 4766
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")
Upvotes: 2
Reputation: 235994
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.
Upvotes: 1