Is it possible to get the original variable name of a variable passed to a function? E.g.
foobar = "foo"
def func(var):
print var.origname
So that:
func(foobar)
Returns:
>>foobar
EDIT:
All I was trying to do was make a function like:
def log(soup):
f = open(varname+'.html', 'w')
print >>f, soup.prettify()
f.close()
.. and have the function generate the filename from the name of the variable passed to it.
I suppose if it's not possible I'll just have to pass the variable and the variable's name as a string each time.
EDIT: To make it clear, I don't recommend using this AT ALL, it will break, it's a mess, it won't help you in anyway, but it's doable for entertainment/education purposes.
You can hack around with the
inspect
module, I don't recommend that, but you can do it...Output:
Another way you can try if you know what the calling code will look like is to use
traceback
:code
will contain the line of code that was used to callfunc
(in your example, it would be the stringfunc(foobar)
). You can parse that to pull out the argumentLooks like Ivo beat me to
inspect
, but here's another implementation:Of course, it can be fooled:
Moral: don't do it.
To add to Michael Mrozek's answer, you can extract the exact parameters versus the full code by:
You can't. It's evaluated before being passed to the function. All you can do is pass it as a string.
If you want a Key Value Pair relationship, maybe using a Dictionary would be better?
...or if you're trying to create some auto-documentation from your code, perhaps something like Doxygen (http://www.stack.nl/~dimitri/doxygen/) could do the job for you?