Accessing a variable's name [duplicate] - python

This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 4 months ago.
I'm trying to access a variable's name. For example, if I call a function to print a list (printL)
and want to print my list's name "A_minus_B":
def printL (xlist):
print "****************************"
print "name of list"
print (" entries : "),len(xlist)
print xlist
print "****************************"
return()
How can I get the function to print "A_minus_B" instead of "name of list", the name I used when calling the function printL(A_minus_B)?

You can't.* The detailed reasons are discussed in the Python language reference, but basically what Python does when you call printL(A_minus_B) is take the value that has been labeled A_minus_B and create a new label, xlist, that happens to refer to the same thing. From that point on, the label xlist has absolutely no connection to the other label A_minus_B, and in fact, the value which has been labeled A_minus_B or xlist or whatever has no connection to any of the names that have been used to label it.
*Well, you can, by using some deep "Python voodoo"... you would basically have to tell Python to read the piece of source code where you call printL(A_minus_B) and extract the variable name from there. Normally that's the kind of thing you probably shouldn't be doing (not because you're a beginner, but because it usually indicates you've designed your program the wrong way), but debugging is one of those cases where it's probably appropriate. Here's one way to do it:
import inspect, pprint
def print_values(*names):
caller = inspect.stack()[1][0]
for name in names:
if name in caller.f_locals:
value = caller.f_locals[name]
elif name in caller.f_globals:
value = caller.f_globals[name]
else:
print 'no such variable: ' + name
# do whatever you want with name and value, for example:
print "****************************"
print name
print (" entries : "),len(value)
print value
print "****************************"
The catch is that when you call this function, you have to pass it the name of the variable you want printed, not the variable itself. So you would call print_values('A_minus_B'), not print_values(A_minus_B). You can pass multiple names to have them all printed out, for example print_values('A_minus_B', 'C_minus_D', 'foo').

Alternate way to do it:
list_dict = {} #creates empty dictionary
list_dict['list_a'] = [1,2,3,4,5,6] # here you create the name (key)
nice_name = 'list_b'
list_dict[nice_name] = [7,8,9,10,11,12] # here you use already existing string as name (key)
def list_info(ld):
for key in sorted(ld):
print "****************************"
print key
print " entries : " ,len(ld[key])
print ld[key]
print "****************************"
list_info(list_dict)

Related

Can you find an item from a list from the item's name in python?

So I was wondering if it was possible to find an item from a list by it's name. I am working on a very simple programming language, and with variables, there are two lists:
var_name = []
variable_data = []
And I have created an algorithm for assigning variables to these lists if you enter a command to assign a variable. Here is the code:
if 'var:> ' in user_input:
varnames.append(user_input.replace('var:> ', "").split(', ', 1)[0])
variable_data.append(re.sub(r'.*, ', "", user_input))
And if you're wondering, the code in my language for making a variable is:
var:> var_name, var_data
But, coding things like printing and inputs do not support variables because I need to create some sort of translator that can get an item from a list from a string input. For example, if there was a variable named x in my programming language, can you make some sort of translator that finds the x item in the list from a string named x?
For example:
If you wanted to print a variable, or:
print:var> x
Is there a form to create some sort of translator that translates that x and takes it to the "x" item in the variable name list?
Also, I was considering using a dictionary for this, so if its easier, you could make a method for that too.
Thanks.
Try using dictionary. Its a map that translates key to its value. Key must be immutable value like string, and value can be any python data-type. Dictionary suits perfectly for your application.
dict = {}
if 'var:> ' in user_input:
key = user_input.replace('var:> ', "").split(', ', 1)[0]
value = re.sub(r'.*, ', "", user_input)
dict[key] = value
# dict = {'var_name':'var_data'}
To get data for x. Use regex to get x from your input. Then get from dictionary
key = re.search(r'var>(?P<key>.*)', d).group('key').strip()
value = dict.get(key, "Variable not defined yet")
# gives value of x if exist, else return "Variable not defined yet"

parsing variable name into functions, python

I am making webscraper of a sort, and i made simple function where you pars xpath of an element and if its a multiple elements a number for list index.
But i want to do some debugging, some times function isnt working, and i made simple try/except so it will give me some sort of info why it failed instead of whole code going to dead stop
this is the function:
def getting_company(xpath, number):
try:
data_element = driver.find_elements_by_xpath(str(xpath))
all_elements = len(data_element)
elemet_text = data_element[int(number)].text
print(" this is range of a list : " + str(all_elements))
return elemet_text
except:
data_element = driver.find_elements_by_xpath(str(xpath))
print(" this is range of a list : " + str(all_elements))
return "not found"
Now, i am interested, when i use that function and assing it to some variable lets say
random_varriable = getting_company(xpath, number)
is there any way to include name "random variable" into the function automaticly, somehow to parse that paticular name without adding string "random variable"?
So i want if i call:
variable1 = getting_company(xpath, number)
variable2 = getting_company(xpath, number)
and if function fails:
"variable 1 had x len of elements" "variable 2 had x len of
elements"
but without typing "variable 1 " + function return after the function rather to have that incoporated into the function.
I am hoping that i was clear... i dont know how to explane it better since english isnt my first language.

Python Function Arguments: NameError argumant is not defined

I am new to Python. I want to call a function that detect null value in a excel table and passing "Fail" to a variable stat.
def checkBlank(tb):
book=xlrd.open_workbook(reportFile)
sheet = book.sheet_by_name(tb)
s= "Pass"
for i in range(sheet.nrows):
row = sheet.row_values(i)
for cell in row:
if cell =='':
s="Fail"
return s
print checkBlank('Sheet1')
Above code will return "Fail"
but below code will give: NameError: name 'stat' is not defined
def checkBlank(tb,stat):
book=xlrd.open_workbook(reportFile)
sheet = book.sheet_by_name(tb)
s= "Pass"
for i in range(sheet.nrows):
row = sheet.row_values(i)
for cell in row:
if cell =='':
s="Fail"
print checkBlank('Sheet1', stat)
print stat
How can I assign "Fail" to stat if the function find the empty cell?
It appears that you are attemping to pass a variable into a function to be used as the return value. This is not Pythonic and in general will not work. Instead, your function should be returning a value and you should be assigning that value to a new "variable."
def function(arg):
if arg:
return 'Pass'
else:
return 'Fail'
status = function(False)
print(status) # 'Fail'
In Python, you don't want to try to write a function that calls by reference, because variables don't exist in Python in the same way that they do in C. Instead, what we have are names which are more akin to placeholders and can be used to retrieve objects. This article and many other Stack Overflow answers go into this in more depth.

Converting list of variables to strings [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I have a list of commands that I want to iterate over so I've put those commands into a list. However, I want to also use that list as strings to name some files. How do I convert variable names to strings?
itemIDScore = """SELECT * from anytime;"""
queryList = [itemIDScore, accountScore, itemWithIssue, itemsPerService]
for x in queryList:
fileName = x+".txt"
cur.execute(x) #This should execute the SQL command
print fileName #This should return "itemIDScore.txt"
I want fileName to be "itemIDScore.txt" but itemIDScore in queryList is a SQL query that I'll use elsewhere. I need to name files after the name of the query.
Thanks!
I don't think you may get name of the variable as string from the variable object. But instead, you may create the list of string of your variables as:
queryList = ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService']
Then you may access the value of variable from the variable name string using the globals() function as:
for x in queryList:
fileName = "{}.txt".format(x)
data = globals()[x]
cur.execute(data)
As the globals() document say:
Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).
As far as I know, there is no easy way to do that, but you could simply use a dict with what currently are variable names as keys, e.g.:
queries = {
'itemIDScore': 'sql 1',
'accountScore': 'sql 2',
...
}
for x in queries:
fileName = x + ".txt"
cur.execute(queries[x])
print fileName
This would also preserve your desired semantics without making the code less readable.
I think you would have an easier time storing the names explicitly, then evaluating them to get their values. For example, consider something like:
itemIDScore = "some-long-query-here"
# etc.
queryDict = dict( (name,eval(name)) for name in ['itemIDScore', 'accountScore', 'itemWithIssue', 'itemsPerService'] )
for k in queryDict:
fileName = k+".txt"
cur.execute(queryDict[k])
You can use the in-built str() function.
for x in queryList:
fileName = str(x) + ".txt"
cur.execute(x)

Passing a list name and an item into a function to search the list. ValueError: substring not found

I'm fairly new to Python but am ok with programming (although haven't done any for about 5 years).
I've searched but can't find anything to answer my problem:
I have a number of lists, each with values in them, I'm trying to create a generic function that takes 2 values that searches a list, the 2 values are obviously the list name, and the string to search for in that list:
list0 = ["name","date","cat","dog"]
list1 = ["house","chair","table"]
list2 = ["tv","dvd","computer","mouse"]
usersearchlist = raw_input("Enter list name: ")
usersearchitem = raw_input("Enter item to search for: ")
def searchmemory(usersearchlist,usersearchitem):
return usersearchlist.index(usersearchitem)
I then call the function:
print "I found", searchmemory(usersearchlist,usersearchitem)
I'm getting the "ValueError: substring not found" because the function call is taking the literal string passed into the function and not referencing the value contained inside of it.
Hope that makes sense, am I doing something totally wrong?
try
lists = {"list0" : ["name","date","cat","dog"],
"list1" : ["house","chair","table"],
"list2" : ["tv","dvd","computer","mouse"]}
usersearchlist = raw_input("Enter list name: ")
usersearchitem = raw_input("Enter item to search for: ")
def searchmemory(usersearchlist, usersearchitem):
if (usersearchlist in lists and usersearchitem in lists[usersearchlist]):
return lists[usersearchlist].index(usersearchitem)
else:
return -1
This stores all the lists in a dictionary and checks if the value exists first so you shouldn't get a ValueError
I would prefer to put the lists in a dictionary similar to #SimplyKiwi 's answer.
Alternatively, you can also achieve it with globals():
print "I found", searchmemory(globals().get(usersearchlist, []), usersearchitem)
Be warned though in this case, you are implicitly giving the user access to all the global variables. In most scenario, this is not what you would want the users to be able to do.

Categories