pysnmp icon indicating copy to clipboard operation
pysnmp copied to clipboard

Exceptions should not be singletons in Python 3

Open kouli opened this issue 6 years ago • 2 comments

Due to exception chaining introduced in Python 3 (probably), exceptions should not be "singletons": i.e. each exception raised should be a separate individual instance of Exception. Please, do not use those singletons as e.g. in pysnmp.proto.errind (get rid of the requestTimedOut instance and always instantiate exceptions using RequestTimedOut()). See output (exception's traceback) of the following example to see why it is bad - singleton obtains an accumulated traceback from all places it was raised at:

class TimeoutError(Exception): pass
timeoutError = TimeoutError()

def work():
    raise timeoutError

def main(m):
    for i in range(10):
        try:
            work()
        except TimeoutError:
            if i >= m: # ignore first `m` timeouts
                raise

main(15)
main(3) # raises a TimeoutError with 18 "cycles" in its traceback

kouli avatar Jun 24 '19 01:06 kouli

That's a great point, thank you!

etingof avatar Sep 24 '19 17:09 etingof

I don't think this is a valid report.

Commonly the code looks like

            raise error.StatusInformation(
                errorIndication=errind.decryptionError
            )

Since none of the instances from errind is called directly by raise, the trackback information is not accumulated.

lextm avatar Feb 11 '24 05:02 lextm