Python: How to get argument's name runtime

こ雲淡風輕ζ 提交于 2020-01-03 03:15:10

问题


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?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/16732955/python-how-to-get-arguments-name-runtime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!