简体   繁体   中英

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?

Based on the documentation: Python Docs - traceback module

The first argument to traceback.print_exc isn't the exception, it is a depth limit of how many deep the traceback goes. You are hitting an exception within the traceback module itselse, since it expects the first argument to be a limit.

Your code needs to be:

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

The exception data is kept as a thread global in sys.exc_info() which is what traceback.print_exc() uses.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM