parsing variable name into functions, python - 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.

Related

How can I properly use variables returned in other function / method?

Please bare with me since I am just starting to learn coding, and Python is my first language to go.
I struggle and can't really get to understand how the functions work.
I can't manage to call it and use later on when I need it in another function.
Can someone please help me understand the depth of it ?
My code doesn't work and I can't manage to understand how to grab the results from a function, in order to use those results for the end purpose.
This is something I tried in the project I am working on:
manly_coded_bag = []
female_coded_bag = []
feminine_coded_words = [
"agree",
"affectionate",
"child",
"cheer",
]
masculine_coded_words = [
"active",
"adventurous",
"aggressive",
"ambitios",
]
explanations = {
"feminine-coded": (
"This job ad uses more words that are subtly coded as feminine than words that are subtly coded as masculine"
),
"masculine-coded": (
"This job ad uses more words that are subtly coded as masculine than words that are subtly coded as feminine."
)
def men_coded_words(masc_bag, text):
add_text = text
man_coded_bag = masc_bag
for word in masculine_coded_words:
if word in add_text:
man_coded_bag.append(word)
return man_coded_bag
def women_coded_words(fem_bag, text):
add_text = text
woman_coded_bag = fem_bag
for word in feminine_coded_words:
if word in add_text:
woman_coded_bag.append(word)
return woman_coded_bag
def analise_and_explain_results(text, count_man, count_fem):
count_man_words = count_man
count_man_words = len(man_coded_bag)
count_woman_words = count_fem
count_woman_words = len(woman_coded_bag)
coding_score = count_woman_words - count_man_words
strengths_of_coding = ""
if coding_score == 0:
if count_man_words:
strengths_of_coding = "neutral"
else:
strengths_of_coding = "empty"
elif coding_score > 0:
strengths_of_coding = "feminine-coded"
else:
strengths_of_coding = "masculine-coded"
return count_man_words, count_woman_words, strengths_of_coding
def get_results(text):
user_input = text
user_input = input("add text here:").lower()
res = analise_and_explain_results(text, man_coded_bag,
woman_coded_bag)
# i am trying to use the returned variable strengths_of_coding and
is not accesible.
explain_results = explanations[strengths_of_coding]
return res, explain_results
get_results("random text added here, really whatever for testing purposes")
Right, so when I am calling get_results('text'), I get this error and I know where it is coming from, "name 'strengths_of_coding' is not defined", but I just don't know how to access that variable...
I'm stuck here and a little bit frustrated because I understand it's a noob mistake, yet still I can't get the hang of it after a week of stress and frustration.
Any feedback is welcome.
So it's hard to explain everything if you barely have any knowledge in OOP or coding in general. But in python, the return value of a function can be anything. None, a integer, a list, tuple, dictionary, object. Can even be a class definition. Only by looking at it, will you know exactly. That is called duck-typing; "If it walks like a duck and it quacks like a duck, then it must be a duck"
In this case, your analise_and_explain_results function does not return one thing, but several since it does this:
return count_man_words, count_woman_words, strengths_of_coding
So it actually returns a tuple with those three values inside. And these variables are scoped to that specific function, you cannot use them outside that function anymore. Note: For the sake of simplicity; let's just stick to not using them outside of the function since it's bad practice.
In your code, you then do this:
res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)
Which means that res at this point is actually the tuple holding the three values you are interested in. You have several ways to resolve this. But this easiest to follow is to just assign the values of variables like this:
count_man_words, count_woman_words, strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)
This basically unpacks the tuple into three different values since it basically does this:
a, b, c = (1, 2 ,3)
Where before you did:
d = (1, 2, 3)
Unpacking is easy, as long as the item you unpack holds as many items as you're trying to assign;
a, b, c = d
If you have trouble grasping OOP and python I would suggest you learn to walk, before you run, which you're doing now IMO.
Follow some tutorials or videos explaining OOP and python. Or combine them like they do on realpython.
strengths_of_coding is only defined inside the analise_and_explain_results function. When you return the values of that function, they are no longer attached to the names you used inside the function
return count_man_words, count_woman_words, strengths_of_coding can be also written as return (count_man_words, count_woman_words, strengths_of_coding) - it means the return value of the function is a tuple with 3 elements that are values of each of the variables, and that tuple is assigned to res in res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)
Value of variable called strengths_of_coding inside the function is available as res[2] in get_results after you do the assignment to res
res = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag) turns res into a tuple with 3 elements. strengths_of_coding is the 3rd element in this tuple. So, you access it as res[2]. In python, when you return multiple stuff to one variable, the variable turns into a tuple. You can provide multiple variables to take each return. e,g, count_man_words, count_woman_words, strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag). Or, if you only need that one return then, strengths_of_coding = analise_and_explain_results(user_input, man_coded_bag, woman_coded_bag)[2].
Sorry for a late answer. This is how I ended up fixing my code with the kind help from people who answered, I have came to understand where I was making mistakes.
This is how I fixed my code, using the example above, just in case someone else struggle with grasping the basics.
As a bonus for any new beginner finding this useful, something I learned from someone else.
The last print statement is a very useful way to debug your code:
print("results are: %s" % results)
For example adding it at the end, you can see if you ended up getting the right results, like in my example, or you can add it in your code to see what results you return in each functions and so on.
user_input = "Active, child, whatever random text, testing"
text = user_input.lower()
# declare the coded words, feminine and masculine
feminine_coded_words = [
"agree",
"affectionate",
"child",
"cheer",
]
masculine_coded_words = [
"active",
"adventurous",
"aggressive",
"ambitios",
]
# declare explanations to use when we explain the results to the user.
explanations = {
"feminine-coded": (
"This job ad uses more words that are subtly coded as feminine than words that are subtly coded as masculine"
),
"masculine-coded": (
"This job ad uses more words that are subtly coded as masculine than words that are subtly coded as feminine."
),
"neutral": ("this is neutral"),
"empty": ("empty text"),
}
# initiate two empty variable where we add our coded words, when we find them.
def men_coded_words(text):
add_text = text
manly_coded_bag = []
for word in masculine_coded_words:
if word in add_text:
manly_coded_bag.append(word)
return manly_coded_bag
def women_coded_words(text):
add_text = text
feminine_coded_bag = []
for word in feminine_coded_words:
if word in add_text:
feminine_coded_bag.append(word)
return feminine_coded_bag
def feminine_counted_words(text):
woman_coded_bag = women_coded_words(text)
return len(woman_coded_bag)
def masculine_counted_words(text):
man_coded_bag = men_coded_words(text)
return len(man_coded_bag)
def coding_score(text):
count_fem_words = feminine_counted_words(text)
count_masc_words = masculine_counted_words(text)
return count_fem_words - count_masc_words
def explain_results(text):
strengths_of_coding = ""
count_masc_words = masculine_counted_words(text)
coding_score_results = coding_score(text)
if coding_score_results == 0:
if count_masc_words:
strengths_of_coding = "neutral"
else:
strengths_of_coding = "empty"
elif coding_score_results > 0:
strengths_of_coding = "feminine-coded"
else:
strengths_of_coding = "masculine-coded"
return strengths_of_coding
def get_results(text):
strenght_of_coding = explain_results(text)
return explanations[strenght_of_coding]
results = get_results(text)
print("results are: %s" % results)

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"

Function Not Printing Desired Output

I am having issues with creating a function that takes a list of tuples and then returns one string which is the first character of each tuple. Below is my current code, but nothing it happening, I do not get a syntax error. Any help would be appreciated.
lst_of_tups = ([('hello', 'all'), ('music', 'playing'), ('celebration', 'station')])
def build_string(lst_of_tups):
final_str = ""
for tup in list_of_tups:
for item in tup:
final_str = final_str + item[0]
return final_str
print build_string
**** expected output: hampcs****
those string manipulation functions are error-prone: they define lots of variables, can return within inner loops, have unexpected side-effects...
Once you're used to list comprehensions, you can create such programs easily & with great execution performance (string concatenation is slow). One way:
def build_string(lst_of_tups):
return "".join([x[0] for y in lst_of_tups for x in y])
basically, it's just 2 loops (flattening the data) within a list comprehension to extract each first character from every string, joined together using str.join to rebuild the string.
Once you reach a return statement in a function, the function ends for good. The line
print build_string
cannot be reached. (Another problem is that the name build_string is not defined.)
Use your function like this:
result = build_string(lst_of_tups) # calls your function and puts the return value in the result variable
print result # print the result
Of course, the intermediary variable result is not necessary, you could just issue print build_string(lst_of_tups) as well.

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.

Accessing a variable's name [duplicate]

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)

Categories