This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 4 months ago.
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 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
Looks like Ivo beat me to inspect, but here's another implementation:
import inspect
def varName(var):
lcls = inspect.stack()[2][0].f_locals
for name in lcls:
if id(var) == id(lcls[name]):
return name
return None
def foo(x=None):
lcl='not me'
return varName(x)
def bar():
lcl = 'hi'
return foo(lcl)
bar()
# 'lcl'
Of course, it can be fooled:
def baz():
lcl = 'hi'
x='hi'
return foo(lcl)
baz()
# 'x'
Moral: don't do it.
Another way you can try if you know what the calling code will look like is to use traceback:
def func(var):
stack = traceback.extract_stack()
filename, lineno, function_name, code = stack[-2]
code will contain the line of code that was used to call func (in your example, it would be the string func(foobar)). You can parse that to pull out the argument
You can't. It's evaluated before being passed to the function. All you can do is pass it as a string.
#Ivo Wetzel's answer works in the case of function call are made in one line, like
e = 1 + 7
c = 3
foo(e, 100, b=c)
In case that function call is not in one line, like:
e = 1 + 7
c = 3
foo(e,
1000,
b = c)
below code works:
import inspect, ast
def foo(a, f, b):
frame = inspect.currentframe()
frame = inspect.getouterframes(frame)[1]
string = inspect.findsource(frame[0])[0]
nodes = ast.parse(''.join(string))
i_expr = -1
for (i, node) in enumerate(nodes.body):
if hasattr(node, 'value') and isinstance(node.value, ast.Call)
and hasattr(node.value.func, 'id') and node.value.func.id == 'foo' # Here goes name of the function:
i_expr = i
break
i_expr_next = min(i_expr + 1, len(nodes.body)-1)
lineno_start = nodes.body[i_expr].lineno
lineno_end = nodes.body[i_expr_next].lineno if i_expr_next != i_expr else len(string)
str_func_call = ''.join([i.strip() for i in string[lineno_start - 1: lineno_end]])
params = str_func_call[str_func_call.find('(') + 1:-1].split(',')
print(params)
You will get:
[u'e', u'1000', u'b = c']
But still, this might break.
You can use python-varname package
from varname import nameof
s = 'Hey!'
print (nameof(s))
Output:
s
Package below:
https://github.com/pwwang/python-varname
For posterity, here's some code I wrote for this task, in general I think there is a missing module in Python to give everyone nice and robust inspection of the caller environment. Similar to what rlang eval framework provides for R.
import re, inspect, ast
#Convoluted frame stack walk and source scrape to get what the calling statement to a function looked like.
#Specifically return the name of the variable passed as parameter found at position pos in the parameter list.
def _caller_param_name(pos):
#The parameter name to return
param = None
#Get the frame object for this function call
thisframe = inspect.currentframe()
try:
#Get the parent calling frames details
frames = inspect.getouterframes(thisframe)
#Function this function was just called from that we wish to find the calling parameter name for
function = frames[1][3]
#Get all the details of where the calling statement was
frame,filename,line_number,function_name,source,source_index = frames[2]
#Read in the source file in the parent calling frame upto where the call was made
with open(filename) as source_file:
head=[source_file.next() for x in xrange(line_number)]
source_file.close()
#Build all lines of the calling statement, this deals with when a function is called with parameters listed on each line
lines = []
#Compile a regex for matching the start of the function being called
regex = re.compile(r'\.?\s*%s\s*\(' % (function))
#Work backwards from the parent calling frame line number until we see the start of the calling statement (usually the same line!!!)
for line in reversed(head):
lines.append(line.strip())
if re.search(regex, line):
break
#Put the lines we have groked back into sourcefile order rather than reverse order
lines.reverse()
#Join all the lines that were part of the calling statement
call = "".join(lines)
#Grab the parameter list from the calling statement for the function we were called from
match = re.search('\.?\s*%s\s*\((.*)\)' % (function), call)
paramlist = match.group(1)
#If the function was called with no parameters raise an exception
if paramlist == "":
raise LookupError("Function called with no parameters.")
#Use the Python abstract syntax tree parser to create a parsed form of the function parameter list 'Name' nodes are variable names
parameter = ast.parse(paramlist).body[0].value
#If there were multiple parameters get the positional requested
if type(parameter).__name__ == 'Tuple':
#If we asked for a parameter outside of what was passed complain
if pos >= len(parameter.elts):
raise LookupError("The function call did not have a parameter at postion %s" % pos)
parameter = parameter.elts[pos]
#If there was only a single parameter and another was requested raise an exception
elif pos != 0:
raise LookupError("There was only a single calling parameter found. Parameter indices start at 0.")
#If the parameter was the name of a variable we can use it otherwise pass back None
if type(parameter).__name__ == 'Name':
param = parameter.id
finally:
#Remove the frame reference to prevent cyclic references screwing the garbage collector
del thisframe
#Return the parameter name we found
return param
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.doxygen.nl/) could do the job for you?
I wondered how IceCream solves this problem. So I looked into the source code and came up with the following (slightly simplified) solution. It might not be 100% bullet-proof (e.g. I dropped get_text_with_indentation and I assume exactly one function argument), but it works well for different test cases. It does not need to parse source code itself, so it should be more robust and simpler than previous solutions.
#!/usr/bin/env python3
import inspect
from executing import Source
def func(var):
callFrame = inspect.currentframe().f_back
callNode = Source.executing(callFrame).node
source = Source.for_frame(callFrame)
expression = source.asttokens().get_text(callNode.args[0])
print(expression, '=', var)
i = 1
f = 2.0
dct = {'key': 'value'}
obj = type('', (), {'value': 42})
func(i)
func(f)
func(s)
func(dct['key'])
func(obj.value)
Output:
i = 1
f = 2.0
s = string
dct['key'] = value
obj.value = 42
Update: If you want to move the "magic" into a separate function, you simply have to go one frame further back with an additional f_back.
def get_name_of_argument():
callFrame = inspect.currentframe().f_back.f_back
callNode = Source.executing(callFrame).node
source = Source.for_frame(callFrame)
return source.asttokens().get_text(callNode.args[0])
def func(var):
print(get_name_of_argument(), '=', var)
If you want to get the caller params as in #Matt Oates answer answer without using the source file (ie from Jupyter Notebook), this code (combined from #Aeon answer) will do the trick (at least in some simple cases):
def get_caller_params():
# get the frame object for this function call
thisframe = inspect.currentframe()
# get the parent calling frames details
frames = inspect.getouterframes(thisframe)
# frame 0 is the frame of this function
# frame 1 is the frame of the caller function (the one we want to inspect)
# frame 2 is the frame of the code that calls the caller
caller_function_name = frames[1][3]
code_that_calls_caller = inspect.findsource(frames[2][0])[0]
# parse code to get nodes of abstract syntact tree of the call
nodes = ast.parse(''.join(code_that_calls_caller))
# find the node that calls the function
i_expr = -1
for (i, node) in enumerate(nodes.body):
if _node_is_our_function_call(node, caller_function_name):
i_expr = i
break
# line with the call start
idx_start = nodes.body[i_expr].lineno - 1
# line with the end of the call
if i_expr < len(nodes.body) - 1:
# next expression marks the end of the call
idx_end = nodes.body[i_expr + 1].lineno - 1
else:
# end of the source marks the end of the call
idx_end = len(code_that_calls_caller)
call_lines = code_that_calls_caller[idx_start:idx_end]
str_func_call = ''.join([line.strip() for line in call_lines])
str_call_params = str_func_call[str_func_call.find('(') + 1:-1]
params = [p.strip() for p in str_call_params.split(',')]
return params
def _node_is_our_function_call(node, our_function_name):
node_is_call = hasattr(node, 'value') and isinstance(node.value, ast.Call)
if not node_is_call:
return False
function_name_correct = hasattr(node.value.func, 'id') and node.value.func.id == our_function_name
return function_name_correct
You can then run it as this:
def test(*par_values):
par_names = get_caller_params()
for name, val in zip(par_names, par_values):
print(name, val)
a = 1
b = 2
string = 'text'
test(a, b,
string
)
to get the desired output:
a 1
b 2
string text
Since you can have multiple variables with the same content, instead of passing the variable (content), it might be safer (and will be simpler) to pass it's name in a string and get the variable content from the locals dictionary in the callers stack frame. :
def displayvar(name):
import sys
return name+" = "+repr(sys._getframe(1).f_locals[name])
If it just so happens that the variable is a callable (function), it will have a __name__ property.
E.g. a wrapper to log the execution time of a function:
def time_it(func, *args, **kwargs):
start = perf_counter()
result = func(*args, **kwargs)
duration = perf_counter() - start
print(f'{func.__name__} ran in {duration * 1000}ms')
return result
I have a test, that checks an element on a page: if element A is presented, test(function) returns A and runs another function A. If element B is presented, test(function) returns B and runs another function B. How can I do it in Python? I think of using dictionary and something like "if" expression, but I hardly imagine, how to do it. Thanks in advance!
I don't have exact code, just something like this :/
from Pages import SearchHelper
def finding_pop(browser):
pop_click = SearchHelper(browser)
pop_click.go_to_site()
#element = finding_element_function.get_text()
return element
if element =='A':
#function test_A_click must be run
else:
#function test_B_click must be run
def test_A_click(browser):
pop_click = SearchHelper(browser)
pop_click.go_to_site()
logs = pop_click.setting_logs_raw('performance')
result = pop_click.for_logs(pop_click.log_filter, logs)
binded = pop_click.searching_params_in_logs_pops(result, 'bind_to')
ignored = pop_click.searching_params_in_logs_pops(result, 'ignore_to')
if binded == None and ignored == None:
handles, url, url1 = pop_click.opened_in_new_window()
assert handles > 1
assert url != url1
def test_B_click(browser):
pop_click = SearchHelper(browser)
pop_click.go_to_site()
logs = pop_click.setting_logs_raw('performance')
result = pop_click.for_logs(pop_click.log_filter, logs)
binded = pop_click.searching_params_in_logs_pops(result, 'bind_to')
ignored = pop_click.searching_params_in_logs_pops(result, 'ignore_to')
if binded == None and ignored == None:
handles, url, url1 = pop_click.opened_in_current_window()
print(url, url1)
assert handles > 1
assert url != url1
Remember that the return statement should always be at the end of function, because on the return statement the function ends and no further parts of the function get executed. So in the finding_pop fucntion when you write return element, that is where your function ends. The if/else statements below return element are not being executed.
For this perticular scenario I think you don't need a return statemnet inside your finding_pop function , since you're finding_pop function is returning element and then you're performing the if/else on element inside the same the same function.
You can simply change your finding_pop function to:
def finding_pop(browser):
pop_click = SearchHelper(browser)
pop_click.go_to_site()
element = finding_element_function.get_text()
if element =="A":
test_A_click(browser)
elseif element =="B":
test_B_click(browser)
But if you are really in need of a return statement then you need to introduce a separate runner function that will take in the return of finding_pop as an input and then perform if/else to choose the next function to perform.
So it'll be as:
def finding_pop(browser):
pop_click = SearchHelper(browser)
pop_click.go_to_site()
element = finding_element_function.get_text()
return element
def chose_func_A_or_b(browser):
element = finding_pop(browser)
if element == "A":
test_A_click(browser)
if element == "B":
test_B_click(browser)
I built the following module for identifying if a file exists in a directory based on its size and name, all so I can use it in a different part of a project. When I try to use the function for the first time, it works great. But when I call it again, different variables with different parameters return the first answer. What am I missing?
Module:
import os
from stat import *
import math
CORRECT_PATH = ''
FLAG = 1
def check_matching(pathname, desired_file_name):
global FLAG
if desired_file_name in pathname:
FLAG = 0
return pathname
def walktree(dirz, desired_file_name, size):
global CORRECT_PATH
global FLAG
for f in os.listdir(dirz):
try:
if FLAG:
pathname = os.path.join(dirz, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recourse into it
walktree(pathname, desired_file_name, size)
elif S_ISREG(mode):
# It's a file, call the callback function
new_size = int(os.path.getsize(pathname))
if (new_size - int(size)) < math.fabs(0.95*int(size)):
CORRECT_PATH = check_matching(pathname, desired_file_name)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
else:
try:
CORRECT_PATH = CORRECT_PATH.replace('\\', '/')
return True, CORRECT_PATH
except WindowsError as w:
#print w
if w[0] == 5:
return True, CORRECT_PATH
except WindowsError as e:
pass
# print e
# if e[0] == 5:
# return True, CORRECT_PATH # add correct path now
return False, ''
Now when I call the this code (This is an example, I'm using two different text files, with different sizes and different names which are saved on my local computer):
import LS_FINAL_FOUR
ans = LS_FINAL_FOUR.walktree("C:/", "a_test", 38)
print ans # (True, 'C:/a_test.txt')
ans1 = LS_FINAL_FOUR.walktree("C:/", "a_sample", 1000000)
print ans1 # (True, 'C:/a_test.txt')
Both return the same output. Very frustrating. Does anyone know the reason behind this and how to solve it?
Edit: I'm almost certain it's a problem with the module, but I just can't lay my finger on it.
You need to reset the FLAG to 1 each time walktree is called. As it is, the FLAG is set to zero once when you find the first file. Each subsequent call, you re-access this initial result, since if FLAG is false, you run this code again:
else:
try:
CORRECT_PATH = CORRECT_PATH.replace('\\', '/')
return True, CORRECT_PATH
Since CORRECT_PATH is stored as a global, the initial answer persists after your walktree method returns.
I'd suggest fixing up the code by not using globals. Just make check_matching return a result directly to walktree, and don't cache the path result after walktree returns.
I am working on a pointless guessing game for skill development. I decided to write code to read users and their scores from a file, then write a function to check whether there username is currently in the file already:
import getpass
user = getpass.getuser()
def userExists(username):
f = open('score.txt', 'rU')
for line in f:
row = line.split('\r\n')
info = row[0].strip('\r\n').split(':')
username = info[0]
if user==username:
uExists = True
break
else:
uExists = False
return usExists
f.close()
At first I had the return values, True and False inside the loop which caused problems, so I set a variable to the value and return that instead.
The score.txt looks like and uses the format of:
user:10:50
userB:5:10
But whenever I use this function userExists('nonExistingUser') it always returns True regardless if the user exists or not, any ideas what I'm doing wrong?
Your logic is a little cluttered, so first I present a slightly cleaned-up version whose operation should (if I am correct) be pretty much the same.
import getpass
user = getpass.getuser()
def userExists(username):
f = open('score.txt', 'rU')
for line in f:
username = line.rstrip().split(':')[0]
if user==username:
return True
return False
f.close()
The rstrip() method call returns the same string without any trailing whitespace; the split() call returns a list of the three strings separated by colons, and you already know what the [0] does.The uexists flag turns out to be unnecessary. I presumed you wanted to remove all white space from the end of the line?
This does have the unfortunate problem that the file never gets closed (as does your suggested code). A relatively easy (but rather advanced) fix is to use the file as a context manager.
import getpass
user = getpass.getuser()
def userExists(username):
with open('score.txt', 'rU') as f:
for line in f:
username = line.rstrip().split(':')[0]
if user==username:
return True
return False
This ensures that no matter how the function returns the file will be properly closed without needing to explicitly call its close() method.
In addition to what JAvier pointed out, you're also setting uExists but returning usExists it should be along these lines:
def userExists(username):
f = open('score.txt', 'rU')
uExists = False
for line in f:
row = line.split('\r\n')
info = row[0].strip('\r\n').split(':')
if user==info[0]:
uExists = True
break
else:
uExists = False
f.close()
return uExists
Depending upon your version of python, I'd also look into the with statement to clean up that f.close().
Use files with the with statement, that way the file is automatically closed when you exit the with block even if you leave it with an exception or a return statement.
def userExists(username):
with open('score.txt', 'rU') as f:
for line in f:
if line[:line.find(':')] == username:
return True
return False
You could simplify userExists like so:
def userExists(username):
with open('score.txt','rU') as score:
return username+':' in score.read()
You may wish to use a regular expression instead of username+':'