简体   繁体   中英

Python: How to get argument's name runtime

in Python : may be so obvious, :) anyway, we are looking for ? , below:

def printname(x):
   print ?,x

>>> a = 1.3
>>> printname(a)
>>> 'a',1.3

so something instead of ? to represent the name of passed argument.
if not that obvious ? any trick or solution?

You can't possibly know this. Objects don't know their names. They can have many names, or none at all, if they're simply an item in another object or list.

It's not impossible . You need to traverse back up stack frames and find the line of code that calls the function.

It's an ok hack to do for debugging, but no way I would use it in real code

Here's a starting point for you:

import inspect
def printname(x):
    print inspect.stack()[1][4]

a = 1.3
printname(a)

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