import json


def get_pip_packages(session, which_pip, restriction=None):
    """Return a list of pip packages.

    Parameters
    ----------
    session : Session instance
        Session in which to execute the command.
    which_pip : str
        Name of the pip executable.
    restriction : {None, 'local', 'editable'}, optional
        If 'local', excluded globally installed packages (which pip has access
        to if "--system-site-packages" was used when creating the virtualenv
        directory). If 'editable', only include editable packages.

    Returns
    -------
    A generator that yields package names.
    """
    # We could use either 'pip list' or 'pip freeze' to get a list
    # of packages.  The choice to use 'list' rather than 'freeze'
    # is based on how they show editable packages.  'list' outputs
    # a source directory of the package, whereas 'freeze' outputs
    # a URL like "-e git+https://github.com/[...]".
    cmd = [which_pip, "list", "--format=json"]
    if restriction in ["local", "editable"]:
        cmd.append("--{}".format(restriction))
    out, _ = session.execute_command(cmd)
    return (p["name"] for p in json.loads(out))