Python throwing exception for function I didn't call - python

I have a function with the following logic:
def align(val, al): # This is technically imported from a separate file
return (val + (al - 1)) & -al
def compileFont(font, output, audiobank_off=0):
# Get used slot counts
icount = font.instSlotCount()
pcount = font.percSlotCount()
xcount = font.sfxSlotCount()
# Calculate head offset table size
current_pos = (2 + icount) * packspecs.pointerSize()
current_pos = align(current_pos, 16)
To be clear, current_pos is an integer by the last line. When it gets to that last line, though, Python ends up throwing the following exception:
Exception has occurred: TypeError (note: full exception trace is
shown but execution is paused at: <module>)
object of type 'int' has no len()
File "tools/assemble_sound.py", line 311, in compileFont
current_pos = align(current_pos, 16)
File "tools/assemble_sound.py", line 1020, in main
compileFont(font, f, aboff)
File "tools/assemble_sound.py", line 1136, in <module> (Current frame)
main()
I have no idea how len() is coming into play here. I double-checked and the align() function doesn't even call len(). Has anyone ever seen this before? What do I do to troubleshoot this?
Edit: I've added some more of the code and stacktrace to provide additional context. In terms of the types, current_pos is of type int.

The traceback was apparently the right clue. For some reason, when I ran this in VS Code, the exception stacktrace it showed was incomplete (as posted above). When I ran it from the command line, I got this:
Traceback (most recent call last):
File "oot/tools/assemble_sound.py", line 1136, in <module>
main()
File "oot/tools/assemble_sound.py", line 1020, in main
compileFont(font, f, aboff)
File "oot/tools/assemble_sound.py", line 311, in compileFont
current_pos = align(current_pos, 16)
File "~/.local/lib/python3.9/site-packages/makeelf/type/align.py", line 8, in align
full = ceil(len(b) / alignment)
TypeError: object of type 'int' has no len()
This pointed me in the right direction that it was calling the wrong align() method. VS Code couldn't step into align(), so I wasn't able to figure it out until I tried the command line.

Related

How to solve a list indexi error in python

Hellor pythoneers,
I was doing a python program where it reads a group of circles of a file and, once it demands information to the user of a certain circle, determine whether this circle is an inner circumference, an outer circumference or a secant one.
However, i'm experiencing an error I've never seen before.
Traceback (most recent call last):
File "d:\Exercici.py", line 68, in <module>
main()
File "d:\Exercici.py", line 41, in main
x=io.obtReal(i)
File "d:\modul_lect_escr.py", line 93, in obtReal
return float(sequencia[i])
IndexError: list index out of range
I know for a fact the error is in this line of code:
def main():
M=20
N=3
mat=np.zeros((M,N),float)
nomf="circumferencies.txt"
io.obrirFitxer(nomf)
i=0
x=io.obtReal(i) <------
y=io.obtReal(i) <------ Error
radi=io.obtReal(i) <------
while not(x==-999.999 and y==999.999 and radi==999.999):
i=i+1
mat[i,0]=x
mat[i,1]=y
mat[i,2]=radi
x=io.obtReal(i)
y=io.obtReal(i)
radi=io.obtReal(i)
num_circumferencies=i
The function called obtReal comes from a library I was given to read files. Here's the extract of the function:
def obtReal(i): # 1st test ok
return float(sequencia[i])
If anyone has any clue to where the error is, I'd love to hear their opinion.

Python 2 to 3, error converting a list(zip(*aList)[1])

