Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the original variable name of variable passed to a function

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.

like image 573
Acorn Avatar asked May 01 '10 11:05

Acorn


People also ask

What is the variable name that is used by a function to receive passed value?

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.

How do you pass a variable name as an argument in Python?

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.

Can a function and variable have the same name?

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!


2 Answers

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'] 
like image 140
Ivo Wetzel Avatar answered Oct 24 '22 09:10

Ivo Wetzel


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 
like image 31
propjk007 Avatar answered Oct 24 '22 09:10

propjk007