Python Forum
why is this exception being ignored? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: why is this exception being ignored? (/thread-35272.html)



why is this exception being ignored? - Skaperen - Oct-14-2021

Output:
Exception ignored in: <bound method _zopen.__del__ of <zopen2._zopen object at 0x7f3bfca40748>> Traceback (most recent call last): File "/home/phil/zopen2.py", line 696, in __del__ if self.tempfile and self.tempname: # if writing a temporary file do not rename it File "/home/phil/zopen2.py", line 712, in __getattr__ raise AttributeError(f'attribute {name!r} requested of not open instance of class zopen') NameError: name 'name' is not defined Exception ignored in: <bound method _zopen.__del__ of <zopen2._zopen object at 0x7f3bfdc06c88>> Traceback (most recent call last): File "/home/phil/zopen2.py", line 696, in __del__ if self.tempfile and self.tempname: # if writing a temporary file do not rename it File "/home/phil/zopen2.py", line 712, in __getattr__ raise AttributeError(f'attribute {name!r} requested of not open instance of class zopen') NameError: name 'name' is not defined
does anyone know why this exception is being ignored? i don't want to fix why that exception is happening until i know why it is being ignored because it is the only way i can test why the exception is being ignored.


RE: why is this exception being ignored? - Skaperen - Oct-14-2021

Output:
Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'> BrokenPipeError: [Errno 32] Broken pipe
another one. why do exceptions get ignored, especially when my code handles them?

/usr/local/bin/range.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""The range command outputs a range of decimal numbers given 1 to 3 arguments."""
from sys import argv,stderr
def help():
    print(__doc__,file=stderr)
def version():
    print('version 0.0.1',file=stderr)
argv.pop(0)
if argv and argv[0][:2]=='--':
    if '--help' in argv:help()
    if '--version' in argv:version()
    exit(3)
if len(argv) > 3:
    exit('too many numbers for start, end, and increment')
s = []
try:
    for a in argv:
        n = eval(a)
        if not isinstance(n,int):
            exit('all numbers must be integers')
        s.append(n)
    if not s:
        exit('no numbers')
    for n in range(*s):
        print(n)
except ValueError:
    exit('all numbers must be integers')
except KeyboardInterrupt:
    exit('\newww... that tickled!\n')
except BrokenPipeError:
    exit(0)



RE: why is this exception being ignored? - Gribouillis - Oct-15-2021

I could not reproduce the bug with python 3.8.10 in linux. In the original post, I think the exception is ignored because it happened during the execution of a __del__ method. Try to close the zopen2._zopen instance before it is finalized perhaps.


RE: why is this exception being ignored? - DeaD_EyE - Oct-15-2021

Improving bad code to wake up ...
#!/usr/bin/env python3
"""The range command outputs a range of decimal numbers given 1 to 3 arguments."""

import click


@click.command()
@click.argument("start", type=int)
@click.argument("stop", type=int, default=None, required=False)
@click.argument("step", type=int, default=None, required=False)
def count(start, stop=None, step=None):

    if stop is None:
        for value in range(start):
            print(value)

    else:
        if step is None:
            step = 1
        for value in range(start, stop, step):
            print(value)


if __name__ == "__main__":
    count()



RE: why is this exception being ignored? - Skaperen - Oct-15-2021

the zopen2._zopen instance does get closed when zhash is finished reading it. what is "finalized"? the __del__ method is there to have it do any needed close so the files are finished. what else do i need to do with this?

here's what that method has:
#-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------
# support object deletion
#-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------
# if a temporary file is being written, then delete
# what is being written instead of replacing the
# original with what may be an incomplete new file
#-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------.-------
    def __del__(self):
        """This object is being deleted so clean up everything."""
        if self.ready:
            if self.tempfile and self.tempname:
                self.tempfile.close()
                remove(self.tempname)
                self.tempname = None # dereference (not essential since this object is being deleted)
                self.tempfile = None # dereference (not essential since this object is being deleted)
            self.close()
        return
the whole thing is at http://ipal.net/python/zopen.py (32708 bytes, 709 lines)


RE: why is this exception being ignored? - Gribouillis - Oct-16-2021

Read the official documentation of the __del__ method, especially the warning about the precarious condition under which this method si called. From my experience, it is always a bad idea to implement a del method. Many issues can happen, such as the one you encouter here: an attribute of the instance is no longer accessible and this raises an exception.

If you want to ensure that files are closed, use a context protocol for example. It will work more reliably, so implement __enter__() and __exit__() methods for the class. I don't understand why the __exit__ method doesn't impement the logic that you are injecting in __del__ in this code.


RE: why is this exception being ignored? - Skaperen - Oct-16-2021

it does have __enter__() and __exit__() but they are very minimal. i will put the close call in __exit__() and see if that makes it cleaner.