简体   繁体   中英

How get names of passed parameters inside a function

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"  

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")

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM