I got an error message that didn't make sense in a script that scrapes websites for Ethereum prices.
This is where the exception was raised:
# part of a loop
....
element = browser.find_element_by_css_selector(selector)
data = element.text.split('\n')
symbol, price = tuple(data[-2].split(' '))
assert symbol == 'Ξ'
total_price += float(price)
price_list.append((total_price, dict_with_data))
# in top namespace
price_list.sort() #<-- the acual line that raised an exception
This is the false traceback:
Traceback (most recent call last):
File ..., line 142, in <module>
assert symbol == 'Ξ'
TypeError: '<' not supported between instances of 'dict' and 'dict'
The error message is correct and I already fixed it, but it says the error happaned in the line assert symbol == 'Ξ' which is obviously wrong because it happened in the line price_list.sort(). Why is this traceback giving me false information?
Related
def get_response(intents_list, intents_json):
tag = intents_list[0]['intent']
list_of_intents = intents_json['intents']
for i in list_of_intents:
if i['tag'] == tag:
ans = random.choice(i['responses'])
break
return ans
Says that tag = intents_list[0]['intent'] is the problem.
Once I run the code, I'm supposed to be able to interact with it however it displays the error after I type anything in the terminal. I tried using an intents_list.sort() function, but still giving me the error.
edit:
full error displays
Traceback (most recent call last):
File "/Users/xymonaesquivel/Desktop/ECE 495 Final Project/chatbot.py", line 61, in <module>
res = get_response(ints, intents)
File "/Users/xymonaesquivel/Desktop/ECE 495 Final Project/chatbot.py", line 43, in get_response
tag = intents_list[0]['intent']
TypeError: 'NoneType' object is not subscriptable
My test:
def test_search(self):
"""
Test of searching content in a file.
"""
tmp_path = '/tmp/test2.txt'
content = 'HelloWorld! Too Much!'
f = open(tmp_path, "w")
f.write(content)
f.close()
file_utils = bob.FileUtils()
search_result = file_utils.search(tmp_path, 'Much')
The code I am testing:
def search(self, file: str, search: str) -> bool:
"""
Search for a string in a file.
"""
print('-------')
print(file)
print(search)
try:
with open(file, 'rb', 0) as f, mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as s:
r = s.find(search) != -1
except FileNotFoundError:
self.Error().file_not_found_error(file)
except OSError:
self.Error().os_error(file)
except Exception as err:
self.Error().exception(file, err)
finally:
f.close()
return r
From what I read I needed to use the mode rb but it still throws this error:
$ python3 -m unittest 1 ⨯
............................................-------
/tmp/test2.txt
Much
Unexpected error opening /tmp/test2.txt is TypeError("a bytes-like object is required, not 'str'")
ERROR:root:Unexpected error opening /tmp/test2.txt is TypeError("a bytes-like object is required, not 'str'")
Traceback (most recent call last):
File "/home/user/Projects/SiteNetSoft/Bob/BobToolServerImageBuilder/bob.py", line 498, in search
r = s.find(search) != -1
TypeError: a bytes-like object is required, not 'str'
E....
======================================================================
ERROR: test_search (test_bob.TestFileUtils)
Test of searching content in a file.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/user/Projects/SiteNetSoft/Bob/BobToolServerImageBuilder/bob.py", line 498, in search
r = s.find(search) != -1
TypeError: a bytes-like object is required, not 'str'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/user/Projects/SiteNetSoft/Bob/BobToolServerImageBuilder/test_bob.py", line 521, in test_search
search_result = file_utils.search(tmp_path, 'Much')
File "/home/user/Projects/SiteNetSoft/Bob/BobToolServerImageBuilder/bob.py", line 504, in search
self.Error().exception(file, err)
File "/home/user/Projects/SiteNetSoft/Bob/BobToolServerImageBuilder/bob.py", line 543, in exception
sys.exit(1)
SystemExit: 1
----------------------------------------------------------------------
Ran 49 tests in 0.020s
FAILED (errors=1)
When you call search_result = file_utils.search(tmp_path, 'Much') you is sendinga str to this function, but in r = s.find(search) != -1, you are trying to use it as a byte string.
Try to add a b'<STR>' when calling the function, this will convert the str. -> byte-str and solve the problem.
NIT: Always when you see the TypeError: try to compare the types of the inputs, a simple line print(type(<input>)) can help you to understand what is going on.
My program removes the substring 'rotten' from the string list:
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits]
print(remove_rotten(bag_of_fruits))
All tests is completed, but in the end program shows 'Unexpected exception raised':
Traceback (most recent call last):
File "/workspace/default/.venv/lib/python3.10/site-packages/codewars_test/test_framework.py", line 112, in wrapper
func()
File "/workspace/default/tests.py", line 21, in fixed_tests
test.assert_equals(remove_rotten(tst[0]), tst[1], f"Input = {tst[0]}")
File "/workspace/default/solution.py", line 4, in remove_rotten
bag_of_fruits = [x.removeprefix('rotten') for x in bag_of_fruits]
TypeError: 'NoneType' object is not iterable
Try to change the name of the variable to avoid the error
bag_of_fruits = ["apple","rottenBanana","apple"]
def remove_rotten(bag_of_fruits):
# ---- > variable name should be changed
bag_of_fruits_edited = [x.removeprefix('rotten') for x in bag_of_fruits]
return [x.lower() for x in bag_of_fruits_edited]
print(remove_rotten(bag_of_fruits))
I use the Python3.6 and I've been confused about this question for a long time..so here is my code.
def fo(x,y):
z=np.sin(x)+0.05*x**2+np.cos(y)+0.05*y**2
if output == True:
print("%8.4f %8.4f %8.4f" % (x,y,z))
return z
import scipy.optimize as sop
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
Here is the error I get:
Traceback (most recent call last):
File "<ipython-input-12-c7886e35ff4b>", line 1, in <module>
sop.brute(fo,(-10,10.1,5),(-10,10.1,5),finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2811, in brute
if len(lrange[k]) < 3:
TypeError: object of type 'int' has no len()
here's another try:
r1=slice(-10,10.1,5)
r2=slice(-10,10.1,5)
sop.brute(fo,r1,r2,finish = None)
and the error:
Traceback (most recent call last):
File "<ipython-input-48-230c07265998>", line 1, in <module>
sop.brute(fo,r1,r2,finish = None)
File "C:\ProgramData\Anaconda3\lib\site-packages\scipy\optimize\optimize.py", line 2804, in brute
N = len(ranges)
TypeError: object of type 'slice' has no len()
sop.brute(fo,(r1,r2),finish = None)
TypeError: fo() missing 1 required positional argument: 'y'
I'm new to here and sorry if I ask a stupid question but I cant' work it out T.T thx a lot
def fo(p):
x, y = p
z = np.sin(x)+0.05*x**2+np.sin(y)+0.05*y**2
if output == True:
print('%8.4f %8.4f %8.4f' % (x,y,z))
return z
unpack tuple like in the code
In python 3, exceptions can be chained, like this:
try:
7/0
except ZeroDivisionError:
raise ValueError("Invalid division")
# Traceback (most recent call last):
# File "<stdin>", line 2, in <module>
# ZeroDivisionError: division by zero
#
# During handling of the above exception, another exception occurred:
#
# Traceback (most recent call last):
# File "<stdin>", line 4, in <module>
# ValueError: Invalid division
What if I have the following situation:
A class with a method that may either succeed or throw an error.
I have a bunch of instances of that class in a list.
Somewhere I call that method for every instance on the list.
It is enough for one of them to succeed. If every instance fails I throw an error.
Now, if I have to throw an error, I want to print all exceptions thrown during the test of each instance in the list. Code to clarify:
instances_to_test = [instance0, instance1, instance2]
failures = [] # List of all the thrown exceptions
success = False # True if one of the instances in the list succeeds
for instance in instances_to_test:
try:
instance.method_may_raise() # May raise an Error
success = True
break
except Exception as e:
failures.append(e)
if not success:
# ... What to do here ...
An ideal solution to the line in the comment would look something like:
if not success:
raise MultipleFailException("Could not find an adequate instance", parents=failures)
# 0 ------------------------------------
#
# Traceback (most recent call last):
# File "<stdin>", line 6, in <module>
# ValueError: Message of instance0
#
# 1 ------------------------------------
#
# Traceback (most recent call last):
# File "<stdin>", line 6, in <module>
# ValueError: Message of instance1
#
# 2 ------------------------------------
# Traceback (most recent call last):
# File "<stdin>", line 6, in <module>
# ValueError: Message of instance2
#
# During handling of the above exception(s), another exception occurred:
#
# Traceback (most recent call last):
# File "<stdin>", line 12, in <module>
# MultipleFailException: Could not find an adequate instance
Can this be done in a 'clean' way or should I fiddle with the stack trace like in the python 2 days?