Skip to content

Spurious error on bare yield in a context manager under strict-optional #1958

Description

@gnprice

Running mypy --strict-optional on the mypy codebase itself, we get this error:

mypy/build.py: note: In member "wrap_context" of class "State":
mypy/build.py:1170: error: Yield value expected

The function in question looks like this:

    @contextlib.contextmanager
    def wrap_context(self) -> Iterator[None]:
        save_import_context = self.manager.errors.import_context()
        self.manager.errors.set_import_context(self.import_context)
        try:
            yield
        except CompileError:
            raise
        except Exception as err:
            report_internal_error(err, self.path, 0)
        self.manager.errors.set_import_context(save_import_context)
        self.check_blockers()

This is pretty sensible idiomatic code. Arguably there might be some other appropriate annotation to write for the return type; bracketing that question, it looks to be perfectly well-typed code that shouldn't produce an error. It's also not immediately clear to me how to work around it, except I guess with a # type: ignore.

I suspect this is related to the complicated treatment we give in some places to None as a return type -- cf #1509, #299, #359 -- and that treating None in a more regular way as discussed in #1278 and #1847 would fix it.

It may also be related to #1933, but I haven't yet read through that discussion to understand what's going on there.

Activity

  1. ddfisher commented on Aug 4, 2016

    @ddfisher
    Collaborator

    This no longer appears to be a problem. I think this was fixed by #1980.

  2. ambv commented on Jun 14, 2017

    @ambv
    Contributor

    This is fixed for the function syntax, e.g. this doesn't return an error:

    @contextmanager
    def noop_ctxmgr():
        yield

    However, this still does:

    noop_ctxmgr = contextmanager(lambda: (yield))

    Error:

    f.py:11: error: Cannot infer type argument 1 of "contextmanager"
    f.py:11: error: Yield value expected
    
  3. gvanrossum commented on Jun 14, 2017

    @gvanrossum
    Member

    Can you open a new issue?

  4. ambv commented on Jun 14, 2017

    @ambv
    Contributor

    Will do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions