Skip to content

Mypy failing to understand ProgressBar and contextlib.nullcontext() are both context managers #16892

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jamesbraza opened this issue Feb 8, 2024 · 1 comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions

Comments

@jamesbraza
Copy link
Contributor

Bug Report

Mypy 1.8 seems to be failing to combine prompt-toolkit's ProgressBar with contextlib.nullcontext() into a context manager object.

To Reproduce

import contextlib

from prompt_toolkit.shortcuts import ProgressBar

debug_print: bool = True
cm = ProgressBar() if debug_print else contextlib.nullcontext()
reveal_type(cm)  # Revealed type is "builtins.object"
with cm:
    pass

Expected Behavior

No type errors

Actual Behavior

a.py:7:13: note: Revealed type is "builtins.object"
a.py:8:6: error: "object" has no attribute "__enter__"  [attr-defined]
a.py:8:6: error: "object" has no attribute "__exit__"  [attr-defined]

Your Environment

  • Mypy version used: 1.8
  • Mypy command-line flags:
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.12.1
@jamesbraza jamesbraza added the bug mypy got something wrong label Feb 8, 2024
@AlexWaygood AlexWaygood added the topic-join-v-union Using join vs. using unions label Feb 8, 2024
@AlexWaygood
Copy link
Member

AlexWaygood commented Feb 8, 2024

Duplicate of #5512 and #10109.

You can work around the mypy limitation here by using two branches rather than the ternary; for unfortunate historical reasons, mypy has different inference rules for the two ways of writing the same thing:

import contextlib

from prompt_toolkit.shortcuts import ProgressBar

debug_print: bool = True
cm: contextlib.AbstractContextManager[object]
if debug_print:
    cm = ProgressBar()
else:
    cm = contextlib.nullcontext()
reveal_type(cm)  # Revealed type is "contextlib.AbstractContextManager[object]"
with cm:
    pass

@AlexWaygood AlexWaygood closed this as not planned Won't fix, can't repro, duplicate, stale Feb 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-join-v-union Using join vs. using unions
Projects
None yet
Development

No branches or pull requests

2 participants