I have a small chunk of code which not being a python guru I am not sure what it is really 'doing', but it fails under python3:
if indSoundsToPlay:
indSoundsToPlay = list(indSoundsToPlay)
indSoundsToPlay.sort()
soundsToPlay = list(zip(*indSoundsToPlay)[1]) <-- fails
soundsToPlay.reverse() # since played from back to front
self.playSounds(soundsToPlay)
This worked fine in Python2, but upon converting it did not like the list zip line at all. So I converted that line to:
soundsToPlay = list(zip(*indSoundsToPlay))
It was okay with that, I am not sure what the list zip * is really doing in python. Though the error subsided but now I realized that I painted myself into either a) another error or b) a new error just near the same code. The slice of code that now breaks is :
What error I get now is on the function call to playSounds:
def playSounds(self, sounds):
"""Play one or more of a set of sounds; played in order from last to first.
"""
if not sounds:
return
soundFunc = sounds.pop(-1)
soundFunc()
if sounds:
self._soundTimer.start(_SoundInterval, self.playSounds, sounds)
KeyVar('tcc', 'AxisCmdState') <bound method AxisStatusWdg.setAxisCmdState of <TUI.TCC.StatusWdg.AxisStatus.AxisStatusWdg object .!toplevel46.!statuswdg.!axisstatuswdg>>(*(['Drifting', 'Drifting', 'Drifting'],), **{'isCurrent': True, 'keyVar': KeyVar('tcc', 'AxisCmdState', 3, str)}) failed: 'tuple' object is not callable
Traceback (most recent call last):
File "/Users/st/TUI3/RO/AddCallback.py", line 77, in safeCall2
return func(*args, **kwargs)
File "/Users/st/TUI3/TUI/TCC/StatusWdg/AxisStatus.py", line 300, in setAxisCmdState
self.playSounds(soundsToPlay)
File "/Users/st/TUI3/TUI/TCC/StatusWdg/AxisStatus.py", line 359, in playSounds
soundFunc()
TypeError: 'tuple' object is not callable
KeyVar('tcc', 'AxisCmdState') <bound method AxisStatusWdg.setAxisCmdState of <TUI.TCC.StatusWdg.AxisStatus.AxisStatusWdg object .!toplevel46.!statuswdg.!axisstatuswdg>>(*(['Tracking', 'Tracking', 'Tracking'],), **{'isCurrent': True, 'keyVar': KeyVar('tcc', 'AxisCmdState', 3, str)}) failed: 'tuple' object is not callable
Traceback (most recent call last):
File "/Users/st/TUI3/RO/AddCallback.py", line 77, in safeCall2
return func(*args, **kwargs)
File "/Users/st/TUI3/TUI/TCC/StatusWdg/AxisStatus.py", line 300, in setAxisCmdState
self.playSounds(soundsToPlay)
File "/Users/st/TUI3/TUI/TCC/StatusWdg/AxisStatus.py", line 359, in playSounds
soundFunc()
TypeError: 'tuple' object is not callable
I don't know if it's what I did to indSoundsToPlay with the changing of that list(zip command or if it is a separate error in general. So not really sure where to start with this one besides learning what list(zip(* means in python.

Using VS Code to debug python files. Exception thrown on breakpoint and breakpoint is ignored

Tried with multiple different python files. Every time I try to use the debugger in vs code and set breakpoints the breakpoint gets ignored and exception gets raised and the script continues on. I've been googling and tinkering for over 2 hours and can't seem to figure out what's going on here. Tried rebooting PC, running vs code as admin, uninstall/reinstall the python extension for vs code. Tried to dig into the files mentioned in the traceback and pinpointed the function that seems to be raising the exception but I can't figure out where it's being called from or why it's raising the exception. I'm still new-ish to Python. Debugging works properly on my laptop but for whatever reason my desktop is having this issue.
Traceback (most recent call last):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 529, in _original_file_to_client
return cache[filename]
KeyError: 'c:\\users\\joel\\local settings\\application data\\programs\\python\\python37-32\\lib\\runpy.py'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 330, in _on_run
self.process_net_command_json(self.py_db, json_contents)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_process_net_command_json.py", line 190, in process_net_command_json
cmd = on_request(py_db, request)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_process_net_command_json.py", line 771, in on_stacktrace_request
self.api.request_stack(py_db, request.seq, thread_id, fmt=fmt, start_frame=start_frame, levels=levels)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_api.py", line 214, in request_stack
if internal_get_thread_stack.can_be_executed_by(get_current_thread_id(threading.current_thread())):
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_comm.py", line 661, in can_be_executed_by
py_db, self.seq, self.thread_id, frame, self._fmt, must_be_suspended=not timed_out, start_frame=self._start_frame, levels=self._levels)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_net_command_factory_json.py", line 213, in make_get_thread_stack_message
py_db, frames_list
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_net_command_factory_xml.py", line 175, in _iter_visible_frames_info
new_filename_in_utf8, applied_mapping = pydevd_file_utils.norm_file_to_client(filename_in_utf8)
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 531, in _original_file_to_client
translated = _path_to_expected_str(get_path_with_real_case(_AbsFile(filename)))
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 221, in _get_path_with_real_case
return _resolve_listing(drive, iter(parts))
File "c:\Users\Joel\.vscode\extensions\ms-python.python-2020.7.96456\pythonFiles\lib\python\debugpy\_vendored\pydevd\pydevd_file_utils.py", line 184, in _resolve_listing
dir_contents = cache[resolved_lower] = os.listdir(resolved)
PermissionError: [WinError 5] Access is denied: 'C:\\Users\\Joel\\Local Settings'
So I get this traceback every time a breakpoint is hit. Taking a peek at the "_original_file_to_client" function in "pydevd_file_utils.py" we get this:
def _original_file_to_client(filename, cache={}):
try:
return cache[filename]
except KeyError:
translated = _path_to_expected_str(get_path_with_real_case(_AbsFile(filename)))
cache[filename] = (translated, False)
return cache[filename]
I wasn't able to figure out where this function was being called from or what the expected output was supposed to be. Any help with this would be greatly appreciated!
Edit: Forgot to mention I'm using Windows 10 if it wasn't obvious from the trace
This is a similar question. The spaces in the filename cause this problem:
"Local Settings", "application data"

How to execute twitter.Api.PostUpdate in loop?

This code executes with error:
# some constants and auth before, looks not important
topPosts = reddit.get_subreddit('funny').get_top(limit=3)
for post in topPosts:
twitter.PostUpdate(status = post.title, media = post.url)
Console log:
Traceback (most recent call last):
File "script.py", line 17, in <module>
twitter.PostUpdate(status = post.title, media = post.url)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twitter/api.py", line 990, in PostUpdate
media_additional_owners)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/twitter/api.py", line 1132, in UploadMediaChunked
boundary = bytes("--{0}".format(uuid4()), 'utf-8')
TypeError: str() takes at most 1 argument (2 given)
If I do just post.label in loop it works perfectly.
If I execute only one (w/o loop) PostUpdate it works perfectly.
I think it's happening because PostUpdate is asynchronous, but can't figure out how to fix it. Please help.
This is a bug in python-twitter library and it's fixed in this PR. The problem is that bytes in python2 equals to str and accepts only one argument while in python3 bytes requires encoding as a second argument.

Strange error involving "AttributeError: 'NoneType' object has no attribute 'append' "

so i am trying to parse out a text file by converting it to a list and splitting each item in the list at the space.
i have created a test variable to run this part of the code by itself.
my code in the spyder editor:
test = ['NC_009142.1_03_012_002_001 560', 'NC_017586.1_13_009_003_001 555', 'NC_016111.1_13_010_003_001 555']
ListOfLinesParsed = test
PN_List = []
counter_iterative = 0
while counter_iterative < len(ListOfLinesParsed):
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
counter_iterative += 1
print PN_List
Which returns an error:
runfile(r'/home/jake/.spyder2/.temp.py', wdir=r'/home/jake/.spyder2')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-
packages/spyderlib/widgets/externalshell/sitecustomize.py", line 493, in runfile
execfile(filename, namespace)
File "/home/jake/.spyder2/.temp.py", line 7, in <module>
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
AttributeError: 'NoneType' object has no attribute 'append'
BUT if i enter the commands directly into the terminal i get no error:
testL = []
testL.append(test[0].split()[0])
testL
['NC_009142.1_03_012_002_001']
testL.append(test[1].split()[0])
testL
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001']
testL.append(test[2].split()[0])
testL
['NC_009142.1_03_012_002_001', 'NC_017586.1_13_009_003_001', 'NC_016111.1_13_010_003_001']
Shouldn't the 2 things be EXACTLY the same? i don't understand why the one in my script is acting any differently than the terminal commands.
The line
PN_List = PN_List.append(ListOfLinesParsed[counter_iterative].split()[0])
is the problem.
list.append is an in-place operation, which returns None, but alters the original list itself. If you assign PN_List to the result, it becomes None. If you don't, then your program will run smoothly. This is why when you try appending things without an assignment, you get the expected answer.

Categories

Resources