exc_info inside an except clause will always return not None
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
When calling sys.exc_info from inside an except block, the returned variables will never be None, as defined by the standard library.
However, when trying to use one of the returned variables, mypy throws an error as the type is set as Optional[Type[BaseException]].
Here's the output:
> mypy test.py
test.py:8: error: Item "None" of "Optional[Type[BaseException]]" has no attribute "__name__"
Found 1 error in 1 file (checked 1 source file)
Here's the code I'm using to test:
import sys
# This causes the error
try:
raise Exception
except Exception:
ex, val, _ = sys.exc_info()
print(f"Failed: {ex.__name__}: {val}") # Line 8
# This does not
try:
raise Exception
except Exception:
ex, val, _ = sys.exc_info()
if ex is not None: # Pointless comparison
print(f"Failed: {ex.__name__}: {val}")
I'm not sure if this is a bug or a missing feature?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the test.py reproduction and compare mypy's inferred type for sys.exc_info() inside the except block with the standard-library behavior described in the issue. Confirm the expected result by running mypy on the example: the access to ex.name should not require the pointless None check.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100