Search code examples
pythontraceback

Python TypeError when printing traceback of AttributeError using traceback.print_exc()


A reproducible example:

import traceback
X = None
try:
    X.text
except (TypeError, AttributeError) as e:
    traceback.print_exc(e)

This will raise an error at traceback.print_exc(e):

TypeError: '>=' not supported between instances of 'AttributeError' and 'int'

Any suggestion why this happens?


Solution

  • print_exc doesn't take the exception object as an argument, it uses sys.exc_info() to obtain exception information. When you're passing it e, it's interpreting it as a positional argument for limit which expects a type int. I believe if you just remove the argument you'll get the result you're looking for.

    traceback.print_exc documentation