Skip to content

nullcontext treated as having no __enter__ or __exit__ method #10109

Closed as not planned
@l0b0

Description

@l0b0

Bug Report

Using nullcontext to randomly get a specific context manager results in mypy errors.

To Reproduce

Run mypy on the following code:

$ cat test.py 
from contextlib import nullcontext
from random import getrandbits

with (open("path") if bool(getrandbits(1)) else nullcontext()):
    pass

Expected Behavior

As far as I can tell from looking at contextlib.py it does have __enter__ and __exit__, so this error should not happen.

Actual Behavior

$ mypy test.py 
test.py:4: error: "object" has no attribute "__enter__"  [attr-defined]
test.py:4: error: "object" has no attribute "__exit__"  [attr-defined]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 0.800

  • Mypy command-line flags: None

  • Mypy configuration options from mypy.ini (and other config files):

    [mypy]
    check_untyped_defs = true
    disallow_any_generics = true
    disallow_untyped_defs = true
    no_implicit_optional = true
    show_error_codes = true
    warn_redundant_casts = true
    warn_return_any = true
    warn_unused_ignores = true
    
  • Python version used: 3.8.6

  • Operating system and version: Arch Linux

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions