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.
The data passed to the function are referred to as the "actual" parameters. The variables within the function which receive the passed data are referred to as the "formal" parameters.
Use a dict. If you really really want, use your original code and do locals()[x][0] = 10 but that's not really recommended because you could cause unwanted issues if the argument is the name of some other variable you don't want changed. Show activity on this post. Show activity on this post.
You cant because if you have example(), 'example' is a pointer to that function. This is the right answer. There are function pointers, which are variables. But also, all function names are treated as const function pointers!
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 any way, 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...
import inspect def foo(a, f, b): frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] string = inspect.getframeinfo(frame[0]).code_context[0].strip() args = string[string.find('(') + 1:-1].split(',') names = [] for i in args: if i.find('=') != -1: names.append(i.split('=')[1].strip()) else: names.append(i) print names def main(): e = 1 c = 2 foo(e, 1000, b = c) main()
Output:
['e', '1000', 'c']
To add to Michael Mrozek's answer, you can extract the exact parameters versus the full code by:
import re import traceback def func(var): stack = traceback.extract_stack() filename, lineno, function_name, code = stack[-2] vars_name = re.compile(r'\((.*?)\).*$').search(code).groups()[0] print vars_name return foobar = "foo" func(foobar) # PRINTS: foobar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With