etingof / pysnmp

Python SNMP library
http://snmplabs.com/pysnmp/
BSD 2-Clause "Simplified" License
576 stars 195 forks source link

Exceptions should not be singletons in Python 3 #280

Open kouli opened 5 years ago

kouli commented 5 years ago

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
etingof commented 4 years ago

That's a great point, thank you!

lextm commented 7 months ago

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.